display_server_windows.cpp 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385
  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::alert(const String &p_alert, const String &p_title) {
  73. MessageBoxW(nullptr, (LPCWSTR)(p_alert.utf16().get_data()), (LPCWSTR)(p_title.utf16().get_data()), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
  74. }
  75. void DisplayServerWindows::_set_mouse_mode_impl(MouseMode p_mode) {
  76. if (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_CONFINED) {
  77. WindowData &wd = windows[MAIN_WINDOW_ID];
  78. RECT clipRect;
  79. GetClientRect(wd.hWnd, &clipRect);
  80. ClientToScreen(wd.hWnd, (POINT *)&clipRect.left);
  81. ClientToScreen(wd.hWnd, (POINT *)&clipRect.right);
  82. ClipCursor(&clipRect);
  83. if (p_mode == MOUSE_MODE_CAPTURED) {
  84. center = window_get_size() / 2;
  85. POINT pos = { (int)center.x, (int)center.y };
  86. ClientToScreen(wd.hWnd, &pos);
  87. SetCursorPos(pos.x, pos.y);
  88. SetCapture(wd.hWnd);
  89. }
  90. } else {
  91. ReleaseCapture();
  92. ClipCursor(nullptr);
  93. }
  94. if (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_HIDDEN) {
  95. if (hCursor == nullptr) {
  96. hCursor = SetCursor(nullptr);
  97. } else {
  98. SetCursor(nullptr);
  99. }
  100. } else {
  101. CursorShape c = cursor_shape;
  102. cursor_shape = CURSOR_MAX;
  103. cursor_set_shape(c);
  104. }
  105. }
  106. void DisplayServerWindows::mouse_set_mode(MouseMode p_mode) {
  107. _THREAD_SAFE_METHOD_
  108. if (mouse_mode == p_mode)
  109. return;
  110. mouse_mode = p_mode;
  111. _set_mouse_mode_impl(p_mode);
  112. }
  113. DisplayServer::MouseMode DisplayServerWindows::mouse_get_mode() const {
  114. return mouse_mode;
  115. }
  116. void DisplayServerWindows::mouse_warp_to_position(const Point2i &p_to) {
  117. _THREAD_SAFE_METHOD_
  118. if (!windows.has(last_focused_window)) {
  119. return; //no window focused?
  120. }
  121. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  122. old_x = p_to.x;
  123. old_y = p_to.y;
  124. } else {
  125. POINT p;
  126. p.x = p_to.x;
  127. p.y = p_to.y;
  128. ClientToScreen(windows[last_focused_window].hWnd, &p);
  129. SetCursorPos(p.x, p.y);
  130. }
  131. }
  132. Point2i DisplayServerWindows::mouse_get_position() const {
  133. POINT p;
  134. GetCursorPos(&p);
  135. return Point2i(p.x, p.y);
  136. //return Point2(old_x, old_y);
  137. }
  138. int DisplayServerWindows::mouse_get_button_state() const {
  139. return last_button_state;
  140. }
  141. void DisplayServerWindows::clipboard_set(const String &p_text) {
  142. _THREAD_SAFE_METHOD_
  143. if (!windows.has(last_focused_window)) {
  144. return; //no window focused?
  145. }
  146. // Convert LF line endings to CRLF in clipboard content
  147. // Otherwise, line endings won't be visible when pasted in other software
  148. String text = p_text.replace("\r\n", "\n").replace("\n", "\r\n"); // avoid \r\r\n
  149. if (!OpenClipboard(windows[last_focused_window].hWnd)) {
  150. ERR_FAIL_MSG("Unable to open clipboard.");
  151. }
  152. EmptyClipboard();
  153. Char16String utf16 = text.utf16();
  154. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (utf16.length() + 1) * sizeof(WCHAR));
  155. ERR_FAIL_COND_MSG(mem == nullptr, "Unable to allocate memory for clipboard contents.");
  156. LPWSTR lptstrCopy = (LPWSTR)GlobalLock(mem);
  157. memcpy(lptstrCopy, utf16.get_data(), (utf16.length() + 1) * sizeof(WCHAR));
  158. GlobalUnlock(mem);
  159. SetClipboardData(CF_UNICODETEXT, mem);
  160. // set the CF_TEXT version (not needed?)
  161. CharString utf8 = text.utf8();
  162. mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1);
  163. ERR_FAIL_COND_MSG(mem == nullptr, "Unable to allocate memory for clipboard contents.");
  164. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  165. memcpy(ptr, utf8.get_data(), utf8.length());
  166. ptr[utf8.length()] = 0;
  167. GlobalUnlock(mem);
  168. SetClipboardData(CF_TEXT, mem);
  169. CloseClipboard();
  170. }
  171. String DisplayServerWindows::clipboard_get() const {
  172. _THREAD_SAFE_METHOD_
  173. if (!windows.has(last_focused_window)) {
  174. return String(); //no window focused?
  175. }
  176. String ret;
  177. if (!OpenClipboard(windows[last_focused_window].hWnd)) {
  178. ERR_FAIL_V_MSG("", "Unable to open clipboard.");
  179. };
  180. if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
  181. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  182. if (mem != nullptr) {
  183. LPWSTR ptr = (LPWSTR)GlobalLock(mem);
  184. if (ptr != nullptr) {
  185. ret = String::utf16((const char16_t *)ptr);
  186. GlobalUnlock(mem);
  187. };
  188. };
  189. } else if (IsClipboardFormatAvailable(CF_TEXT)) {
  190. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  191. if (mem != nullptr) {
  192. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  193. if (ptr != nullptr) {
  194. ret.parse_utf8((const char *)ptr);
  195. GlobalUnlock(mem);
  196. };
  197. };
  198. };
  199. CloseClipboard();
  200. return ret;
  201. }
  202. typedef struct {
  203. int count;
  204. int screen;
  205. HMONITOR monitor;
  206. } EnumScreenData;
  207. static BOOL CALLBACK _MonitorEnumProcScreen(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  208. EnumScreenData *data = (EnumScreenData *)dwData;
  209. if (data->monitor == hMonitor) {
  210. data->screen = data->count;
  211. }
  212. data->count++;
  213. return TRUE;
  214. }
  215. static BOOL CALLBACK _MonitorEnumProcCount(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  216. int *data = (int *)dwData;
  217. (*data)++;
  218. return TRUE;
  219. }
  220. int DisplayServerWindows::get_screen_count() const {
  221. _THREAD_SAFE_METHOD_
  222. int data = 0;
  223. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcCount, (LPARAM)&data);
  224. return data;
  225. }
  226. typedef struct {
  227. int count;
  228. int screen;
  229. Point2 pos;
  230. } EnumPosData;
  231. static BOOL CALLBACK _MonitorEnumProcPos(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  232. EnumPosData *data = (EnumPosData *)dwData;
  233. if (data->count == data->screen) {
  234. data->pos.x = lprcMonitor->left;
  235. data->pos.y = lprcMonitor->top;
  236. }
  237. data->count++;
  238. return TRUE;
  239. }
  240. Point2i DisplayServerWindows::screen_get_position(int p_screen) const {
  241. _THREAD_SAFE_METHOD_
  242. EnumPosData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, Point2() };
  243. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcPos, (LPARAM)&data);
  244. return data.pos;
  245. }
  246. typedef struct {
  247. int count;
  248. int screen;
  249. Size2 size;
  250. } EnumSizeData;
  251. typedef struct {
  252. int count;
  253. int screen;
  254. Rect2i rect;
  255. } EnumRectData;
  256. static BOOL CALLBACK _MonitorEnumProcSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  257. EnumSizeData *data = (EnumSizeData *)dwData;
  258. if (data->count == data->screen) {
  259. data->size.x = lprcMonitor->right - lprcMonitor->left;
  260. data->size.y = lprcMonitor->bottom - lprcMonitor->top;
  261. }
  262. data->count++;
  263. return TRUE;
  264. }
  265. Size2i DisplayServerWindows::screen_get_size(int p_screen) const {
  266. _THREAD_SAFE_METHOD_
  267. EnumSizeData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, Size2() };
  268. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcSize, (LPARAM)&data);
  269. return data.size;
  270. }
  271. static BOOL CALLBACK _MonitorEnumProcUsableSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  272. EnumRectData *data = (EnumRectData *)dwData;
  273. if (data->count == data->screen) {
  274. MONITORINFO minfo;
  275. zeromem(&minfo, sizeof(MONITORINFO));
  276. minfo.cbSize = sizeof(MONITORINFO);
  277. GetMonitorInfoA(hMonitor, &minfo);
  278. data->rect.position.x = minfo.rcWork.left;
  279. data->rect.position.y = minfo.rcWork.top;
  280. data->rect.size.x = minfo.rcWork.right - minfo.rcWork.left;
  281. data->rect.size.y = minfo.rcWork.bottom - minfo.rcWork.top;
  282. }
  283. data->count++;
  284. return TRUE;
  285. }
  286. Rect2i DisplayServerWindows::screen_get_usable_rect(int p_screen) const {
  287. _THREAD_SAFE_METHOD_
  288. EnumRectData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, Rect2i() };
  289. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcUsableSize, (LPARAM)&data);
  290. return data.rect;
  291. }
  292. typedef struct {
  293. int count;
  294. int screen;
  295. int dpi;
  296. } EnumDpiData;
  297. enum _MonitorDpiType {
  298. MDT_Effective_DPI = 0,
  299. MDT_Angular_DPI = 1,
  300. MDT_Raw_DPI = 2,
  301. MDT_Default = MDT_Effective_DPI
  302. };
  303. static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Default) {
  304. int dpiX = 96, dpiY = 96;
  305. static HMODULE Shcore = nullptr;
  306. typedef HRESULT(WINAPI * GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT * dpiX, UINT * dpiY);
  307. static GetDPIForMonitor_t getDPIForMonitor = nullptr;
  308. if (Shcore == nullptr) {
  309. Shcore = LoadLibraryW(L"Shcore.dll");
  310. getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : nullptr;
  311. if ((Shcore == nullptr) || (getDPIForMonitor == nullptr)) {
  312. if (Shcore)
  313. FreeLibrary(Shcore);
  314. Shcore = (HMODULE)INVALID_HANDLE_VALUE;
  315. }
  316. }
  317. UINT x = 0, y = 0;
  318. HRESULT hr = E_FAIL;
  319. if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE)) {
  320. hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y);
  321. if (SUCCEEDED(hr) && (x > 0) && (y > 0)) {
  322. dpiX = (int)x;
  323. dpiY = (int)y;
  324. }
  325. } else {
  326. static int overallX = 0, overallY = 0;
  327. if (overallX <= 0 || overallY <= 0) {
  328. HDC hdc = GetDC(nullptr);
  329. if (hdc) {
  330. overallX = GetDeviceCaps(hdc, LOGPIXELSX);
  331. overallY = GetDeviceCaps(hdc, LOGPIXELSY);
  332. ReleaseDC(nullptr, hdc);
  333. }
  334. }
  335. if (overallX > 0 && overallY > 0) {
  336. dpiX = overallX;
  337. dpiY = overallY;
  338. }
  339. }
  340. return (dpiX + dpiY) / 2;
  341. }
  342. static BOOL CALLBACK _MonitorEnumProcDpi(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  343. EnumDpiData *data = (EnumDpiData *)dwData;
  344. if (data->count == data->screen) {
  345. data->dpi = QueryDpiForMonitor(hMonitor);
  346. }
  347. data->count++;
  348. return TRUE;
  349. }
  350. int DisplayServerWindows::screen_get_dpi(int p_screen) const {
  351. _THREAD_SAFE_METHOD_
  352. EnumDpiData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, 72 };
  353. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcDpi, (LPARAM)&data);
  354. return data.dpi;
  355. }
  356. bool DisplayServerWindows::screen_is_touchscreen(int p_screen) const {
  357. #ifndef _MSC_VER
  358. #warning touchscreen not working
  359. #endif
  360. return false;
  361. }
  362. void DisplayServerWindows::screen_set_orientation(ScreenOrientation p_orientation, int p_screen) {
  363. }
  364. DisplayServer::ScreenOrientation DisplayServerWindows::screen_get_orientation(int p_screen) const {
  365. return SCREEN_LANDSCAPE;
  366. }
  367. void DisplayServerWindows::screen_set_keep_on(bool p_enable) {
  368. }
  369. bool DisplayServerWindows::screen_is_kept_on() const {
  370. return false;
  371. }
  372. Vector<DisplayServer::WindowID> DisplayServerWindows::get_window_list() const {
  373. _THREAD_SAFE_METHOD_
  374. Vector<DisplayServer::WindowID> ret;
  375. for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
  376. ret.push_back(E->key());
  377. }
  378. return ret;
  379. }
  380. DisplayServer::WindowID DisplayServerWindows::get_window_at_screen_position(const Point2i &p_position) const {
  381. POINT p;
  382. p.x = p_position.x;
  383. p.y = p_position.y;
  384. HWND hwnd = WindowFromPoint(p);
  385. for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
  386. if (E->get().hWnd == hwnd) {
  387. return E->key();
  388. }
  389. }
  390. return INVALID_WINDOW_ID;
  391. }
  392. DisplayServer::WindowID DisplayServerWindows::create_sub_window(WindowMode p_mode, uint32_t p_flags, const Rect2i &p_rect) {
  393. _THREAD_SAFE_METHOD_
  394. WindowID window_id = _create_window(p_mode, p_flags, p_rect);
  395. ERR_FAIL_COND_V_MSG(window_id == INVALID_WINDOW_ID, INVALID_WINDOW_ID, "Failed to create sub window.");
  396. WindowData &wd = windows[window_id];
  397. if (p_flags & WINDOW_FLAG_RESIZE_DISABLED_BIT) {
  398. wd.resizable = false;
  399. }
  400. if (p_flags & WINDOW_FLAG_BORDERLESS_BIT) {
  401. wd.borderless = true;
  402. }
  403. if (p_flags & WINDOW_FLAG_ALWAYS_ON_TOP_BIT && p_mode != WINDOW_MODE_FULLSCREEN) {
  404. wd.always_on_top = true;
  405. }
  406. if (p_flags & WINDOW_FLAG_NO_FOCUS_BIT) {
  407. wd.no_focus = true;
  408. }
  409. return window_id;
  410. }
  411. void DisplayServerWindows::show_window(WindowID p_id) {
  412. WindowData &wd = windows[p_id];
  413. if (p_id != MAIN_WINDOW_ID) {
  414. _update_window_style(p_id);
  415. }
  416. ShowWindow(wd.hWnd, wd.no_focus ? SW_SHOWNOACTIVATE : SW_SHOW); // Show The Window
  417. if (!wd.no_focus) {
  418. SetForegroundWindow(wd.hWnd); // Slightly Higher Priority
  419. SetFocus(wd.hWnd); // Sets Keyboard Focus To
  420. }
  421. }
  422. void DisplayServerWindows::delete_sub_window(WindowID p_window) {
  423. _THREAD_SAFE_METHOD_
  424. ERR_FAIL_COND(!windows.has(p_window));
  425. ERR_FAIL_COND_MSG(p_window == MAIN_WINDOW_ID, "Main window cannot be deleted.");
  426. WindowData &wd = windows[p_window];
  427. while (wd.transient_children.size()) {
  428. window_set_transient(wd.transient_children.front()->get(), INVALID_WINDOW_ID);
  429. }
  430. if (wd.transient_parent != INVALID_WINDOW_ID) {
  431. window_set_transient(p_window, INVALID_WINDOW_ID);
  432. }
  433. #ifdef VULKAN_ENABLED
  434. if (rendering_driver == "vulkan") {
  435. context_vulkan->window_destroy(p_window);
  436. }
  437. #endif
  438. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[p_window].wtctx) {
  439. wintab_WTClose(windows[p_window].wtctx);
  440. windows[p_window].wtctx = 0;
  441. }
  442. DestroyWindow(windows[p_window].hWnd);
  443. windows.erase(p_window);
  444. }
  445. void DisplayServerWindows::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  446. _THREAD_SAFE_METHOD_
  447. ERR_FAIL_COND(!windows.has(p_window));
  448. windows[p_window].instance_id = p_instance;
  449. }
  450. ObjectID DisplayServerWindows::window_get_attached_instance_id(WindowID p_window) const {
  451. _THREAD_SAFE_METHOD_
  452. ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
  453. return windows[p_window].instance_id;
  454. }
  455. void DisplayServerWindows::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  456. _THREAD_SAFE_METHOD_
  457. ERR_FAIL_COND(!windows.has(p_window));
  458. windows[p_window].rect_changed_callback = p_callable;
  459. }
  460. void DisplayServerWindows::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  461. _THREAD_SAFE_METHOD_
  462. ERR_FAIL_COND(!windows.has(p_window));
  463. windows[p_window].event_callback = p_callable;
  464. }
  465. void DisplayServerWindows::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  466. _THREAD_SAFE_METHOD_
  467. ERR_FAIL_COND(!windows.has(p_window));
  468. windows[p_window].input_event_callback = p_callable;
  469. }
  470. void DisplayServerWindows::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  471. _THREAD_SAFE_METHOD_
  472. ERR_FAIL_COND(!windows.has(p_window));
  473. windows[p_window].input_text_callback = p_callable;
  474. }
  475. void DisplayServerWindows::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  476. _THREAD_SAFE_METHOD_
  477. ERR_FAIL_COND(!windows.has(p_window));
  478. windows[p_window].drop_files_callback = p_callable;
  479. }
  480. void DisplayServerWindows::window_set_title(const String &p_title, WindowID p_window) {
  481. _THREAD_SAFE_METHOD_
  482. ERR_FAIL_COND(!windows.has(p_window));
  483. SetWindowTextW(windows[p_window].hWnd, (LPCWSTR)(p_title.utf16().get_data()));
  484. }
  485. void DisplayServerWindows::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
  486. _THREAD_SAFE_METHOD_
  487. ERR_FAIL_COND(!windows.has(p_window));
  488. windows[p_window].mpath = p_region;
  489. _update_window_mouse_passthrough(p_window);
  490. }
  491. void DisplayServerWindows::_update_window_mouse_passthrough(WindowID p_window) {
  492. if (windows[p_window].mpath.size() == 0) {
  493. SetWindowRgn(windows[p_window].hWnd, nullptr, TRUE);
  494. } else {
  495. POINT *points = (POINT *)memalloc(sizeof(POINT) * windows[p_window].mpath.size());
  496. for (int i = 0; i < windows[p_window].mpath.size(); i++) {
  497. if (windows[p_window].borderless) {
  498. points[i].x = windows[p_window].mpath[i].x;
  499. points[i].y = windows[p_window].mpath[i].y;
  500. } else {
  501. points[i].x = windows[p_window].mpath[i].x + GetSystemMetrics(SM_CXSIZEFRAME);
  502. points[i].y = windows[p_window].mpath[i].y + GetSystemMetrics(SM_CYSIZEFRAME) + GetSystemMetrics(SM_CYCAPTION);
  503. }
  504. }
  505. HRGN region = CreatePolygonRgn(points, windows[p_window].mpath.size(), ALTERNATE);
  506. SetWindowRgn(windows[p_window].hWnd, region, TRUE);
  507. DeleteObject(region);
  508. memfree(points);
  509. }
  510. }
  511. int DisplayServerWindows::window_get_current_screen(WindowID p_window) const {
  512. _THREAD_SAFE_METHOD_
  513. ERR_FAIL_COND_V(!windows.has(p_window), -1);
  514. EnumScreenData data = { 0, 0, MonitorFromWindow(windows[p_window].hWnd, MONITOR_DEFAULTTONEAREST) };
  515. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcScreen, (LPARAM)&data);
  516. return data.screen;
  517. }
  518. void DisplayServerWindows::window_set_current_screen(int p_screen, WindowID p_window) {
  519. _THREAD_SAFE_METHOD_
  520. ERR_FAIL_COND(!windows.has(p_window));
  521. ERR_FAIL_INDEX(p_screen, get_screen_count());
  522. Vector2 ofs = window_get_position(p_window) - screen_get_position(window_get_current_screen(p_window));
  523. window_set_position(ofs + screen_get_position(p_screen), p_window);
  524. }
  525. Point2i DisplayServerWindows::window_get_position(WindowID p_window) const {
  526. _THREAD_SAFE_METHOD_
  527. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  528. const WindowData &wd = windows[p_window];
  529. if (wd.minimized) {
  530. return wd.last_pos;
  531. }
  532. POINT point;
  533. point.x = 0;
  534. point.y = 0;
  535. ClientToScreen(wd.hWnd, &point);
  536. return Point2i(point.x, point.y);
  537. #if 0
  538. //do not use this method, as it includes windows decorations
  539. RECT r;
  540. GetWindowRect(wd.hWnd, &r);
  541. return Point2(r.left, r.top);
  542. #endif
  543. }
  544. void DisplayServerWindows::_update_real_mouse_position(WindowID p_window) {
  545. POINT mouse_pos;
  546. if (GetCursorPos(&mouse_pos) && ScreenToClient(windows[p_window].hWnd, &mouse_pos)) {
  547. if (mouse_pos.x > 0 && mouse_pos.y > 0 && mouse_pos.x <= windows[p_window].width && mouse_pos.y <= windows[p_window].height) {
  548. old_x = mouse_pos.x;
  549. old_y = mouse_pos.y;
  550. old_invalid = false;
  551. Input::get_singleton()->set_mouse_position(Point2i(mouse_pos.x, mouse_pos.y));
  552. }
  553. }
  554. }
  555. void DisplayServerWindows::window_set_position(const Point2i &p_position, WindowID p_window) {
  556. _THREAD_SAFE_METHOD_
  557. ERR_FAIL_COND(!windows.has(p_window));
  558. WindowData &wd = windows[p_window];
  559. if (wd.fullscreen)
  560. return;
  561. #if 0
  562. //wrong needs to account properly for decorations
  563. RECT r;
  564. GetWindowRect(wd.hWnd, &r);
  565. MoveWindow(wd.hWnd, p_position.x, p_position.y, r.right - r.left, r.bottom - r.top, TRUE);
  566. #else
  567. RECT rc;
  568. rc.left = p_position.x;
  569. rc.right = p_position.x + wd.width;
  570. rc.bottom = p_position.y + wd.height;
  571. rc.top = p_position.y;
  572. const DWORD style = GetWindowLongPtr(wd.hWnd, GWL_STYLE);
  573. const DWORD exStyle = GetWindowLongPtr(wd.hWnd, GWL_EXSTYLE);
  574. AdjustWindowRectEx(&rc, style, false, exStyle);
  575. MoveWindow(wd.hWnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, TRUE);
  576. #endif
  577. // Don't let the mouse leave the window when moved
  578. if (mouse_mode == MOUSE_MODE_CONFINED) {
  579. RECT rect;
  580. GetClientRect(wd.hWnd, &rect);
  581. ClientToScreen(wd.hWnd, (POINT *)&rect.left);
  582. ClientToScreen(wd.hWnd, (POINT *)&rect.right);
  583. ClipCursor(&rect);
  584. }
  585. wd.last_pos = p_position;
  586. _update_real_mouse_position(p_window);
  587. }
  588. void DisplayServerWindows::window_set_transient(WindowID p_window, WindowID p_parent) {
  589. _THREAD_SAFE_METHOD_
  590. ERR_FAIL_COND(p_window == p_parent);
  591. ERR_FAIL_COND(!windows.has(p_window));
  592. WindowData &wd_window = windows[p_window];
  593. ERR_FAIL_COND(wd_window.transient_parent == p_parent);
  594. ERR_FAIL_COND_MSG(wd_window.always_on_top, "Windows with the 'on top' can't become transient.");
  595. if (p_parent == INVALID_WINDOW_ID) {
  596. //remove transient
  597. ERR_FAIL_COND(wd_window.transient_parent == INVALID_WINDOW_ID);
  598. ERR_FAIL_COND(!windows.has(wd_window.transient_parent));
  599. WindowData &wd_parent = windows[wd_window.transient_parent];
  600. wd_window.transient_parent = INVALID_WINDOW_ID;
  601. wd_parent.transient_children.erase(p_window);
  602. SetWindowLongPtr(wd_window.hWnd, GWLP_HWNDPARENT, (LONG_PTR) nullptr);
  603. } else {
  604. ERR_FAIL_COND(!windows.has(p_parent));
  605. ERR_FAIL_COND_MSG(wd_window.transient_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
  606. WindowData &wd_parent = windows[p_parent];
  607. wd_window.transient_parent = p_parent;
  608. wd_parent.transient_children.insert(p_window);
  609. SetWindowLongPtr(wd_window.hWnd, GWLP_HWNDPARENT, (LONG_PTR)wd_parent.hWnd);
  610. }
  611. }
  612. void DisplayServerWindows::window_set_max_size(const Size2i p_size, WindowID p_window) {
  613. _THREAD_SAFE_METHOD_
  614. ERR_FAIL_COND(!windows.has(p_window));
  615. WindowData &wd = windows[p_window];
  616. if ((p_size != Size2()) && ((p_size.x < wd.min_size.x) || (p_size.y < wd.min_size.y))) {
  617. ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
  618. return;
  619. }
  620. wd.max_size = p_size;
  621. }
  622. Size2i DisplayServerWindows::window_get_max_size(WindowID p_window) const {
  623. _THREAD_SAFE_METHOD_
  624. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  625. const WindowData &wd = windows[p_window];
  626. return wd.max_size;
  627. }
  628. void DisplayServerWindows::window_set_min_size(const Size2i p_size, WindowID p_window) {
  629. _THREAD_SAFE_METHOD_
  630. ERR_FAIL_COND(!windows.has(p_window));
  631. WindowData &wd = windows[p_window];
  632. if ((p_size != Size2()) && (wd.max_size != Size2()) && ((p_size.x > wd.max_size.x) || (p_size.y > wd.max_size.y))) {
  633. ERR_PRINT("Minimum window size can't be larger than maximum window size!");
  634. return;
  635. }
  636. wd.min_size = p_size;
  637. }
  638. Size2i DisplayServerWindows::window_get_min_size(WindowID p_window) const {
  639. _THREAD_SAFE_METHOD_
  640. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  641. const WindowData &wd = windows[p_window];
  642. return wd.min_size;
  643. }
  644. void DisplayServerWindows::window_set_size(const Size2i p_size, WindowID p_window) {
  645. _THREAD_SAFE_METHOD_
  646. ERR_FAIL_COND(!windows.has(p_window));
  647. WindowData &wd = windows[p_window];
  648. int w = p_size.width;
  649. int h = p_size.height;
  650. wd.width = w;
  651. wd.height = h;
  652. #if defined(VULKAN_ENABLED)
  653. if (rendering_driver == "vulkan") {
  654. context_vulkan->window_resize(p_window, w, h);
  655. }
  656. #endif
  657. if (wd.fullscreen) {
  658. return;
  659. }
  660. RECT rect;
  661. GetWindowRect(wd.hWnd, &rect);
  662. if (!wd.borderless) {
  663. RECT crect;
  664. GetClientRect(wd.hWnd, &crect);
  665. w += (rect.right - rect.left) - (crect.right - crect.left);
  666. h += (rect.bottom - rect.top) - (crect.bottom - crect.top);
  667. }
  668. MoveWindow(wd.hWnd, rect.left, rect.top, w, h, TRUE);
  669. // Don't let the mouse leave the window when resizing to a smaller resolution
  670. if (mouse_mode == MOUSE_MODE_CONFINED) {
  671. RECT crect;
  672. GetClientRect(wd.hWnd, &crect);
  673. ClientToScreen(wd.hWnd, (POINT *)&crect.left);
  674. ClientToScreen(wd.hWnd, (POINT *)&crect.right);
  675. ClipCursor(&crect);
  676. }
  677. }
  678. Size2i DisplayServerWindows::window_get_size(WindowID p_window) const {
  679. _THREAD_SAFE_METHOD_
  680. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  681. const WindowData &wd = windows[p_window];
  682. if (wd.minimized) {
  683. return Size2(wd.width, wd.height);
  684. }
  685. RECT r;
  686. if (GetClientRect(wd.hWnd, &r)) { // Only 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 a 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 a 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_data();
  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_data();
  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, NULL);
  1129. }
  1130. int DisplayServerWindows::keyboard_get_current_layout() const {
  1131. HKL cur_layout = GetKeyboardLayout(0);
  1132. int layout_count = GetKeyboardLayoutList(0, NULL);
  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, NULL);
  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, NULL);
  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", NULL, &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, NULL);
  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_accumulated_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::vsync_set_use_via_compositor(bool p_enable) {
  1344. }
  1345. bool DisplayServerWindows::vsync_is_using_via_compositor() const {
  1346. return false;
  1347. }
  1348. void DisplayServerWindows::set_context(Context p_context) {
  1349. }
  1350. #define MI_WP_SIGNATURE 0xFF515700
  1351. #define SIGNATURE_MASK 0xFFFFFF00
  1352. // Keeping the name suggested by Microsoft, but this macro really answers:
  1353. // Is this mouse event emulated from touch or pen input?
  1354. #define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE)
  1355. // This one tells whether the event comes from touchscreen (and not from pen)
  1356. #define IsTouchEvent(dw) (IsPenEvent(dw) && ((dw)&0x80))
  1357. void DisplayServerWindows::_touch_event(WindowID p_window, bool p_pressed, float p_x, float p_y, int idx) {
  1358. // Defensive
  1359. if (touch_state.has(idx) == p_pressed)
  1360. return;
  1361. if (p_pressed) {
  1362. touch_state.insert(idx, Vector2(p_x, p_y));
  1363. } else {
  1364. touch_state.erase(idx);
  1365. }
  1366. Ref<InputEventScreenTouch> event;
  1367. event.instance();
  1368. event->set_index(idx);
  1369. event->set_window_id(p_window);
  1370. event->set_pressed(p_pressed);
  1371. event->set_position(Vector2(p_x, p_y));
  1372. Input::get_singleton()->accumulate_input_event(event);
  1373. }
  1374. void DisplayServerWindows::_drag_event(WindowID p_window, float p_x, float p_y, int idx) {
  1375. Map<int, Vector2>::Element *curr = touch_state.find(idx);
  1376. // Defensive
  1377. if (!curr)
  1378. return;
  1379. if (curr->get() == Vector2(p_x, p_y))
  1380. return;
  1381. Ref<InputEventScreenDrag> event;
  1382. event.instance();
  1383. event->set_window_id(p_window);
  1384. event->set_index(idx);
  1385. event->set_position(Vector2(p_x, p_y));
  1386. event->set_relative(Vector2(p_x, p_y) - curr->get());
  1387. Input::get_singleton()->accumulate_input_event(event);
  1388. curr->get() = Vector2(p_x, p_y);
  1389. }
  1390. void DisplayServerWindows::_send_window_event(const WindowData &wd, WindowEvent p_event) {
  1391. if (!wd.event_callback.is_null()) {
  1392. Variant event = int(p_event);
  1393. Variant *eventp = &event;
  1394. Variant ret;
  1395. Callable::CallError ce;
  1396. wd.event_callback.call((const Variant **)&eventp, 1, ret, ce);
  1397. }
  1398. }
  1399. void DisplayServerWindows::_dispatch_input_events(const Ref<InputEvent> &p_event) {
  1400. ((DisplayServerWindows *)(get_singleton()))->_dispatch_input_event(p_event);
  1401. }
  1402. void DisplayServerWindows::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  1403. _THREAD_SAFE_METHOD_
  1404. if (in_dispatch_input_event) {
  1405. return;
  1406. }
  1407. in_dispatch_input_event = true;
  1408. Variant ev = p_event;
  1409. Variant *evp = &ev;
  1410. Variant ret;
  1411. Callable::CallError ce;
  1412. Ref<InputEventFromWindow> event_from_window = p_event;
  1413. if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
  1414. //send to a window
  1415. if (!windows.has(event_from_window->get_window_id())) {
  1416. in_dispatch_input_event = false;
  1417. ERR_FAIL_MSG("DisplayServerWindows: Invalid window id in input event.");
  1418. }
  1419. Callable callable = windows[event_from_window->get_window_id()].input_event_callback;
  1420. if (callable.is_null()) {
  1421. in_dispatch_input_event = false;
  1422. return;
  1423. }
  1424. callable.call((const Variant **)&evp, 1, ret, ce);
  1425. } else {
  1426. //send to all windows
  1427. for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
  1428. Callable callable = E->get().input_event_callback;
  1429. if (callable.is_null()) {
  1430. continue;
  1431. }
  1432. callable.call((const Variant **)&evp, 1, ret, ce);
  1433. }
  1434. }
  1435. in_dispatch_input_event = false;
  1436. }
  1437. LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  1438. if (drop_events) {
  1439. if (user_proc) {
  1440. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  1441. } else {
  1442. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  1443. }
  1444. };
  1445. WindowID window_id = INVALID_WINDOW_ID;
  1446. bool window_created = false;
  1447. for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
  1448. if (E->get().hWnd == hWnd) {
  1449. window_id = E->key();
  1450. window_created = true;
  1451. break;
  1452. }
  1453. }
  1454. if (!window_created) {
  1455. // Window creation in progress.
  1456. window_id = window_id_counter;
  1457. ERR_FAIL_COND_V(!windows.has(window_id), 0);
  1458. }
  1459. switch (uMsg) // Check For Windows Messages
  1460. {
  1461. case WM_SETFOCUS: {
  1462. windows[window_id].window_has_focus = true;
  1463. last_focused_window = window_id;
  1464. // Restore mouse mode
  1465. _set_mouse_mode_impl(mouse_mode);
  1466. if (!app_focused) {
  1467. if (OS::get_singleton()->get_main_loop()) {
  1468. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
  1469. }
  1470. app_focused = true;
  1471. }
  1472. break;
  1473. }
  1474. case WM_KILLFOCUS: {
  1475. windows[window_id].window_has_focus = false;
  1476. last_focused_window = window_id;
  1477. // Release capture unconditionally because it can be set due to dragging, in addition to captured mode
  1478. ReleaseCapture();
  1479. // Release every touch to avoid sticky points
  1480. for (Map<int, Vector2>::Element *E = touch_state.front(); E; E = E->next()) {
  1481. _touch_event(window_id, false, E->get().x, E->get().y, E->key());
  1482. }
  1483. touch_state.clear();
  1484. bool self_steal = false;
  1485. HWND new_hwnd = (HWND)wParam;
  1486. if (IsWindow(new_hwnd)) {
  1487. self_steal = true;
  1488. }
  1489. if (!self_steal) {
  1490. if (OS::get_singleton()->get_main_loop()) {
  1491. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
  1492. }
  1493. app_focused = false;
  1494. }
  1495. break;
  1496. }
  1497. case WM_ACTIVATE: { // Watch For Window Activate Message
  1498. if (!windows[window_id].window_focused) {
  1499. _process_activate_event(window_id, wParam, lParam);
  1500. } else {
  1501. windows[window_id].saved_wparam = wParam;
  1502. windows[window_id].saved_lparam = lParam;
  1503. // Run a timer to prevent event catching warning if the focused window is closing.
  1504. windows[window_id].focus_timer_id = SetTimer(windows[window_id].hWnd, 2, USER_TIMER_MINIMUM, (TIMERPROC) nullptr);
  1505. }
  1506. return 0; // Return To The Message Loop
  1507. }
  1508. case WM_GETMINMAXINFO: {
  1509. if (windows[window_id].resizable && !windows[window_id].fullscreen) {
  1510. Size2 decor = window_get_size(window_id) - window_get_real_size(window_id); // Size of window decorations
  1511. MINMAXINFO *min_max_info = (MINMAXINFO *)lParam;
  1512. if (windows[window_id].min_size != Size2()) {
  1513. min_max_info->ptMinTrackSize.x = windows[window_id].min_size.x + decor.x;
  1514. min_max_info->ptMinTrackSize.y = windows[window_id].min_size.y + decor.y;
  1515. }
  1516. if (windows[window_id].max_size != Size2()) {
  1517. min_max_info->ptMaxTrackSize.x = windows[window_id].max_size.x + decor.x;
  1518. min_max_info->ptMaxTrackSize.y = windows[window_id].max_size.y + decor.y;
  1519. }
  1520. return 0;
  1521. } else {
  1522. break;
  1523. }
  1524. }
  1525. case WM_PAINT:
  1526. Main::force_redraw();
  1527. break;
  1528. case WM_SYSCOMMAND: // Intercept System Commands
  1529. {
  1530. switch (wParam) // Check System Calls
  1531. {
  1532. case SC_SCREENSAVE: // Screensaver Trying To Start?
  1533. case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
  1534. return 0; // Prevent From Happening
  1535. case SC_KEYMENU:
  1536. if ((lParam >> 16) <= 0)
  1537. return 0;
  1538. }
  1539. break; // Exit
  1540. }
  1541. case WM_CLOSE: // Did We Receive A Close Message?
  1542. {
  1543. if (windows[window_id].focus_timer_id != 0U) {
  1544. KillTimer(windows[window_id].hWnd, windows[window_id].focus_timer_id);
  1545. }
  1546. _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST);
  1547. return 0; // Jump Back
  1548. }
  1549. case WM_MOUSELEAVE: {
  1550. old_invalid = true;
  1551. outside = true;
  1552. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_EXIT);
  1553. } break;
  1554. case WM_INPUT: {
  1555. if (mouse_mode != MOUSE_MODE_CAPTURED || !use_raw_input) {
  1556. break;
  1557. }
  1558. UINT dwSize;
  1559. GetRawInputData((HRAWINPUT)lParam, RID_INPUT, nullptr, &dwSize, sizeof(RAWINPUTHEADER));
  1560. LPBYTE lpb = new BYTE[dwSize];
  1561. if (lpb == nullptr) {
  1562. return 0;
  1563. }
  1564. if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize)
  1565. OutputDebugString(TEXT("GetRawInputData does not return correct size !\n"));
  1566. RAWINPUT *raw = (RAWINPUT *)lpb;
  1567. if (raw->header.dwType == RIM_TYPEMOUSE) {
  1568. Ref<InputEventMouseMotion> mm;
  1569. mm.instance();
  1570. mm->set_window_id(window_id);
  1571. mm->set_control(control_mem);
  1572. mm->set_shift(shift_mem);
  1573. mm->set_alt(alt_mem);
  1574. mm->set_pressure((raw->data.mouse.ulButtons & RI_MOUSE_LEFT_BUTTON_DOWN) ? 1.0f : 0.0f);
  1575. mm->set_button_mask(last_button_state);
  1576. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  1577. // centering just so it works as before
  1578. POINT pos = { (int)c.x, (int)c.y };
  1579. ClientToScreen(windows[window_id].hWnd, &pos);
  1580. SetCursorPos(pos.x, pos.y);
  1581. mm->set_position(c);
  1582. mm->set_global_position(c);
  1583. Input::get_singleton()->set_mouse_position(c);
  1584. mm->set_speed(Vector2(0, 0));
  1585. if (raw->data.mouse.usFlags == MOUSE_MOVE_RELATIVE) {
  1586. mm->set_relative(Vector2(raw->data.mouse.lLastX, raw->data.mouse.lLastY));
  1587. } else if (raw->data.mouse.usFlags == MOUSE_MOVE_ABSOLUTE) {
  1588. int nScreenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
  1589. int nScreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
  1590. int nScreenLeft = GetSystemMetrics(SM_XVIRTUALSCREEN);
  1591. int nScreenTop = GetSystemMetrics(SM_YVIRTUALSCREEN);
  1592. Vector2 abs_pos(
  1593. (double(raw->data.mouse.lLastX) - 65536.0 / (nScreenWidth)) * nScreenWidth / 65536.0 + nScreenLeft,
  1594. (double(raw->data.mouse.lLastY) - 65536.0 / (nScreenHeight)) * nScreenHeight / 65536.0 + nScreenTop);
  1595. POINT coords; //client coords
  1596. coords.x = abs_pos.x;
  1597. coords.y = abs_pos.y;
  1598. ScreenToClient(hWnd, &coords);
  1599. mm->set_relative(Vector2(coords.x - old_x, coords.y - old_y));
  1600. old_x = coords.x;
  1601. old_y = coords.y;
  1602. /*Input.mi.dx = (int)((((double)(pos.x)-nScreenLeft) * 65536) / nScreenWidth + 65536 / (nScreenWidth));
  1603. Input.mi.dy = (int)((((double)(pos.y)-nScreenTop) * 65536) / nScreenHeight + 65536 / (nScreenHeight));
  1604. */
  1605. }
  1606. if (windows[window_id].window_has_focus && mm->get_relative() != Vector2())
  1607. Input::get_singleton()->accumulate_input_event(mm);
  1608. }
  1609. delete[] lpb;
  1610. } break;
  1611. case WT_CSRCHANGE:
  1612. case WT_PROXIMITY: {
  1613. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
  1614. AXIS pressure;
  1615. if (wintab_WTInfo(WTI_DEVICES + windows[window_id].wtlc.lcDevice, DVC_NPRESSURE, &pressure)) {
  1616. windows[window_id].min_pressure = int(pressure.axMin);
  1617. windows[window_id].max_pressure = int(pressure.axMax);
  1618. }
  1619. AXIS orientation[3];
  1620. if (wintab_WTInfo(WTI_DEVICES + windows[window_id].wtlc.lcDevice, DVC_ORIENTATION, &orientation)) {
  1621. windows[window_id].tilt_supported = orientation[0].axResolution && orientation[1].axResolution;
  1622. }
  1623. return 0;
  1624. }
  1625. } break;
  1626. case WT_PACKET: {
  1627. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
  1628. PACKET packet;
  1629. if (wintab_WTPacket(windows[window_id].wtctx, wParam, &packet)) {
  1630. float pressure = float(packet.pkNormalPressure - windows[window_id].min_pressure) / float(windows[window_id].max_pressure - windows[window_id].min_pressure);
  1631. windows[window_id].last_pressure = pressure;
  1632. windows[window_id].last_pressure_update = 0;
  1633. double azim = (packet.pkOrientation.orAzimuth / 10.0f) * (Math_PI / 180);
  1634. double alt = Math::tan((Math::abs(packet.pkOrientation.orAltitude / 10.0f)) * (Math_PI / 180));
  1635. if (windows[window_id].tilt_supported) {
  1636. windows[window_id].last_tilt = Vector2(Math::atan(Math::sin(azim) / alt), Math::atan(Math::cos(azim) / alt));
  1637. } else {
  1638. windows[window_id].last_tilt = Vector2();
  1639. }
  1640. POINT coords;
  1641. GetCursorPos(&coords);
  1642. ScreenToClient(windows[window_id].hWnd, &coords);
  1643. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  1644. if (!windows[window_id].window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED)
  1645. break;
  1646. Ref<InputEventMouseMotion> mm;
  1647. mm.instance();
  1648. mm->set_window_id(window_id);
  1649. mm->set_control(GetKeyState(VK_CONTROL) < 0);
  1650. mm->set_shift(GetKeyState(VK_SHIFT) < 0);
  1651. mm->set_alt(alt_mem);
  1652. mm->set_pressure(windows[window_id].last_pressure);
  1653. mm->set_tilt(windows[window_id].last_tilt);
  1654. mm->set_button_mask(last_button_state);
  1655. mm->set_position(Vector2(coords.x, coords.y));
  1656. mm->set_global_position(Vector2(coords.x, coords.y));
  1657. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1658. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  1659. old_x = c.x;
  1660. old_y = c.y;
  1661. if (mm->get_position() == c) {
  1662. center = c;
  1663. return 0;
  1664. }
  1665. Point2i ncenter = mm->get_position();
  1666. center = ncenter;
  1667. POINT pos = { (int)c.x, (int)c.y };
  1668. ClientToScreen(windows[window_id].hWnd, &pos);
  1669. SetCursorPos(pos.x, pos.y);
  1670. }
  1671. Input::get_singleton()->set_mouse_position(mm->get_position());
  1672. mm->set_speed(Input::get_singleton()->get_last_mouse_speed());
  1673. if (old_invalid) {
  1674. old_x = mm->get_position().x;
  1675. old_y = mm->get_position().y;
  1676. old_invalid = false;
  1677. }
  1678. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  1679. old_x = mm->get_position().x;
  1680. old_y = mm->get_position().y;
  1681. if (windows[window_id].window_has_focus)
  1682. Input::get_singleton()->accumulate_input_event(mm);
  1683. }
  1684. return 0;
  1685. }
  1686. } break;
  1687. case WM_POINTERENTER: {
  1688. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  1689. break;
  1690. }
  1691. if ((tablet_get_current_driver() != "winink") || !winink_available) {
  1692. break;
  1693. }
  1694. uint32_t pointer_id = LOWORD(wParam);
  1695. POINTER_INPUT_TYPE pointer_type = PT_POINTER;
  1696. if (!win8p_GetPointerType(pointer_id, &pointer_type)) {
  1697. break;
  1698. }
  1699. if (pointer_type != PT_PEN) {
  1700. break;
  1701. }
  1702. windows[window_id].block_mm = true;
  1703. return 0;
  1704. } break;
  1705. case WM_POINTERLEAVE: {
  1706. windows[window_id].block_mm = false;
  1707. return 0;
  1708. } break;
  1709. case WM_POINTERUPDATE: {
  1710. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  1711. break;
  1712. }
  1713. if ((tablet_get_current_driver() != "winink") || !winink_available) {
  1714. break;
  1715. }
  1716. uint32_t pointer_id = LOWORD(wParam);
  1717. POINTER_INPUT_TYPE pointer_type = PT_POINTER;
  1718. if (!win8p_GetPointerType(pointer_id, &pointer_type)) {
  1719. break;
  1720. }
  1721. if (pointer_type != PT_PEN) {
  1722. break;
  1723. }
  1724. POINTER_PEN_INFO pen_info;
  1725. if (!win8p_GetPointerPenInfo(pointer_id, &pen_info)) {
  1726. break;
  1727. }
  1728. if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
  1729. // Universal translation enabled; ignore OS translation
  1730. LPARAM extra = GetMessageExtraInfo();
  1731. if (IsTouchEvent(extra)) {
  1732. break;
  1733. }
  1734. }
  1735. if (outside) {
  1736. //mouse enter
  1737. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  1738. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
  1739. }
  1740. CursorShape c = cursor_shape;
  1741. cursor_shape = CURSOR_MAX;
  1742. cursor_set_shape(c);
  1743. outside = false;
  1744. //Once-Off notification, must call again....
  1745. TRACKMOUSEEVENT tme;
  1746. tme.cbSize = sizeof(TRACKMOUSEEVENT);
  1747. tme.dwFlags = TME_LEAVE;
  1748. tme.hwndTrack = hWnd;
  1749. tme.dwHoverTime = HOVER_DEFAULT;
  1750. TrackMouseEvent(&tme);
  1751. }
  1752. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  1753. if (!windows[window_id].window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED)
  1754. break;
  1755. Ref<InputEventMouseMotion> mm;
  1756. mm.instance();
  1757. mm->set_window_id(window_id);
  1758. if (pen_info.penMask & PEN_MASK_PRESSURE) {
  1759. mm->set_pressure((float)pen_info.pressure / 1024);
  1760. } else {
  1761. mm->set_pressure((HIWORD(wParam) & POINTER_MESSAGE_FLAG_FIRSTBUTTON) ? 1.0f : 0.0f);
  1762. }
  1763. if ((pen_info.penMask & PEN_MASK_TILT_X) && (pen_info.penMask & PEN_MASK_TILT_Y)) {
  1764. mm->set_tilt(Vector2((float)pen_info.tiltX / 90, (float)pen_info.tiltY / 90));
  1765. }
  1766. mm->set_control(GetKeyState(VK_CONTROL) < 0);
  1767. mm->set_shift(GetKeyState(VK_SHIFT) < 0);
  1768. mm->set_alt(alt_mem);
  1769. mm->set_button_mask(last_button_state);
  1770. POINT coords; //client coords
  1771. coords.x = GET_X_LPARAM(lParam);
  1772. coords.y = GET_Y_LPARAM(lParam);
  1773. ScreenToClient(windows[window_id].hWnd, &coords);
  1774. mm->set_position(Vector2(coords.x, coords.y));
  1775. mm->set_global_position(Vector2(coords.x, coords.y));
  1776. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1777. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  1778. old_x = c.x;
  1779. old_y = c.y;
  1780. if (mm->get_position() == c) {
  1781. center = c;
  1782. return 0;
  1783. }
  1784. Point2i ncenter = mm->get_position();
  1785. center = ncenter;
  1786. POINT pos = { (int)c.x, (int)c.y };
  1787. ClientToScreen(hWnd, &pos);
  1788. SetCursorPos(pos.x, pos.y);
  1789. }
  1790. Input::get_singleton()->set_mouse_position(mm->get_position());
  1791. mm->set_speed(Input::get_singleton()->get_last_mouse_speed());
  1792. if (old_invalid) {
  1793. old_x = mm->get_position().x;
  1794. old_y = mm->get_position().y;
  1795. old_invalid = false;
  1796. }
  1797. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  1798. old_x = mm->get_position().x;
  1799. old_y = mm->get_position().y;
  1800. if (windows[window_id].window_has_focus) {
  1801. Input::get_singleton()->accumulate_input_event(mm);
  1802. }
  1803. return 0; //Pointer event handled return 0 to avoid duplicate WM_MOUSEMOVE event
  1804. } break;
  1805. case WM_MOUSEMOVE: {
  1806. if (windows[window_id].block_mm) {
  1807. break;
  1808. }
  1809. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  1810. break;
  1811. }
  1812. if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
  1813. // Universal translation enabled; ignore OS translation
  1814. LPARAM extra = GetMessageExtraInfo();
  1815. if (IsTouchEvent(extra)) {
  1816. break;
  1817. }
  1818. }
  1819. if (outside) {
  1820. //mouse enter
  1821. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  1822. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
  1823. }
  1824. CursorShape c = cursor_shape;
  1825. cursor_shape = CURSOR_MAX;
  1826. cursor_set_shape(c);
  1827. outside = false;
  1828. //Once-Off notification, must call again....
  1829. TRACKMOUSEEVENT tme;
  1830. tme.cbSize = sizeof(TRACKMOUSEEVENT);
  1831. tme.dwFlags = TME_LEAVE;
  1832. tme.hwndTrack = hWnd;
  1833. tme.dwHoverTime = HOVER_DEFAULT;
  1834. TrackMouseEvent(&tme);
  1835. }
  1836. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  1837. if (!windows[window_id].window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED)
  1838. break;
  1839. Ref<InputEventMouseMotion> mm;
  1840. mm.instance();
  1841. mm->set_window_id(window_id);
  1842. mm->set_control((wParam & MK_CONTROL) != 0);
  1843. mm->set_shift((wParam & MK_SHIFT) != 0);
  1844. mm->set_alt(alt_mem);
  1845. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
  1846. // Note: WinTab sends both WT_PACKET and WM_xBUTTONDOWN/UP/MOUSEMOVE events, use mouse 1/0 pressure only when last_pressure was not update recently.
  1847. if (windows[window_id].last_pressure_update < 10) {
  1848. windows[window_id].last_pressure_update++;
  1849. } else {
  1850. windows[window_id].last_tilt = Vector2();
  1851. windows[window_id].last_pressure = (wParam & MK_LBUTTON) ? 1.0f : 0.0f;
  1852. }
  1853. } else {
  1854. windows[window_id].last_tilt = Vector2();
  1855. windows[window_id].last_pressure = (wParam & MK_LBUTTON) ? 1.0f : 0.0f;
  1856. }
  1857. mm->set_pressure(windows[window_id].last_pressure);
  1858. mm->set_tilt(windows[window_id].last_tilt);
  1859. mm->set_button_mask(last_button_state);
  1860. mm->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  1861. mm->set_global_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  1862. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1863. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  1864. old_x = c.x;
  1865. old_y = c.y;
  1866. if (mm->get_position() == c) {
  1867. center = c;
  1868. return 0;
  1869. }
  1870. Point2i ncenter = mm->get_position();
  1871. center = ncenter;
  1872. POINT pos = { (int)c.x, (int)c.y };
  1873. ClientToScreen(windows[window_id].hWnd, &pos);
  1874. SetCursorPos(pos.x, pos.y);
  1875. }
  1876. Input::get_singleton()->set_mouse_position(mm->get_position());
  1877. mm->set_speed(Input::get_singleton()->get_last_mouse_speed());
  1878. if (old_invalid) {
  1879. old_x = mm->get_position().x;
  1880. old_y = mm->get_position().y;
  1881. old_invalid = false;
  1882. }
  1883. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  1884. old_x = mm->get_position().x;
  1885. old_y = mm->get_position().y;
  1886. if (windows[window_id].window_has_focus)
  1887. Input::get_singleton()->accumulate_input_event(mm);
  1888. } break;
  1889. case WM_LBUTTONDOWN:
  1890. case WM_LBUTTONUP:
  1891. if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
  1892. // Universal translation enabled; ignore OS translations for left button
  1893. LPARAM extra = GetMessageExtraInfo();
  1894. if (IsTouchEvent(extra)) {
  1895. break;
  1896. }
  1897. }
  1898. [[fallthrough]];
  1899. case WM_MBUTTONDOWN:
  1900. case WM_MBUTTONUP:
  1901. case WM_RBUTTONDOWN:
  1902. case WM_RBUTTONUP:
  1903. case WM_MOUSEWHEEL:
  1904. case WM_MOUSEHWHEEL:
  1905. case WM_LBUTTONDBLCLK:
  1906. case WM_MBUTTONDBLCLK:
  1907. case WM_RBUTTONDBLCLK:
  1908. case WM_XBUTTONDBLCLK:
  1909. case WM_XBUTTONDOWN:
  1910. case WM_XBUTTONUP: {
  1911. Ref<InputEventMouseButton> mb;
  1912. mb.instance();
  1913. mb->set_window_id(window_id);
  1914. switch (uMsg) {
  1915. case WM_LBUTTONDOWN: {
  1916. mb->set_pressed(true);
  1917. mb->set_button_index(1);
  1918. } break;
  1919. case WM_LBUTTONUP: {
  1920. mb->set_pressed(false);
  1921. mb->set_button_index(1);
  1922. } break;
  1923. case WM_MBUTTONDOWN: {
  1924. mb->set_pressed(true);
  1925. mb->set_button_index(3);
  1926. } break;
  1927. case WM_MBUTTONUP: {
  1928. mb->set_pressed(false);
  1929. mb->set_button_index(3);
  1930. } break;
  1931. case WM_RBUTTONDOWN: {
  1932. mb->set_pressed(true);
  1933. mb->set_button_index(2);
  1934. } break;
  1935. case WM_RBUTTONUP: {
  1936. mb->set_pressed(false);
  1937. mb->set_button_index(2);
  1938. } break;
  1939. case WM_LBUTTONDBLCLK: {
  1940. mb->set_pressed(true);
  1941. mb->set_button_index(1);
  1942. mb->set_doubleclick(true);
  1943. } break;
  1944. case WM_RBUTTONDBLCLK: {
  1945. mb->set_pressed(true);
  1946. mb->set_button_index(2);
  1947. mb->set_doubleclick(true);
  1948. } break;
  1949. case WM_MBUTTONDBLCLK: {
  1950. mb->set_pressed(true);
  1951. mb->set_button_index(3);
  1952. mb->set_doubleclick(true);
  1953. } break;
  1954. case WM_MOUSEWHEEL: {
  1955. mb->set_pressed(true);
  1956. int motion = (short)HIWORD(wParam);
  1957. if (!motion)
  1958. return 0;
  1959. if (motion > 0)
  1960. mb->set_button_index(BUTTON_WHEEL_UP);
  1961. else
  1962. mb->set_button_index(BUTTON_WHEEL_DOWN);
  1963. } break;
  1964. case WM_MOUSEHWHEEL: {
  1965. mb->set_pressed(true);
  1966. int motion = (short)HIWORD(wParam);
  1967. if (!motion)
  1968. return 0;
  1969. if (motion < 0) {
  1970. mb->set_button_index(BUTTON_WHEEL_LEFT);
  1971. mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
  1972. } else {
  1973. mb->set_button_index(BUTTON_WHEEL_RIGHT);
  1974. mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
  1975. }
  1976. } break;
  1977. case WM_XBUTTONDOWN: {
  1978. mb->set_pressed(true);
  1979. if (HIWORD(wParam) == XBUTTON1)
  1980. mb->set_button_index(BUTTON_XBUTTON1);
  1981. else
  1982. mb->set_button_index(BUTTON_XBUTTON2);
  1983. } break;
  1984. case WM_XBUTTONUP: {
  1985. mb->set_pressed(false);
  1986. if (HIWORD(wParam) == XBUTTON1)
  1987. mb->set_button_index(BUTTON_XBUTTON1);
  1988. else
  1989. mb->set_button_index(BUTTON_XBUTTON2);
  1990. } break;
  1991. case WM_XBUTTONDBLCLK: {
  1992. mb->set_pressed(true);
  1993. if (HIWORD(wParam) == XBUTTON1)
  1994. mb->set_button_index(BUTTON_XBUTTON1);
  1995. else
  1996. mb->set_button_index(BUTTON_XBUTTON2);
  1997. mb->set_doubleclick(true);
  1998. } break;
  1999. default: {
  2000. return 0;
  2001. }
  2002. }
  2003. mb->set_control((wParam & MK_CONTROL) != 0);
  2004. mb->set_shift((wParam & MK_SHIFT) != 0);
  2005. mb->set_alt(alt_mem);
  2006. //mb->get_alt()=(wParam&MK_MENU)!=0;
  2007. if (mb->is_pressed())
  2008. last_button_state |= (1 << (mb->get_button_index() - 1));
  2009. else
  2010. last_button_state &= ~(1 << (mb->get_button_index() - 1));
  2011. mb->set_button_mask(last_button_state);
  2012. mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  2013. if (mouse_mode == MOUSE_MODE_CAPTURED && !use_raw_input) {
  2014. mb->set_position(Vector2(old_x, old_y));
  2015. }
  2016. if (uMsg != WM_MOUSEWHEEL && uMsg != WM_MOUSEHWHEEL) {
  2017. if (mb->is_pressed()) {
  2018. if (++pressrc > 0 && mouse_mode != MOUSE_MODE_CAPTURED)
  2019. SetCapture(hWnd);
  2020. } else {
  2021. if (--pressrc <= 0) {
  2022. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  2023. ReleaseCapture();
  2024. }
  2025. pressrc = 0;
  2026. }
  2027. }
  2028. } else {
  2029. // for reasons unknown to mankind, wheel comes in screen coordinates
  2030. POINT coords;
  2031. coords.x = mb->get_position().x;
  2032. coords.y = mb->get_position().y;
  2033. ScreenToClient(hWnd, &coords);
  2034. mb->set_position(Vector2(coords.x, coords.y));
  2035. }
  2036. mb->set_global_position(mb->get_position());
  2037. Input::get_singleton()->accumulate_input_event(mb);
  2038. if (mb->is_pressed() && mb->get_button_index() > 3 && mb->get_button_index() < 8) {
  2039. //send release for mouse wheel
  2040. Ref<InputEventMouseButton> mbd = mb->duplicate();
  2041. mbd->set_window_id(window_id);
  2042. last_button_state &= ~(1 << (mbd->get_button_index() - 1));
  2043. mbd->set_button_mask(last_button_state);
  2044. mbd->set_pressed(false);
  2045. Input::get_singleton()->accumulate_input_event(mbd);
  2046. }
  2047. } break;
  2048. case WM_MOVE: {
  2049. if (!IsIconic(windows[window_id].hWnd)) {
  2050. int x = int16_t(LOWORD(lParam));
  2051. int y = int16_t(HIWORD(lParam));
  2052. windows[window_id].last_pos = Point2(x, y);
  2053. if (!windows[window_id].rect_changed_callback.is_null()) {
  2054. Variant size = Rect2i(windows[window_id].last_pos.x, windows[window_id].last_pos.y, windows[window_id].width, windows[window_id].height);
  2055. Variant *sizep = &size;
  2056. Variant ret;
  2057. Callable::CallError ce;
  2058. windows[window_id].rect_changed_callback.call((const Variant **)&sizep, 1, ret, ce);
  2059. }
  2060. }
  2061. } break;
  2062. case WM_SIZE: {
  2063. // Ignore size when a SIZE_MINIMIZED event is triggered
  2064. if (wParam != SIZE_MINIMIZED) {
  2065. int window_w = LOWORD(lParam);
  2066. int window_h = HIWORD(lParam);
  2067. if (window_w > 0 && window_h > 0 && !windows[window_id].preserve_window_size) {
  2068. windows[window_id].width = window_w;
  2069. windows[window_id].height = window_h;
  2070. #if defined(VULKAN_ENABLED)
  2071. if ((rendering_driver == "vulkan") && window_created) {
  2072. context_vulkan->window_resize(window_id, windows[window_id].width, windows[window_id].height);
  2073. }
  2074. #endif
  2075. } else {
  2076. windows[window_id].preserve_window_size = false;
  2077. window_set_size(Size2(windows[window_id].width, windows[window_id].height), window_id);
  2078. }
  2079. }
  2080. if (!windows[window_id].rect_changed_callback.is_null()) {
  2081. Variant size = Rect2i(windows[window_id].last_pos.x, windows[window_id].last_pos.y, windows[window_id].width, windows[window_id].height);
  2082. Variant *sizep = &size;
  2083. Variant ret;
  2084. Callable::CallError ce;
  2085. windows[window_id].rect_changed_callback.call((const Variant **)&sizep, 1, ret, ce);
  2086. }
  2087. if (wParam == SIZE_MAXIMIZED) {
  2088. windows[window_id].maximized = true;
  2089. windows[window_id].minimized = false;
  2090. } else if (wParam == SIZE_MINIMIZED) {
  2091. windows[window_id].maximized = false;
  2092. windows[window_id].minimized = true;
  2093. } else if (wParam == SIZE_RESTORED) {
  2094. windows[window_id].maximized = false;
  2095. windows[window_id].minimized = false;
  2096. }
  2097. #if 0
  2098. if (is_layered_allowed() && layered_window) {
  2099. DeleteObject(hBitmap);
  2100. RECT r;
  2101. GetWindowRect(hWnd, &r);
  2102. dib_size = Size2i(r.right - r.left, r.bottom - r.top);
  2103. BITMAPINFO bmi;
  2104. ZeroMemory(&bmi, sizeof(BITMAPINFO));
  2105. bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
  2106. bmi.bmiHeader.biWidth = dib_size.x;
  2107. bmi.bmiHeader.biHeight = dib_size.y;
  2108. bmi.bmiHeader.biPlanes = 1;
  2109. bmi.bmiHeader.biBitCount = 32;
  2110. bmi.bmiHeader.biCompression = BI_RGB;
  2111. bmi.bmiHeader.biSizeImage = dib_size.x * dib_size.y * 4;
  2112. hBitmap = CreateDIBSection(hDC_dib, &bmi, DIB_RGB_COLORS, (void **)&dib_data, nullptr, 0x0);
  2113. SelectObject(hDC_dib, hBitmap);
  2114. ZeroMemory(dib_data, dib_size.x * dib_size.y * 4);
  2115. }
  2116. #endif
  2117. //return 0; // Jump Back
  2118. } break;
  2119. case WM_ENTERSIZEMOVE: {
  2120. Input::get_singleton()->release_pressed_events();
  2121. windows[window_id].move_timer_id = SetTimer(windows[window_id].hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC) nullptr);
  2122. } break;
  2123. case WM_EXITSIZEMOVE: {
  2124. KillTimer(windows[window_id].hWnd, windows[window_id].move_timer_id);
  2125. } break;
  2126. case WM_TIMER: {
  2127. if (wParam == windows[window_id].move_timer_id) {
  2128. _process_key_events();
  2129. if (!Main::is_iterating()) {
  2130. Main::iteration();
  2131. }
  2132. } else if (wParam == windows[window_id].focus_timer_id) {
  2133. _process_activate_event(window_id, windows[window_id].saved_wparam, windows[window_id].saved_lparam);
  2134. KillTimer(windows[window_id].hWnd, wParam);
  2135. windows[window_id].focus_timer_id = 0U;
  2136. }
  2137. } break;
  2138. case WM_SYSKEYDOWN:
  2139. case WM_SYSKEYUP:
  2140. case WM_KEYUP:
  2141. case WM_KEYDOWN: {
  2142. if (wParam == VK_SHIFT)
  2143. shift_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
  2144. if (wParam == VK_CONTROL)
  2145. control_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
  2146. if (wParam == VK_MENU) {
  2147. alt_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
  2148. if (lParam & (1 << 24))
  2149. gr_mem = alt_mem;
  2150. }
  2151. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2152. // When SetCapture is used, ALT+F4 hotkey is ignored by Windows, so handle it ourselves
  2153. if (wParam == VK_F4 && alt_mem && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN)) {
  2154. _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST);
  2155. }
  2156. }
  2157. /*
  2158. if (wParam==VK_WIN) TODO wtf is this?
  2159. meta_mem=uMsg==WM_KEYDOWN;
  2160. */
  2161. [[fallthrough]];
  2162. }
  2163. case WM_CHAR: {
  2164. ERR_BREAK(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
  2165. // Make sure we don't include modifiers for the modifier key itself.
  2166. KeyEvent ke;
  2167. ke.shift = (wParam != VK_SHIFT) ? shift_mem : false;
  2168. ke.alt = (!(wParam == VK_MENU && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN))) ? alt_mem : false;
  2169. ke.control = (wParam != VK_CONTROL) ? control_mem : false;
  2170. ke.meta = meta_mem;
  2171. ke.uMsg = uMsg;
  2172. ke.window_id = window_id;
  2173. if (ke.uMsg == WM_SYSKEYDOWN)
  2174. ke.uMsg = WM_KEYDOWN;
  2175. if (ke.uMsg == WM_SYSKEYUP)
  2176. ke.uMsg = WM_KEYUP;
  2177. ke.wParam = wParam;
  2178. ke.lParam = lParam;
  2179. key_event_buffer[key_event_pos++] = ke;
  2180. } break;
  2181. case WM_INPUTLANGCHANGEREQUEST: {
  2182. // FIXME: Do something?
  2183. } break;
  2184. case WM_TOUCH: {
  2185. BOOL bHandled = FALSE;
  2186. UINT cInputs = LOWORD(wParam);
  2187. PTOUCHINPUT pInputs = memnew_arr(TOUCHINPUT, cInputs);
  2188. if (pInputs) {
  2189. if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) {
  2190. for (UINT i = 0; i < cInputs; i++) {
  2191. TOUCHINPUT ti = pInputs[i];
  2192. POINT touch_pos = {
  2193. TOUCH_COORD_TO_PIXEL(ti.x),
  2194. TOUCH_COORD_TO_PIXEL(ti.y),
  2195. };
  2196. ScreenToClient(hWnd, &touch_pos);
  2197. //do something with each touch input entry
  2198. if (ti.dwFlags & TOUCHEVENTF_MOVE) {
  2199. _drag_event(window_id, touch_pos.x, touch_pos.y, ti.dwID);
  2200. } else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) {
  2201. _touch_event(window_id, ti.dwFlags & TOUCHEVENTF_DOWN, touch_pos.x, touch_pos.y, ti.dwID);
  2202. };
  2203. }
  2204. bHandled = TRUE;
  2205. } else {
  2206. /* handle the error here */
  2207. }
  2208. memdelete_arr(pInputs);
  2209. } else {
  2210. /* handle the error here, probably out of memory */
  2211. }
  2212. if (bHandled) {
  2213. CloseTouchInputHandle((HTOUCHINPUT)lParam);
  2214. return 0;
  2215. };
  2216. } break;
  2217. case WM_DEVICECHANGE: {
  2218. joypad->probe_joypads();
  2219. } break;
  2220. case WM_SETCURSOR: {
  2221. if (LOWORD(lParam) == HTCLIENT) {
  2222. if (windows[window_id].window_has_focus && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED)) {
  2223. //Hide the cursor
  2224. if (hCursor == nullptr) {
  2225. hCursor = SetCursor(nullptr);
  2226. } else {
  2227. SetCursor(nullptr);
  2228. }
  2229. } else {
  2230. if (hCursor != nullptr) {
  2231. CursorShape c = cursor_shape;
  2232. cursor_shape = CURSOR_MAX;
  2233. cursor_set_shape(c);
  2234. hCursor = nullptr;
  2235. }
  2236. }
  2237. }
  2238. } break;
  2239. case WM_DROPFILES: {
  2240. HDROP hDropInfo = (HDROP)wParam;
  2241. const int buffsize = 4096;
  2242. WCHAR buf[buffsize];
  2243. int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF, nullptr, 0);
  2244. Vector<String> files;
  2245. for (int i = 0; i < fcount; i++) {
  2246. DragQueryFileW(hDropInfo, i, buf, buffsize);
  2247. String file = String::utf16((const char16_t *)buf);
  2248. files.push_back(file);
  2249. }
  2250. if (files.size() && !windows[window_id].drop_files_callback.is_null()) {
  2251. Variant v = files;
  2252. Variant *vp = &v;
  2253. Variant ret;
  2254. Callable::CallError ce;
  2255. windows[window_id].drop_files_callback.call((const Variant **)&vp, 1, ret, ce);
  2256. }
  2257. } break;
  2258. default: {
  2259. if (user_proc) {
  2260. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  2261. };
  2262. };
  2263. }
  2264. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  2265. }
  2266. LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  2267. DisplayServerWindows *ds_win = static_cast<DisplayServerWindows *>(DisplayServer::get_singleton());
  2268. if (ds_win)
  2269. return ds_win->WndProc(hWnd, uMsg, wParam, lParam);
  2270. else
  2271. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  2272. }
  2273. void DisplayServerWindows::_process_activate_event(WindowID p_window_id, WPARAM wParam, LPARAM lParam) {
  2274. if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE) {
  2275. _send_window_event(windows[p_window_id], WINDOW_EVENT_FOCUS_IN);
  2276. windows[p_window_id].window_focused = true;
  2277. alt_mem = false;
  2278. control_mem = false;
  2279. shift_mem = false;
  2280. } else { // WM_INACTIVE
  2281. Input::get_singleton()->release_pressed_events();
  2282. _send_window_event(windows[p_window_id], WINDOW_EVENT_FOCUS_OUT);
  2283. windows[p_window_id].window_focused = false;
  2284. alt_mem = false;
  2285. }
  2286. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[p_window_id].wtctx) {
  2287. wintab_WTEnable(windows[p_window_id].wtctx, GET_WM_ACTIVATE_STATE(wParam, lParam));
  2288. }
  2289. }
  2290. void DisplayServerWindows::_process_key_events() {
  2291. for (int i = 0; i < key_event_pos; i++) {
  2292. KeyEvent &ke = key_event_buffer[i];
  2293. switch (ke.uMsg) {
  2294. case WM_CHAR: {
  2295. // extended keys should only be processed as WM_KEYDOWN message.
  2296. if (!KeyMappingWindows::is_extended_key(ke.wParam) && ((i == 0 && ke.uMsg == WM_CHAR) || (i > 0 && key_event_buffer[i - 1].uMsg == WM_CHAR))) {
  2297. static char32_t prev_wc = 0;
  2298. char32_t unicode = ke.wParam;
  2299. if ((unicode & 0xfffffc00) == 0xd800) {
  2300. if (prev_wc != 0) {
  2301. ERR_PRINT("invalid utf16 surrogate input");
  2302. }
  2303. prev_wc = unicode;
  2304. break; // Skip surrogate.
  2305. } else if ((unicode & 0xfffffc00) == 0xdc00) {
  2306. if (prev_wc == 0) {
  2307. ERR_PRINT("invalid utf16 surrogate input");
  2308. break; // Skip invalid surrogate.
  2309. }
  2310. unicode = (prev_wc << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  2311. prev_wc = 0;
  2312. } else {
  2313. prev_wc = 0;
  2314. }
  2315. Ref<InputEventKey> k;
  2316. k.instance();
  2317. k->set_window_id(ke.window_id);
  2318. k->set_shift(ke.shift);
  2319. k->set_alt(ke.alt);
  2320. k->set_control(ke.control);
  2321. k->set_metakey(ke.meta);
  2322. k->set_pressed(true);
  2323. k->set_keycode(KeyMappingWindows::get_keysym(ke.wParam));
  2324. k->set_physical_keycode(KeyMappingWindows::get_scansym((ke.lParam >> 16) & 0xFF, ke.lParam & (1 << 24)));
  2325. k->set_unicode(unicode);
  2326. if (k->get_unicode() && gr_mem) {
  2327. k->set_alt(false);
  2328. k->set_control(false);
  2329. }
  2330. if (k->get_unicode() < 32)
  2331. k->set_unicode(0);
  2332. Input::get_singleton()->accumulate_input_event(k);
  2333. }
  2334. //do nothing
  2335. } break;
  2336. case WM_KEYUP:
  2337. case WM_KEYDOWN: {
  2338. Ref<InputEventKey> k;
  2339. k.instance();
  2340. k->set_window_id(ke.window_id);
  2341. k->set_shift(ke.shift);
  2342. k->set_alt(ke.alt);
  2343. k->set_control(ke.control);
  2344. k->set_metakey(ke.meta);
  2345. k->set_pressed(ke.uMsg == WM_KEYDOWN);
  2346. if ((ke.lParam & (1 << 24)) && (ke.wParam == VK_RETURN)) {
  2347. // Special case for Numpad Enter key
  2348. k->set_keycode(KEY_KP_ENTER);
  2349. } else {
  2350. k->set_keycode(KeyMappingWindows::get_keysym(ke.wParam));
  2351. }
  2352. k->set_physical_keycode(KeyMappingWindows::get_scansym((ke.lParam >> 16) & 0xFF, ke.lParam & (1 << 24)));
  2353. if (i + 1 < key_event_pos && key_event_buffer[i + 1].uMsg == WM_CHAR) {
  2354. char32_t unicode = key_event_buffer[i + 1].wParam;
  2355. static char32_t prev_wck = 0;
  2356. if ((unicode & 0xfffffc00) == 0xd800) {
  2357. if (prev_wck != 0) {
  2358. ERR_PRINT("invalid utf16 surrogate input");
  2359. }
  2360. prev_wck = unicode;
  2361. break; // Skip surrogate.
  2362. } else if ((unicode & 0xfffffc00) == 0xdc00) {
  2363. if (prev_wck == 0) {
  2364. ERR_PRINT("invalid utf16 surrogate input");
  2365. break; // Skip invalid surrogate.
  2366. }
  2367. unicode = (prev_wck << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  2368. prev_wck = 0;
  2369. } else {
  2370. prev_wck = 0;
  2371. }
  2372. k->set_unicode(unicode);
  2373. }
  2374. if (k->get_unicode() && gr_mem) {
  2375. k->set_alt(false);
  2376. k->set_control(false);
  2377. }
  2378. if (k->get_unicode() < 32)
  2379. k->set_unicode(0);
  2380. k->set_echo((ke.uMsg == WM_KEYDOWN && (ke.lParam & (1 << 30))));
  2381. Input::get_singleton()->accumulate_input_event(k);
  2382. } break;
  2383. }
  2384. }
  2385. key_event_pos = 0;
  2386. }
  2387. void DisplayServerWindows::_update_tablet_ctx(const String &p_old_driver, const String &p_new_driver) {
  2388. for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
  2389. WindowData &wd = E->get();
  2390. wd.block_mm = false;
  2391. if ((p_old_driver == "wintab") && wintab_available && wd.wtctx) {
  2392. wintab_WTEnable(wd.wtctx, false);
  2393. wintab_WTClose(wd.wtctx);
  2394. wd.wtctx = 0;
  2395. }
  2396. if ((p_new_driver == "wintab") && wintab_available) {
  2397. wintab_WTInfo(WTI_DEFSYSCTX, 0, &wd.wtlc);
  2398. wd.wtlc.lcOptions |= CXO_MESSAGES;
  2399. wd.wtlc.lcPktData = PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE | PK_ORIENTATION;
  2400. wd.wtlc.lcMoveMask = PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE;
  2401. wd.wtlc.lcPktMode = 0;
  2402. wd.wtlc.lcOutOrgX = 0;
  2403. wd.wtlc.lcOutExtX = wd.wtlc.lcInExtX;
  2404. wd.wtlc.lcOutOrgY = 0;
  2405. wd.wtlc.lcOutExtY = -wd.wtlc.lcInExtY;
  2406. wd.wtctx = wintab_WTOpen(wd.hWnd, &wd.wtlc, false);
  2407. if (wd.wtctx) {
  2408. wintab_WTEnable(wd.wtctx, true);
  2409. AXIS pressure;
  2410. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_NPRESSURE, &pressure)) {
  2411. wd.min_pressure = int(pressure.axMin);
  2412. wd.max_pressure = int(pressure.axMax);
  2413. }
  2414. AXIS orientation[3];
  2415. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_ORIENTATION, &orientation)) {
  2416. wd.tilt_supported = orientation[0].axResolution && orientation[1].axResolution;
  2417. }
  2418. wintab_WTEnable(wd.wtctx, true);
  2419. } else {
  2420. print_verbose("WinTab context creation failed.");
  2421. }
  2422. }
  2423. }
  2424. }
  2425. DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode, uint32_t p_flags, const Rect2i &p_rect) {
  2426. DWORD dwExStyle;
  2427. DWORD dwStyle;
  2428. _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);
  2429. RECT WindowRect;
  2430. WindowRect.left = p_rect.position.x;
  2431. WindowRect.right = p_rect.position.x + p_rect.size.x;
  2432. WindowRect.top = p_rect.position.y;
  2433. WindowRect.bottom = p_rect.position.y + p_rect.size.y;
  2434. if (p_mode == WINDOW_MODE_FULLSCREEN) {
  2435. int nearest_area = 0;
  2436. Rect2i screen_rect;
  2437. for (int i = 0; i < get_screen_count(); i++) {
  2438. Rect2i r;
  2439. r.position = screen_get_position(i);
  2440. r.size = screen_get_size(i);
  2441. Rect2 inters = r.intersection(p_rect);
  2442. int area = inters.size.width * inters.size.height;
  2443. if (area >= nearest_area) {
  2444. screen_rect = r;
  2445. nearest_area = area;
  2446. }
  2447. }
  2448. WindowRect.left = screen_rect.position.x;
  2449. WindowRect.right = screen_rect.position.x + screen_rect.size.x;
  2450. WindowRect.top = screen_rect.position.y;
  2451. WindowRect.bottom = screen_rect.position.y + screen_rect.size.y;
  2452. }
  2453. AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
  2454. WindowID id = window_id_counter;
  2455. {
  2456. WindowData &wd = windows[id];
  2457. wd.hWnd = CreateWindowExW(
  2458. dwExStyle,
  2459. L"Engine", L"",
  2460. dwStyle,
  2461. // (GetSystemMetrics(SM_CXSCREEN) - WindowRect.right) / 2,
  2462. // (GetSystemMetrics(SM_CYSCREEN) - WindowRect.bottom) / 2,
  2463. WindowRect.left,
  2464. WindowRect.top,
  2465. WindowRect.right - WindowRect.left,
  2466. WindowRect.bottom - WindowRect.top,
  2467. nullptr, nullptr, hInstance, nullptr);
  2468. if (!wd.hWnd) {
  2469. MessageBoxW(nullptr, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
  2470. windows.erase(id);
  2471. return INVALID_WINDOW_ID;
  2472. }
  2473. if (p_mode != WINDOW_MODE_FULLSCREEN) {
  2474. wd.pre_fs_valid = true;
  2475. }
  2476. #ifdef VULKAN_ENABLED
  2477. if (rendering_driver == "vulkan") {
  2478. if (context_vulkan->window_create(id, wd.hWnd, hInstance, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top) == -1) {
  2479. memdelete(context_vulkan);
  2480. context_vulkan = nullptr;
  2481. windows.erase(id);
  2482. ERR_FAIL_V_MSG(INVALID_WINDOW_ID, "Failed to create Vulkan Window.");
  2483. }
  2484. }
  2485. #endif
  2486. RegisterTouchWindow(wd.hWnd, 0);
  2487. TRACKMOUSEEVENT tme;
  2488. tme.cbSize = sizeof(TRACKMOUSEEVENT);
  2489. tme.dwFlags = TME_LEAVE;
  2490. tme.hwndTrack = wd.hWnd;
  2491. tme.dwHoverTime = HOVER_DEFAULT;
  2492. TrackMouseEvent(&tme);
  2493. DragAcceptFiles(wd.hWnd, true);
  2494. if ((tablet_get_current_driver() == "wintab") && wintab_available) {
  2495. wintab_WTInfo(WTI_DEFSYSCTX, 0, &wd.wtlc);
  2496. wd.wtlc.lcOptions |= CXO_MESSAGES;
  2497. wd.wtlc.lcPktData = PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE | PK_ORIENTATION;
  2498. wd.wtlc.lcMoveMask = PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE;
  2499. wd.wtlc.lcPktMode = 0;
  2500. wd.wtlc.lcOutOrgX = 0;
  2501. wd.wtlc.lcOutExtX = wd.wtlc.lcInExtX;
  2502. wd.wtlc.lcOutOrgY = 0;
  2503. wd.wtlc.lcOutExtY = -wd.wtlc.lcInExtY;
  2504. wd.wtctx = wintab_WTOpen(wd.hWnd, &wd.wtlc, false);
  2505. if (wd.wtctx) {
  2506. wintab_WTEnable(wd.wtctx, true);
  2507. AXIS pressure;
  2508. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_NPRESSURE, &pressure)) {
  2509. wd.min_pressure = int(pressure.axMin);
  2510. wd.max_pressure = int(pressure.axMax);
  2511. }
  2512. AXIS orientation[3];
  2513. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_ORIENTATION, &orientation)) {
  2514. wd.tilt_supported = orientation[0].axResolution && orientation[1].axResolution;
  2515. }
  2516. } else {
  2517. print_verbose("WinTab context creation failed.");
  2518. }
  2519. } else {
  2520. wd.wtctx = 0;
  2521. }
  2522. wd.last_pressure = 0;
  2523. wd.last_pressure_update = 0;
  2524. wd.last_tilt = Vector2();
  2525. // IME
  2526. wd.im_himc = ImmGetContext(wd.hWnd);
  2527. ImmReleaseContext(wd.hWnd, wd.im_himc);
  2528. wd.im_position = Vector2();
  2529. wd.last_pos = p_rect.position;
  2530. wd.width = p_rect.size.width;
  2531. wd.height = p_rect.size.height;
  2532. window_id_counter++;
  2533. }
  2534. return id;
  2535. }
  2536. // WinTab API
  2537. bool DisplayServerWindows::wintab_available = false;
  2538. WTOpenPtr DisplayServerWindows::wintab_WTOpen = nullptr;
  2539. WTClosePtr DisplayServerWindows::wintab_WTClose = nullptr;
  2540. WTInfoPtr DisplayServerWindows::wintab_WTInfo = nullptr;
  2541. WTPacketPtr DisplayServerWindows::wintab_WTPacket = nullptr;
  2542. WTEnablePtr DisplayServerWindows::wintab_WTEnable = nullptr;
  2543. // Windows Ink API
  2544. bool DisplayServerWindows::winink_available = false;
  2545. GetPointerTypePtr DisplayServerWindows::win8p_GetPointerType = nullptr;
  2546. GetPointerPenInfoPtr DisplayServerWindows::win8p_GetPointerPenInfo = nullptr;
  2547. typedef enum _SHC_PROCESS_DPI_AWARENESS {
  2548. SHC_PROCESS_DPI_UNAWARE = 0,
  2549. SHC_PROCESS_SYSTEM_DPI_AWARE = 1,
  2550. SHC_PROCESS_PER_MONITOR_DPI_AWARE = 2
  2551. } SHC_PROCESS_DPI_AWARENESS;
  2552. int DisplayServerWindows::tablet_get_driver_count() const {
  2553. return tablet_drivers.size();
  2554. }
  2555. String DisplayServerWindows::tablet_get_driver_name(int p_driver) const {
  2556. if (p_driver < 0 || p_driver >= tablet_drivers.size()) {
  2557. return "";
  2558. } else {
  2559. return tablet_drivers[p_driver];
  2560. }
  2561. }
  2562. String DisplayServerWindows::tablet_get_current_driver() const {
  2563. return tablet_driver;
  2564. }
  2565. void DisplayServerWindows::tablet_set_current_driver(const String &p_driver) {
  2566. if (tablet_get_driver_count() == 0) {
  2567. return;
  2568. }
  2569. bool found = false;
  2570. for (int i = 0; i < tablet_get_driver_count(); i++) {
  2571. if (p_driver == tablet_get_driver_name(i)) {
  2572. found = true;
  2573. }
  2574. }
  2575. if (found) {
  2576. _update_tablet_ctx(tablet_driver, p_driver);
  2577. tablet_driver = p_driver;
  2578. } else {
  2579. ERR_PRINT("Unknown tablet driver " + p_driver + ".");
  2580. }
  2581. }
  2582. DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
  2583. drop_events = false;
  2584. key_event_pos = 0;
  2585. alt_mem = false;
  2586. gr_mem = false;
  2587. shift_mem = false;
  2588. control_mem = false;
  2589. meta_mem = false;
  2590. console_visible = IsWindowVisible(GetConsoleWindow());
  2591. hInstance = ((OS_Windows *)OS::get_singleton())->get_hinstance();
  2592. pressrc = 0;
  2593. old_invalid = true;
  2594. mouse_mode = MOUSE_MODE_VISIBLE;
  2595. outside = true;
  2596. //Note: Wacom WinTab driver API for pen input, for devices incompatible with Windows Ink.
  2597. HMODULE wintab_lib = LoadLibraryW(L"wintab32.dll");
  2598. if (wintab_lib) {
  2599. wintab_WTOpen = (WTOpenPtr)GetProcAddress(wintab_lib, "WTOpenW");
  2600. wintab_WTClose = (WTClosePtr)GetProcAddress(wintab_lib, "WTClose");
  2601. wintab_WTInfo = (WTInfoPtr)GetProcAddress(wintab_lib, "WTInfoW");
  2602. wintab_WTPacket = (WTPacketPtr)GetProcAddress(wintab_lib, "WTPacket");
  2603. wintab_WTEnable = (WTEnablePtr)GetProcAddress(wintab_lib, "WTEnable");
  2604. wintab_available = wintab_WTOpen && wintab_WTClose && wintab_WTInfo && wintab_WTPacket && wintab_WTEnable;
  2605. }
  2606. if (wintab_available) {
  2607. tablet_drivers.push_back("wintab");
  2608. }
  2609. //Note: Windows Ink API for pen input, available on Windows 8+ only.
  2610. HMODULE user32_lib = LoadLibraryW(L"user32.dll");
  2611. if (user32_lib) {
  2612. win8p_GetPointerType = (GetPointerTypePtr)GetProcAddress(user32_lib, "GetPointerType");
  2613. win8p_GetPointerPenInfo = (GetPointerPenInfoPtr)GetProcAddress(user32_lib, "GetPointerPenInfo");
  2614. winink_available = win8p_GetPointerType && win8p_GetPointerPenInfo;
  2615. }
  2616. if (winink_available) {
  2617. tablet_drivers.push_back("winink");
  2618. }
  2619. if (OS::get_singleton()->is_hidpi_allowed()) {
  2620. HMODULE Shcore = LoadLibraryW(L"Shcore.dll");
  2621. if (Shcore != nullptr) {
  2622. typedef HRESULT(WINAPI * SetProcessDpiAwareness_t)(SHC_PROCESS_DPI_AWARENESS);
  2623. SetProcessDpiAwareness_t SetProcessDpiAwareness = (SetProcessDpiAwareness_t)GetProcAddress(Shcore, "SetProcessDpiAwareness");
  2624. if (SetProcessDpiAwareness) {
  2625. SetProcessDpiAwareness(SHC_PROCESS_SYSTEM_DPI_AWARE);
  2626. }
  2627. }
  2628. }
  2629. memset(&wc, 0, sizeof(WNDCLASSEXW));
  2630. wc.cbSize = sizeof(WNDCLASSEXW);
  2631. wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
  2632. wc.lpfnWndProc = (WNDPROC)::WndProc;
  2633. wc.cbClsExtra = 0;
  2634. wc.cbWndExtra = 0;
  2635. //wc.hInstance = hInstance;
  2636. wc.hInstance = hInstance ? hInstance : GetModuleHandle(nullptr);
  2637. wc.hIcon = LoadIcon(nullptr, IDI_WINLOGO);
  2638. wc.hCursor = nullptr; //LoadCursor(nullptr, IDC_ARROW);
  2639. wc.hbrBackground = nullptr;
  2640. wc.lpszMenuName = nullptr;
  2641. wc.lpszClassName = L"Engine";
  2642. if (!RegisterClassExW(&wc)) {
  2643. MessageBox(nullptr, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
  2644. r_error = ERR_UNAVAILABLE;
  2645. return;
  2646. }
  2647. use_raw_input = true;
  2648. RAWINPUTDEVICE Rid[1];
  2649. Rid[0].usUsagePage = 0x01;
  2650. Rid[0].usUsage = 0x02;
  2651. Rid[0].dwFlags = 0;
  2652. Rid[0].hwndTarget = 0;
  2653. if (RegisterRawInputDevices(Rid, 1, sizeof(Rid[0])) == FALSE) {
  2654. //registration failed.
  2655. use_raw_input = false;
  2656. }
  2657. rendering_driver = "vulkan";
  2658. #if defined(VULKAN_ENABLED)
  2659. if (rendering_driver == "vulkan") {
  2660. context_vulkan = memnew(VulkanContextWindows);
  2661. if (context_vulkan->initialize() != OK) {
  2662. memdelete(context_vulkan);
  2663. context_vulkan = nullptr;
  2664. r_error = ERR_UNAVAILABLE;
  2665. return;
  2666. }
  2667. }
  2668. #endif
  2669. #if defined(OPENGL_ENABLED)
  2670. if (rendering_driver_index == VIDEO_DRIVER_GLES2) {
  2671. context_gles2 = memnew(ContextGL_Windows(hWnd, false));
  2672. if (context_gles2->initialize() != OK) {
  2673. memdelete(context_gles2);
  2674. context_gles2 = nullptr;
  2675. ERR_FAIL_V(ERR_UNAVAILABLE);
  2676. }
  2677. context_gles2->set_use_vsync(video_mode.use_vsync);
  2678. set_vsync_via_compositor(video_mode.vsync_via_compositor);
  2679. if (RasterizerGLES2::is_viable() == OK) {
  2680. RasterizerGLES2::register_config();
  2681. RasterizerGLES2::make_current();
  2682. } else {
  2683. memdelete(context_gles2);
  2684. context_gles2 = nullptr;
  2685. ERR_FAIL_V(ERR_UNAVAILABLE);
  2686. }
  2687. }
  2688. #endif
  2689. Point2i window_position(
  2690. (screen_get_size(0).width - p_resolution.width) / 2,
  2691. (screen_get_size(0).height - p_resolution.height) / 2);
  2692. WindowID main_window = _create_window(p_mode, 0, Rect2i(window_position, p_resolution));
  2693. ERR_FAIL_COND_MSG(main_window == INVALID_WINDOW_ID, "Failed to create main window.");
  2694. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  2695. if (p_flags & (1 << i)) {
  2696. window_set_flag(WindowFlags(i), true, main_window);
  2697. }
  2698. }
  2699. show_window(MAIN_WINDOW_ID);
  2700. #if defined(VULKAN_ENABLED)
  2701. if (rendering_driver == "vulkan") {
  2702. rendering_device_vulkan = memnew(RenderingDeviceVulkan);
  2703. rendering_device_vulkan->initialize(context_vulkan);
  2704. RendererCompositorRD::make_current();
  2705. }
  2706. #endif
  2707. //set_ime_active(false);
  2708. if (!OS::get_singleton()->is_in_low_processor_usage_mode()) {
  2709. //SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
  2710. SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
  2711. DWORD index = 0;
  2712. HANDLE handle = AvSetMmThreadCharacteristics("Games", &index);
  2713. if (handle)
  2714. AvSetMmThreadPriority(handle, AVRT_PRIORITY_CRITICAL);
  2715. // This is needed to make sure that background work does not starve the main thread.
  2716. // This is only setting priority of this thread, not the whole process.
  2717. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  2718. }
  2719. cursor_shape = CURSOR_ARROW;
  2720. _update_real_mouse_position(MAIN_WINDOW_ID);
  2721. joypad = new JoypadWindows(&windows[MAIN_WINDOW_ID].hWnd);
  2722. r_error = OK;
  2723. ((OS_Windows *)OS::get_singleton())->set_main_window(windows[MAIN_WINDOW_ID].hWnd);
  2724. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
  2725. }
  2726. Vector<String> DisplayServerWindows::get_rendering_drivers_func() {
  2727. Vector<String> drivers;
  2728. #ifdef VULKAN_ENABLED
  2729. drivers.push_back("vulkan");
  2730. #endif
  2731. #ifdef OPENGL_ENABLED
  2732. drivers.push_back("opengl");
  2733. #endif
  2734. return drivers;
  2735. }
  2736. DisplayServer *DisplayServerWindows::create_func(const String &p_rendering_driver, WindowMode p_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
  2737. DisplayServer *ds = memnew(DisplayServerWindows(p_rendering_driver, p_mode, p_flags, p_resolution, r_error));
  2738. if (r_error != OK) {
  2739. ds->alert("Your video card driver does not support any of the supported Vulkan versions.\n"
  2740. "Please update your drivers or if you have a very old or integrated GPU upgrade it.",
  2741. "Unable to initialize Video driver");
  2742. }
  2743. return ds;
  2744. }
  2745. void DisplayServerWindows::register_windows_driver() {
  2746. register_create_function("windows", create_func, get_rendering_drivers_func);
  2747. }
  2748. DisplayServerWindows::~DisplayServerWindows() {
  2749. delete joypad;
  2750. touch_state.clear();
  2751. cursors_cache.clear();
  2752. if (user_proc) {
  2753. SetWindowLongPtr(windows[MAIN_WINDOW_ID].hWnd, GWLP_WNDPROC, (LONG_PTR)user_proc);
  2754. };
  2755. if (windows.has(MAIN_WINDOW_ID)) {
  2756. #ifdef VULKAN_ENABLED
  2757. if (rendering_driver == "vulkan") {
  2758. context_vulkan->window_destroy(MAIN_WINDOW_ID);
  2759. }
  2760. #endif
  2761. if (wintab_available && windows[MAIN_WINDOW_ID].wtctx) {
  2762. wintab_WTClose(windows[MAIN_WINDOW_ID].wtctx);
  2763. windows[MAIN_WINDOW_ID].wtctx = 0;
  2764. }
  2765. DestroyWindow(windows[MAIN_WINDOW_ID].hWnd);
  2766. }
  2767. #if defined(VULKAN_ENABLED)
  2768. if (rendering_driver == "vulkan") {
  2769. if (rendering_device_vulkan) {
  2770. rendering_device_vulkan->finalize();
  2771. memdelete(rendering_device_vulkan);
  2772. }
  2773. if (context_vulkan)
  2774. memdelete(context_vulkan);
  2775. }
  2776. #endif
  2777. }