SDL_windowsevents.c 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_VIDEO_DRIVER_WINDOWS
  20. #include "SDL_windowsvideo.h"
  21. #include "../../events/SDL_events_c.h"
  22. #include "../../events/SDL_touch_c.h"
  23. #include "../../events/scancodes_windows.h"
  24. #include "../../main/SDL_main_callbacks.h"
  25. #include "../../core/windows/SDL_hid.h"
  26. // Dropfile support
  27. #include <shellapi.h>
  28. // Device names
  29. #include <setupapi.h>
  30. // For GET_X_LPARAM, GET_Y_LPARAM.
  31. #include <windowsx.h>
  32. // For WM_TABLET_QUERYSYSTEMGESTURESTATUS et. al.
  33. #ifdef HAVE_TPCSHRD_H
  34. #include <tpcshrd.h>
  35. #endif // HAVE_TPCSHRD_H
  36. #if 0
  37. #define WMMSG_DEBUG
  38. #endif
  39. #ifdef WMMSG_DEBUG
  40. #include <stdio.h>
  41. #include "wmmsg.h"
  42. #endif
  43. #ifdef HAVE_SHOBJIDL_CORE_H
  44. #include <shobjidl_core.h>
  45. #endif
  46. #ifdef SDL_PLATFORM_GDK
  47. #include "../../core/gdk/SDL_gdk.h"
  48. #endif
  49. // #define HIGHDPI_DEBUG
  50. // Make sure XBUTTON stuff is defined that isn't in older Platform SDKs...
  51. #ifndef WM_XBUTTONDOWN
  52. #define WM_XBUTTONDOWN 0x020B
  53. #endif
  54. #ifndef WM_XBUTTONUP
  55. #define WM_XBUTTONUP 0x020C
  56. #endif
  57. #ifndef GET_XBUTTON_WPARAM
  58. #define GET_XBUTTON_WPARAM(w) (HIWORD(w))
  59. #endif
  60. #ifndef WM_INPUT
  61. #define WM_INPUT 0x00ff
  62. #endif
  63. #ifndef WM_TOUCH
  64. #define WM_TOUCH 0x0240
  65. #endif
  66. #ifndef WM_MOUSEHWHEEL
  67. #define WM_MOUSEHWHEEL 0x020E
  68. #endif
  69. #ifndef RI_MOUSE_HWHEEL
  70. #define RI_MOUSE_HWHEEL 0x0800
  71. #endif
  72. #ifndef WM_POINTERUPDATE
  73. #define WM_POINTERUPDATE 0x0245
  74. #endif
  75. #ifndef WM_POINTERDOWN
  76. #define WM_POINTERDOWN 0x0246
  77. #endif
  78. #ifndef WM_POINTERUP
  79. #define WM_POINTERUP 0x0247
  80. #endif
  81. #ifndef WM_POINTERENTER
  82. #define WM_POINTERENTER 0x0249
  83. #endif
  84. #ifndef WM_POINTERLEAVE
  85. #define WM_POINTERLEAVE 0x024A
  86. #endif
  87. #ifndef WM_POINTERCAPTURECHANGED
  88. #define WM_POINTERCAPTURECHANGED 0x024C
  89. #endif
  90. #ifndef WM_UNICHAR
  91. #define WM_UNICHAR 0x0109
  92. #endif
  93. #ifndef WM_DPICHANGED
  94. #define WM_DPICHANGED 0x02E0
  95. #endif
  96. #ifndef WM_GETDPISCALEDSIZE
  97. #define WM_GETDPISCALEDSIZE 0x02E4
  98. #endif
  99. #ifndef TOUCHEVENTF_PEN
  100. #define TOUCHEVENTF_PEN 0x0040
  101. #endif
  102. #ifndef MAPVK_VK_TO_VSC_EX
  103. #define MAPVK_VK_TO_VSC_EX 4
  104. #endif
  105. #ifndef WC_ERR_INVALID_CHARS
  106. #define WC_ERR_INVALID_CHARS 0x00000080
  107. #endif
  108. #ifndef IS_HIGH_SURROGATE
  109. #define IS_HIGH_SURROGATE(x) (((x) >= 0xd800) && ((x) <= 0xdbff))
  110. #endif
  111. #ifndef USER_TIMER_MINIMUM
  112. #define USER_TIMER_MINIMUM 0x0000000A
  113. #endif
  114. // Used to compare Windows message timestamps
  115. #define SDL_TICKS_PASSED(A, B) ((Sint32)((B) - (A)) <= 0)
  116. #ifdef _WIN64
  117. typedef Uint64 QWORD; // Needed for NEXTRAWINPUTBLOCK()
  118. #endif
  119. static bool SDL_processing_messages;
  120. static DWORD message_tick;
  121. static Uint64 timestamp_offset;
  122. static void WIN_SetMessageTick(DWORD tick)
  123. {
  124. message_tick = tick;
  125. }
  126. static Uint64 WIN_GetEventTimestamp(void)
  127. {
  128. const Uint64 TIMESTAMP_WRAP_OFFSET = SDL_MS_TO_NS(0x100000000LL);
  129. Uint64 timestamp, now;
  130. if (!SDL_processing_messages) {
  131. // message_tick isn't valid, just use the current time
  132. return 0;
  133. }
  134. now = SDL_GetTicksNS();
  135. timestamp = SDL_MS_TO_NS(message_tick);
  136. timestamp += timestamp_offset;
  137. if (!timestamp_offset) {
  138. // Initializing timestamp offset
  139. //SDL_Log("Initializing timestamp offset");
  140. timestamp_offset = (now - timestamp);
  141. timestamp = now;
  142. } else if ((Sint64)(now - timestamp - TIMESTAMP_WRAP_OFFSET) >= 0) {
  143. // The windows message tick wrapped
  144. //SDL_Log("Adjusting timestamp offset for wrapping tick");
  145. timestamp_offset += TIMESTAMP_WRAP_OFFSET;
  146. timestamp += TIMESTAMP_WRAP_OFFSET;
  147. } else if (timestamp > now) {
  148. // We got a newer timestamp, but it can't be newer than now, so adjust our offset
  149. //SDL_Log("Adjusting timestamp offset, %.2f ms newer", (double)(timestamp - now) / SDL_NS_PER_MS);
  150. timestamp_offset -= (timestamp - now);
  151. timestamp = now;
  152. }
  153. return timestamp;
  154. }
  155. // A message hook called before TranslateMessage()
  156. static SDL_WindowsMessageHook g_WindowsMessageHook = NULL;
  157. static void *g_WindowsMessageHookData = NULL;
  158. void SDL_SetWindowsMessageHook(SDL_WindowsMessageHook callback, void *userdata)
  159. {
  160. g_WindowsMessageHook = callback;
  161. g_WindowsMessageHookData = userdata;
  162. }
  163. static SDL_Scancode WindowsScanCodeToSDLScanCode(LPARAM lParam, WPARAM wParam, Uint16 *rawcode, bool *virtual_key)
  164. {
  165. SDL_Scancode code;
  166. Uint8 index;
  167. Uint16 keyFlags = HIWORD(lParam);
  168. Uint16 scanCode = LOBYTE(keyFlags);
  169. /* On-Screen Keyboard can send wrong scan codes with high-order bit set (key break code).
  170. * Strip high-order bit. */
  171. scanCode &= ~0x80;
  172. *virtual_key = (scanCode == 0);
  173. if (scanCode != 0) {
  174. if ((keyFlags & KF_EXTENDED) == KF_EXTENDED) {
  175. scanCode = MAKEWORD(scanCode, 0xe0);
  176. } else if (scanCode == 0x45) {
  177. // Pause
  178. scanCode = 0xe046;
  179. }
  180. } else {
  181. Uint16 vkCode = LOWORD(wParam);
  182. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  183. /* Windows may not report scan codes for some buttons (multimedia buttons etc).
  184. * Get scan code from the VK code.*/
  185. scanCode = LOWORD(MapVirtualKey(vkCode, WIN_IsWindowsXP() ? MAPVK_VK_TO_VSC : MAPVK_VK_TO_VSC_EX));
  186. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  187. /* Pause/Break key have a special scan code with 0xe1 prefix.
  188. * Use Pause scan code that is used in Win32. */
  189. if (scanCode == 0xe11d) {
  190. scanCode = 0xe046;
  191. }
  192. }
  193. // Pack scan code into one byte to make the index.
  194. index = LOBYTE(scanCode) | (HIBYTE(scanCode) ? 0x80 : 0x00);
  195. code = windows_scancode_table[index];
  196. *rawcode = scanCode;
  197. return code;
  198. }
  199. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  200. static bool WIN_ShouldIgnoreFocusClick(SDL_WindowData *data)
  201. {
  202. return !SDL_WINDOW_IS_POPUP(data->window) &&
  203. !SDL_GetHintBoolean(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, false);
  204. }
  205. static void WIN_CheckWParamMouseButton(Uint64 timestamp, bool bwParamMousePressed, Uint32 mouseFlags, bool bSwapButtons, SDL_WindowData *data, Uint8 button, SDL_MouseID mouseID)
  206. {
  207. if (bSwapButtons) {
  208. if (button == SDL_BUTTON_LEFT) {
  209. button = SDL_BUTTON_RIGHT;
  210. } else if (button == SDL_BUTTON_RIGHT) {
  211. button = SDL_BUTTON_LEFT;
  212. }
  213. }
  214. if (data->focus_click_pending & SDL_BUTTON_MASK(button)) {
  215. // Ignore the button click for activation
  216. if (!bwParamMousePressed) {
  217. data->focus_click_pending &= ~SDL_BUTTON_MASK(button);
  218. WIN_UpdateClipCursor(data->window);
  219. }
  220. return;
  221. }
  222. if (bwParamMousePressed && !(mouseFlags & SDL_BUTTON_MASK(button))) {
  223. SDL_SendMouseButton(timestamp, data->window, mouseID, button, true);
  224. } else if (!bwParamMousePressed && (mouseFlags & SDL_BUTTON_MASK(button))) {
  225. SDL_SendMouseButton(timestamp, data->window, mouseID, button, false);
  226. }
  227. }
  228. /*
  229. * Some windows systems fail to send a WM_LBUTTONDOWN sometimes, but each mouse move contains the current button state also
  230. * so this function reconciles our view of the world with the current buttons reported by windows
  231. */
  232. static void WIN_CheckWParamMouseButtons(Uint64 timestamp, WPARAM wParam, SDL_WindowData *data, SDL_MouseID mouseID)
  233. {
  234. if (wParam != data->mouse_button_flags) {
  235. SDL_MouseButtonFlags mouseFlags = SDL_GetMouseState(NULL, NULL);
  236. // WM_LBUTTONDOWN and friends handle button swapping for us. No need to check SM_SWAPBUTTON here.
  237. WIN_CheckWParamMouseButton(timestamp, (wParam & MK_LBUTTON), mouseFlags, false, data, SDL_BUTTON_LEFT, mouseID);
  238. WIN_CheckWParamMouseButton(timestamp, (wParam & MK_MBUTTON), mouseFlags, false, data, SDL_BUTTON_MIDDLE, mouseID);
  239. WIN_CheckWParamMouseButton(timestamp, (wParam & MK_RBUTTON), mouseFlags, false, data, SDL_BUTTON_RIGHT, mouseID);
  240. WIN_CheckWParamMouseButton(timestamp, (wParam & MK_XBUTTON1), mouseFlags, false, data, SDL_BUTTON_X1, mouseID);
  241. WIN_CheckWParamMouseButton(timestamp, (wParam & MK_XBUTTON2), mouseFlags, false, data, SDL_BUTTON_X2, mouseID);
  242. data->mouse_button_flags = wParam;
  243. }
  244. }
  245. static void WIN_CheckAsyncMouseRelease(Uint64 timestamp, SDL_WindowData *data)
  246. {
  247. SDL_MouseID mouseID = SDL_GLOBAL_MOUSE_ID;
  248. Uint32 mouseFlags;
  249. SHORT keyState;
  250. bool swapButtons;
  251. /* mouse buttons may have changed state here, we need to resync them,
  252. but we will get a WM_MOUSEMOVE right away which will fix things up if in non raw mode also
  253. */
  254. mouseFlags = SDL_GetMouseState(NULL, NULL);
  255. swapButtons = GetSystemMetrics(SM_SWAPBUTTON) != 0;
  256. keyState = GetAsyncKeyState(VK_LBUTTON);
  257. if (!(keyState & 0x8000)) {
  258. WIN_CheckWParamMouseButton(timestamp, false, mouseFlags, swapButtons, data, SDL_BUTTON_LEFT, mouseID);
  259. }
  260. keyState = GetAsyncKeyState(VK_RBUTTON);
  261. if (!(keyState & 0x8000)) {
  262. WIN_CheckWParamMouseButton(timestamp, false, mouseFlags, swapButtons, data, SDL_BUTTON_RIGHT, mouseID);
  263. }
  264. keyState = GetAsyncKeyState(VK_MBUTTON);
  265. if (!(keyState & 0x8000)) {
  266. WIN_CheckWParamMouseButton(timestamp, false, mouseFlags, swapButtons, data, SDL_BUTTON_MIDDLE, mouseID);
  267. }
  268. keyState = GetAsyncKeyState(VK_XBUTTON1);
  269. if (!(keyState & 0x8000)) {
  270. WIN_CheckWParamMouseButton(timestamp, false, mouseFlags, swapButtons, data, SDL_BUTTON_X1, mouseID);
  271. }
  272. keyState = GetAsyncKeyState(VK_XBUTTON2);
  273. if (!(keyState & 0x8000)) {
  274. WIN_CheckWParamMouseButton(timestamp, false, mouseFlags, swapButtons, data, SDL_BUTTON_X2, mouseID);
  275. }
  276. data->mouse_button_flags = (WPARAM)-1;
  277. }
  278. static void WIN_UpdateFocus(SDL_Window *window, bool expect_focus, DWORD pos)
  279. {
  280. SDL_WindowData *data = window->internal;
  281. HWND hwnd = data->hwnd;
  282. bool had_focus = (SDL_GetKeyboardFocus() == window);
  283. bool has_focus = (GetForegroundWindow() == hwnd);
  284. if (had_focus == has_focus || has_focus != expect_focus) {
  285. return;
  286. }
  287. if (has_focus) {
  288. POINT cursorPos;
  289. if (WIN_ShouldIgnoreFocusClick(data) && !(window->flags & SDL_WINDOW_MOUSE_CAPTURE)) {
  290. bool swapButtons = GetSystemMetrics(SM_SWAPBUTTON) != 0;
  291. if (GetAsyncKeyState(VK_LBUTTON)) {
  292. data->focus_click_pending |= !swapButtons ? SDL_BUTTON_LMASK : SDL_BUTTON_RMASK;
  293. }
  294. if (GetAsyncKeyState(VK_RBUTTON)) {
  295. data->focus_click_pending |= !swapButtons ? SDL_BUTTON_RMASK : SDL_BUTTON_LMASK;
  296. }
  297. if (GetAsyncKeyState(VK_MBUTTON)) {
  298. data->focus_click_pending |= SDL_BUTTON_MMASK;
  299. }
  300. if (GetAsyncKeyState(VK_XBUTTON1)) {
  301. data->focus_click_pending |= SDL_BUTTON_X1MASK;
  302. }
  303. if (GetAsyncKeyState(VK_XBUTTON2)) {
  304. data->focus_click_pending |= SDL_BUTTON_X2MASK;
  305. }
  306. }
  307. SDL_SetKeyboardFocus(window->keyboard_focus ? window->keyboard_focus : window);
  308. // In relative mode we are guaranteed to have mouse focus if we have keyboard focus
  309. if (!SDL_GetMouse()->relative_mode) {
  310. cursorPos.x = (LONG)GET_X_LPARAM(pos);
  311. cursorPos.y = (LONG)GET_Y_LPARAM(pos);
  312. ScreenToClient(hwnd, &cursorPos);
  313. SDL_SendMouseMotion(WIN_GetEventTimestamp(), window, SDL_GLOBAL_MOUSE_ID, false, (float)cursorPos.x, (float)cursorPos.y);
  314. }
  315. WIN_CheckAsyncMouseRelease(WIN_GetEventTimestamp(), data);
  316. WIN_UpdateClipCursor(window);
  317. /*
  318. * FIXME: Update keyboard state
  319. */
  320. WIN_CheckClipboardUpdate(data->videodata);
  321. SDL_ToggleModState(SDL_KMOD_CAPS, (GetKeyState(VK_CAPITAL) & 0x0001) ? true : false);
  322. SDL_ToggleModState(SDL_KMOD_NUM, (GetKeyState(VK_NUMLOCK) & 0x0001) ? true : false);
  323. SDL_ToggleModState(SDL_KMOD_SCROLL, (GetKeyState(VK_SCROLL) & 0x0001) ? true : false);
  324. WIN_UpdateWindowICCProfile(data->window, true);
  325. } else {
  326. data->in_window_deactivation = true;
  327. SDL_SetKeyboardFocus(NULL);
  328. // In relative mode we are guaranteed to not have mouse focus if we don't have keyboard focus
  329. if (SDL_GetMouse()->relative_mode) {
  330. SDL_SetMouseFocus(NULL);
  331. }
  332. WIN_ResetDeadKeys();
  333. WIN_UnclipCursorForWindow(window);
  334. data->in_window_deactivation = false;
  335. }
  336. }
  337. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  338. static bool ShouldGenerateWindowCloseOnAltF4(void)
  339. {
  340. return SDL_GetHintBoolean(SDL_HINT_WINDOWS_CLOSE_ON_ALT_F4, true);
  341. }
  342. static bool ShouldClearWindowOnEraseBackground(SDL_WindowData *data)
  343. {
  344. switch (data->hint_erase_background_mode) {
  345. case SDL_ERASEBACKGROUNDMODE_NEVER:
  346. return false;
  347. case SDL_ERASEBACKGROUNDMODE_INITIAL:
  348. return !data->videodata->cleared;
  349. case SDL_ERASEBACKGROUNDMODE_ALWAYS:
  350. return true;
  351. default:
  352. // Unexpected value, fallback to default behaviour
  353. return !data->videodata->cleared;
  354. }
  355. }
  356. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  357. // We want to generate mouse events from mouse and pen, and touch events from touchscreens
  358. #define MI_WP_SIGNATURE 0xFF515700
  359. #define MI_WP_SIGNATURE_MASK 0xFFFFFF00
  360. #define IsTouchEvent(dw) ((dw)&MI_WP_SIGNATURE_MASK) == MI_WP_SIGNATURE
  361. typedef enum
  362. {
  363. SDL_MOUSE_EVENT_SOURCE_UNKNOWN,
  364. SDL_MOUSE_EVENT_SOURCE_MOUSE,
  365. SDL_MOUSE_EVENT_SOURCE_TOUCH,
  366. SDL_MOUSE_EVENT_SOURCE_PEN,
  367. } SDL_MOUSE_EVENT_SOURCE;
  368. static SDL_MOUSE_EVENT_SOURCE GetMouseMessageSource(ULONG extrainfo)
  369. {
  370. // Mouse data (ignoring synthetic mouse events generated for touchscreens)
  371. /* Versions below Vista will set the low 7 bits to the Mouse ID and don't use bit 7:
  372. Check bits 8-31 for the signature (which will indicate a Tablet PC Pen or Touch Device).
  373. Only check bit 7 when Vista and up(Cleared=Pen, Set=Touch(which we need to filter out)),
  374. when the signature is set. The Mouse ID will be zero for an actual mouse. */
  375. if (IsTouchEvent(extrainfo)) {
  376. if (extrainfo & 0x80) {
  377. return SDL_MOUSE_EVENT_SOURCE_TOUCH;
  378. } else {
  379. return SDL_MOUSE_EVENT_SOURCE_PEN;
  380. }
  381. }
  382. return SDL_MOUSE_EVENT_SOURCE_MOUSE;
  383. }
  384. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  385. static SDL_WindowData *WIN_GetWindowDataFromHWND(HWND hwnd)
  386. {
  387. SDL_VideoDevice *_this = SDL_GetVideoDevice();
  388. SDL_Window *window;
  389. if (_this) {
  390. for (window = _this->windows; window; window = window->next) {
  391. SDL_WindowData *data = window->internal;
  392. if (data && data->hwnd == hwnd) {
  393. return data;
  394. }
  395. }
  396. }
  397. return NULL;
  398. }
  399. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  400. LRESULT CALLBACK
  401. WIN_KeyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam)
  402. {
  403. KBDLLHOOKSTRUCT *hookData = (KBDLLHOOKSTRUCT *)lParam;
  404. SDL_VideoData *data = SDL_GetVideoDevice()->internal;
  405. SDL_Scancode scanCode;
  406. if (nCode < 0 || nCode != HC_ACTION) {
  407. return CallNextHookEx(NULL, nCode, wParam, lParam);
  408. }
  409. if (hookData->scanCode == 0x21d) {
  410. // Skip fake LCtrl when RAlt is pressed
  411. return 1;
  412. }
  413. switch (hookData->vkCode) {
  414. case VK_LWIN:
  415. scanCode = SDL_SCANCODE_LGUI;
  416. break;
  417. case VK_RWIN:
  418. scanCode = SDL_SCANCODE_RGUI;
  419. break;
  420. case VK_LMENU:
  421. scanCode = SDL_SCANCODE_LALT;
  422. break;
  423. case VK_RMENU:
  424. scanCode = SDL_SCANCODE_RALT;
  425. break;
  426. case VK_LCONTROL:
  427. scanCode = SDL_SCANCODE_LCTRL;
  428. break;
  429. case VK_RCONTROL:
  430. scanCode = SDL_SCANCODE_RCTRL;
  431. break;
  432. // These are required to intercept Alt+Tab and Alt+Esc on Windows 7
  433. case VK_TAB:
  434. scanCode = SDL_SCANCODE_TAB;
  435. break;
  436. case VK_ESCAPE:
  437. scanCode = SDL_SCANCODE_ESCAPE;
  438. break;
  439. default:
  440. return CallNextHookEx(NULL, nCode, wParam, lParam);
  441. }
  442. if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
  443. if (!data->raw_keyboard_enabled) {
  444. SDL_SendKeyboardKey(0, SDL_GLOBAL_KEYBOARD_ID, hookData->scanCode, scanCode, true);
  445. }
  446. } else {
  447. if (!data->raw_keyboard_enabled) {
  448. SDL_SendKeyboardKey(0, SDL_GLOBAL_KEYBOARD_ID, hookData->scanCode, scanCode, false);
  449. }
  450. /* If the key was down prior to our hook being installed, allow the
  451. key up message to pass normally the first time. This ensures other
  452. windows have a consistent view of the key state, and avoids keys
  453. being stuck down in those windows if they are down when the grab
  454. happens and raised while grabbed. */
  455. if (hookData->vkCode <= 0xFF && data->pre_hook_key_state[hookData->vkCode]) {
  456. data->pre_hook_key_state[hookData->vkCode] = 0;
  457. return CallNextHookEx(NULL, nCode, wParam, lParam);
  458. }
  459. }
  460. return 1;
  461. }
  462. static bool WIN_SwapButtons(HANDLE hDevice)
  463. {
  464. if (hDevice == NULL) {
  465. // Touchpad, already has buttons swapped
  466. return false;
  467. }
  468. return GetSystemMetrics(SM_SWAPBUTTON) != 0;
  469. }
  470. static void WIN_HandleRawMouseInput(Uint64 timestamp, SDL_VideoData *data, HANDLE hDevice, RAWMOUSE *rawmouse)
  471. {
  472. static struct {
  473. USHORT usButtonFlags;
  474. Uint8 button;
  475. bool down;
  476. } raw_buttons[] = {
  477. { RI_MOUSE_LEFT_BUTTON_DOWN, SDL_BUTTON_LEFT, true },
  478. { RI_MOUSE_LEFT_BUTTON_UP, SDL_BUTTON_LEFT, false },
  479. { RI_MOUSE_RIGHT_BUTTON_DOWN, SDL_BUTTON_RIGHT, true },
  480. { RI_MOUSE_RIGHT_BUTTON_UP, SDL_BUTTON_RIGHT, false },
  481. { RI_MOUSE_MIDDLE_BUTTON_DOWN, SDL_BUTTON_MIDDLE, true },
  482. { RI_MOUSE_MIDDLE_BUTTON_UP, SDL_BUTTON_MIDDLE, false },
  483. { RI_MOUSE_BUTTON_4_DOWN, SDL_BUTTON_X1, true },
  484. { RI_MOUSE_BUTTON_4_UP, SDL_BUTTON_X1, false },
  485. { RI_MOUSE_BUTTON_5_DOWN, SDL_BUTTON_X2, true },
  486. { RI_MOUSE_BUTTON_5_UP, SDL_BUTTON_X2, false }
  487. };
  488. int dx = (int)rawmouse->lLastX;
  489. int dy = (int)rawmouse->lLastY;
  490. bool haveMotion = (dx || dy);
  491. bool haveButton = (rawmouse->usButtonFlags != 0);
  492. bool isAbsolute = ((rawmouse->usFlags & MOUSE_MOVE_ABSOLUTE) != 0);
  493. SDL_MouseID mouseID = (SDL_MouseID)(uintptr_t)hDevice;
  494. // Check whether relative mode should also receive events from the rawinput stream
  495. if (!data->raw_mouse_enabled) {
  496. return;
  497. }
  498. // Relative mouse motion is delivered to the window with keyboard focus
  499. SDL_Window *window = SDL_GetKeyboardFocus();
  500. if (!window) {
  501. return;
  502. }
  503. if (GetMouseMessageSource(rawmouse->ulExtraInformation) != SDL_MOUSE_EVENT_SOURCE_MOUSE ||
  504. (SDL_TouchDevicesAvailable() && (rawmouse->ulExtraInformation & 0x80) == 0x80)) {
  505. return;
  506. }
  507. SDL_WindowData *windowdata = window->internal;
  508. if (haveMotion && !windowdata->in_modal_loop) {
  509. if (!isAbsolute) {
  510. SDL_SendMouseMotion(timestamp, window, mouseID, true, (float)dx, (float)dy);
  511. } else {
  512. /* This is absolute motion, either using a tablet or mouse over RDP
  513. Notes on how RDP appears to work, as of Windows 10 2004:
  514. - SetCursorPos() calls are cached, with multiple calls coalesced into a single call that's sent to the RDP client. If the last call to SetCursorPos() has the same value as the last one that was sent to the client, it appears to be ignored and not sent. This means that we need to jitter the SetCursorPos() position slightly in order for the recentering to work correctly.
  515. - User mouse motion is coalesced with SetCursorPos(), so the WM_INPUT positions we see will not necessarily match the position we requested with SetCursorPos().
  516. - SetCursorPos() outside of the bounds of the focus window appears not to do anything.
  517. - SetCursorPos() while the cursor is NULL doesn't do anything
  518. We handle this by creating a safe area within the application window, and when the mouse leaves that safe area, we warp back to the opposite side. Any single motion > 50% of the safe area is assumed to be a warp and ignored.
  519. */
  520. bool remote_desktop = (GetSystemMetrics(SM_REMOTESESSION) == TRUE);
  521. bool virtual_desktop = ((rawmouse->usFlags & MOUSE_VIRTUAL_DESKTOP) != 0);
  522. bool raw_coordinates = ((rawmouse->usFlags & 0x40) != 0);
  523. int w = GetSystemMetrics(virtual_desktop ? SM_CXVIRTUALSCREEN : SM_CXSCREEN);
  524. int h = GetSystemMetrics(virtual_desktop ? SM_CYVIRTUALSCREEN : SM_CYSCREEN);
  525. int x = raw_coordinates ? dx : (int)(((float)dx / 65535.0f) * w);
  526. int y = raw_coordinates ? dy : (int)(((float)dy / 65535.0f) * h);
  527. int relX, relY;
  528. /* Calculate relative motion */
  529. if (data->last_raw_mouse_position.x == 0 && data->last_raw_mouse_position.y == 0) {
  530. data->last_raw_mouse_position.x = x;
  531. data->last_raw_mouse_position.y = y;
  532. }
  533. relX = x - data->last_raw_mouse_position.x;
  534. relY = y - data->last_raw_mouse_position.y;
  535. if (remote_desktop) {
  536. if (!windowdata->in_title_click && !windowdata->focus_click_pending) {
  537. static int wobble;
  538. float floatX = (float)x / w;
  539. float floatY = (float)y / h;
  540. /* See if the mouse is at the edge of the screen, or in the RDP title bar area */
  541. if (floatX <= 0.01f || floatX >= 0.99f || floatY <= 0.01f || floatY >= 0.99f || y < 32) {
  542. /* Wobble the cursor position so it's not ignored if the last warp didn't have any effect */
  543. RECT rect = windowdata->cursor_clipped_rect;
  544. int warpX = rect.left + ((rect.right - rect.left) / 2) + wobble;
  545. int warpY = rect.top + ((rect.bottom - rect.top) / 2);
  546. WIN_SetCursorPos(warpX, warpY);
  547. ++wobble;
  548. if (wobble > 1) {
  549. wobble = -1;
  550. }
  551. } else {
  552. /* Send relative motion if we didn't warp last frame (had good position data)
  553. We also sometimes get large deltas due to coalesced mouse motion and warping,
  554. so ignore those.
  555. */
  556. const int MAX_RELATIVE_MOTION = (h / 6);
  557. if (SDL_abs(relX) < MAX_RELATIVE_MOTION &&
  558. SDL_abs(relY) < MAX_RELATIVE_MOTION) {
  559. SDL_SendMouseMotion(timestamp, window, mouseID, true, (float)relX, (float)relY);
  560. }
  561. }
  562. }
  563. } else {
  564. const int MAXIMUM_TABLET_RELATIVE_MOTION = 32;
  565. if (SDL_abs(relX) > MAXIMUM_TABLET_RELATIVE_MOTION ||
  566. SDL_abs(relY) > MAXIMUM_TABLET_RELATIVE_MOTION) {
  567. /* Ignore this motion, probably a pen lift and drop */
  568. } else {
  569. SDL_SendMouseMotion(timestamp, window, mouseID, true, (float)relX, (float)relY);
  570. }
  571. }
  572. data->last_raw_mouse_position.x = x;
  573. data->last_raw_mouse_position.y = y;
  574. }
  575. }
  576. if (haveButton) {
  577. for (int i = 0; i < SDL_arraysize(raw_buttons); ++i) {
  578. if (rawmouse->usButtonFlags & raw_buttons[i].usButtonFlags) {
  579. Uint8 button = raw_buttons[i].button;
  580. bool down = raw_buttons[i].down;
  581. if (button == SDL_BUTTON_LEFT) {
  582. if (WIN_SwapButtons(hDevice)) {
  583. button = SDL_BUTTON_RIGHT;
  584. }
  585. } else if (button == SDL_BUTTON_RIGHT) {
  586. if (WIN_SwapButtons(hDevice)) {
  587. button = SDL_BUTTON_LEFT;
  588. }
  589. }
  590. if (windowdata->focus_click_pending & SDL_BUTTON_MASK(button)) {
  591. // Ignore the button click for activation
  592. if (!down) {
  593. windowdata->focus_click_pending &= ~SDL_BUTTON_MASK(button);
  594. WIN_UpdateClipCursor(window);
  595. }
  596. continue;
  597. }
  598. SDL_SendMouseButton(timestamp, window, mouseID, button, down);
  599. }
  600. }
  601. if (rawmouse->usButtonFlags & RI_MOUSE_WHEEL) {
  602. SHORT amount = (SHORT)rawmouse->usButtonData;
  603. float fAmount = (float)amount / WHEEL_DELTA;
  604. SDL_SendMouseWheel(WIN_GetEventTimestamp(), window, mouseID, 0.0f, fAmount, SDL_MOUSEWHEEL_NORMAL);
  605. } else if (rawmouse->usButtonFlags & RI_MOUSE_HWHEEL) {
  606. SHORT amount = (SHORT)rawmouse->usButtonData;
  607. float fAmount = (float)amount / WHEEL_DELTA;
  608. SDL_SendMouseWheel(WIN_GetEventTimestamp(), window, mouseID, fAmount, 0.0f, SDL_MOUSEWHEEL_NORMAL);
  609. }
  610. /* Invalidate the mouse button flags. If we don't do this then disabling raw input
  611. will cause held down mouse buttons to persist when released. */
  612. windowdata->mouse_button_flags = (WPARAM)-1;
  613. }
  614. }
  615. static void WIN_HandleRawKeyboardInput(Uint64 timestamp, SDL_VideoData *data, HANDLE hDevice, RAWKEYBOARD *rawkeyboard)
  616. {
  617. SDL_KeyboardID keyboardID = (SDL_KeyboardID)(uintptr_t)hDevice;
  618. if (!data->raw_keyboard_enabled) {
  619. return;
  620. }
  621. if (rawkeyboard->Flags & RI_KEY_E1) {
  622. // First key in a Ctrl+{key} sequence
  623. data->pending_E1_key_sequence = true;
  624. return;
  625. }
  626. if ((rawkeyboard->Flags & RI_KEY_E0) && rawkeyboard->MakeCode == 0x2A) {
  627. // 0xE02A make code prefix, ignored
  628. return;
  629. }
  630. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  631. if (!rawkeyboard->MakeCode) {
  632. rawkeyboard->MakeCode = LOWORD(MapVirtualKey(rawkeyboard->VKey, WIN_IsWindowsXP() ? MAPVK_VK_TO_VSC : MAPVK_VK_TO_VSC_EX));
  633. }
  634. #endif
  635. if (!rawkeyboard->MakeCode) {
  636. return;
  637. }
  638. bool down = !(rawkeyboard->Flags & RI_KEY_BREAK);
  639. SDL_Scancode code;
  640. USHORT rawcode = rawkeyboard->MakeCode;
  641. if (data->pending_E1_key_sequence) {
  642. rawcode |= 0xE100;
  643. if (rawkeyboard->MakeCode == 0x45) {
  644. // Ctrl+NumLock == Pause
  645. code = SDL_SCANCODE_PAUSE;
  646. } else {
  647. // Ctrl+ScrollLock == Break (no SDL scancode?)
  648. code = SDL_SCANCODE_UNKNOWN;
  649. }
  650. data->pending_E1_key_sequence = false;
  651. } else {
  652. // The code is in the lower 7 bits, the high bit is set for the E0 prefix
  653. Uint8 index = (Uint8)rawkeyboard->MakeCode;
  654. if (rawkeyboard->Flags & RI_KEY_E0) {
  655. rawcode |= 0xE000;
  656. index |= 0x80;
  657. }
  658. code = windows_scancode_table[index];
  659. }
  660. if (down) {
  661. SDL_Window *focus = SDL_GetKeyboardFocus();
  662. if (!focus || focus->text_input_active) {
  663. return;
  664. }
  665. }
  666. SDL_SendKeyboardKey(timestamp, keyboardID, rawcode, code, down);
  667. }
  668. void WIN_PollRawInput(SDL_VideoDevice *_this, Uint64 poll_start)
  669. {
  670. SDL_VideoData *data = _this->internal;
  671. UINT size, i, count, total = 0;
  672. RAWINPUT *input;
  673. Uint64 poll_finish;
  674. if (data->rawinput_offset == 0) {
  675. BOOL isWow64;
  676. data->rawinput_offset = sizeof(RAWINPUTHEADER);
  677. if (IsWow64Process(GetCurrentProcess(), &isWow64) && isWow64) {
  678. // We're going to get 64-bit data, so use the 64-bit RAWINPUTHEADER size
  679. data->rawinput_offset += 8;
  680. }
  681. }
  682. // Get all available events
  683. input = (RAWINPUT *)data->rawinput;
  684. for (;;) {
  685. size = data->rawinput_size - (UINT)((BYTE *)input - data->rawinput);
  686. count = GetRawInputBuffer(input, &size, sizeof(RAWINPUTHEADER));
  687. poll_finish = SDL_GetTicksNS();
  688. if (count == 0 || count == (UINT)-1) {
  689. if (!data->rawinput || (count == (UINT)-1 && GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
  690. const UINT RAWINPUT_BUFFER_SIZE_INCREMENT = 96; // 2 64-bit raw mouse packets
  691. BYTE *rawinput = (BYTE *)SDL_realloc(data->rawinput, data->rawinput_size + RAWINPUT_BUFFER_SIZE_INCREMENT);
  692. if (!rawinput) {
  693. break;
  694. }
  695. input = (RAWINPUT *)(rawinput + ((BYTE *)input - data->rawinput));
  696. data->rawinput = rawinput;
  697. data->rawinput_size += RAWINPUT_BUFFER_SIZE_INCREMENT;
  698. } else {
  699. break;
  700. }
  701. } else {
  702. total += count;
  703. // Advance input to the end of the buffer
  704. while (count--) {
  705. input = NEXTRAWINPUTBLOCK(input);
  706. }
  707. }
  708. }
  709. if (total > 0) {
  710. Uint64 delta = poll_finish - poll_start;
  711. UINT mouse_total = 0;
  712. for (i = 0, input = (RAWINPUT *)data->rawinput; i < total; ++i, input = NEXTRAWINPUTBLOCK(input)) {
  713. if (input->header.dwType == RIM_TYPEMOUSE) {
  714. mouse_total += 1;
  715. }
  716. }
  717. int mouse_index = 0;
  718. for (i = 0, input = (RAWINPUT *)data->rawinput; i < total; ++i, input = NEXTRAWINPUTBLOCK(input)) {
  719. if (input->header.dwType == RIM_TYPEMOUSE) {
  720. mouse_index += 1; // increment first so that it starts at one
  721. RAWMOUSE *rawmouse = (RAWMOUSE *)((BYTE *)input + data->rawinput_offset);
  722. Uint64 time = poll_finish - (delta * (mouse_total - mouse_index)) / mouse_total;
  723. WIN_HandleRawMouseInput(time, data, input->header.hDevice, rawmouse);
  724. } else if (input->header.dwType == RIM_TYPEKEYBOARD) {
  725. RAWKEYBOARD *rawkeyboard = (RAWKEYBOARD *)((BYTE *)input + data->rawinput_offset);
  726. WIN_HandleRawKeyboardInput(poll_finish, data, input->header.hDevice, rawkeyboard);
  727. }
  728. }
  729. }
  730. data->last_rawinput_poll = poll_finish;
  731. }
  732. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  733. static void AddDeviceID(Uint32 deviceID, Uint32 **list, int *count)
  734. {
  735. int new_count = (*count + 1);
  736. Uint32 *new_list = (Uint32 *)SDL_realloc(*list, new_count * sizeof(*new_list));
  737. if (!new_list) {
  738. // Oh well, we'll drop this one
  739. return;
  740. }
  741. new_list[new_count - 1] = deviceID;
  742. *count = new_count;
  743. *list = new_list;
  744. }
  745. static bool HasDeviceID(Uint32 deviceID, const Uint32 *list, int count)
  746. {
  747. for (int i = 0; i < count; ++i) {
  748. if (deviceID == list[i]) {
  749. return true;
  750. }
  751. }
  752. return false;
  753. }
  754. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  755. static char *GetDeviceName(HANDLE hDevice, HDEVINFO devinfo, const char *instance, const char *default_name, bool hid_loaded)
  756. {
  757. char *vendor_name = NULL;
  758. char *product_name = NULL;
  759. char *name = NULL;
  760. // These are 126 for USB, but can be longer for Bluetooth devices
  761. WCHAR vend[256], prod[256];
  762. vend[0] = 0;
  763. prod[0] = 0;
  764. HIDD_ATTRIBUTES attr;
  765. attr.VendorID = 0;
  766. attr.ProductID = 0;
  767. attr.Size = sizeof(attr);
  768. if (hid_loaded) {
  769. char devName[MAX_PATH + 1];
  770. UINT cap = sizeof(devName) - 1;
  771. UINT len = GetRawInputDeviceInfoA(hDevice, RIDI_DEVICENAME, devName, &cap);
  772. if (len != (UINT)-1) {
  773. devName[len] = '\0';
  774. // important: for devices with exclusive access mode as per
  775. // https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/top-level-collections-opened-by-windows-for-system-use
  776. // they can only be opened with a desired access of none instead of generic read.
  777. HANDLE hFile = CreateFileA(devName, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  778. if (hFile != INVALID_HANDLE_VALUE) {
  779. SDL_HidD_GetAttributes(hFile, &attr);
  780. SDL_HidD_GetManufacturerString(hFile, vend, sizeof(vend));
  781. SDL_HidD_GetProductString(hFile, prod, sizeof(prod));
  782. CloseHandle(hFile);
  783. }
  784. }
  785. }
  786. if (vend[0]) {
  787. vendor_name = WIN_StringToUTF8W(vend);
  788. }
  789. if (prod[0]) {
  790. product_name = WIN_StringToUTF8W(prod);
  791. } else {
  792. SP_DEVINFO_DATA data;
  793. SDL_zero(data);
  794. data.cbSize = sizeof(data);
  795. for (DWORD i = 0;; ++i) {
  796. if (!SetupDiEnumDeviceInfo(devinfo, i, &data)) {
  797. if (GetLastError() == ERROR_NO_MORE_ITEMS) {
  798. break;
  799. } else {
  800. continue;
  801. }
  802. }
  803. char DeviceInstanceId[64];
  804. if (!SetupDiGetDeviceInstanceIdA(devinfo, &data, DeviceInstanceId, sizeof(DeviceInstanceId), NULL))
  805. continue;
  806. if (SDL_strcasecmp(instance, DeviceInstanceId) == 0) {
  807. DWORD size = 0;
  808. if (SetupDiGetDeviceRegistryPropertyW(devinfo, &data, SPDRP_DEVICEDESC, NULL, (PBYTE)prod, sizeof(prod), &size)) {
  809. // Make sure the device description is null terminated
  810. size /= sizeof(*prod);
  811. if (size >= SDL_arraysize(prod)) {
  812. // Truncated description...
  813. size = (SDL_arraysize(prod) - 1);
  814. }
  815. prod[size] = 0;
  816. if (attr.VendorID || attr.ProductID) {
  817. SDL_asprintf(&product_name, "%S (0x%.4x/0x%.4x)", prod, attr.VendorID, attr.ProductID);
  818. } else {
  819. product_name = WIN_StringToUTF8W(prod);
  820. }
  821. }
  822. break;
  823. }
  824. }
  825. }
  826. if (!product_name && (attr.VendorID || attr.ProductID)) {
  827. SDL_asprintf(&product_name, "%s (0x%.4x/0x%.4x)", default_name, attr.VendorID, attr.ProductID);
  828. }
  829. name = SDL_CreateDeviceName(attr.VendorID, attr.ProductID, vendor_name, product_name, default_name);
  830. SDL_free(vendor_name);
  831. SDL_free(product_name);
  832. return name;
  833. }
  834. void WIN_CheckKeyboardAndMouseHotplug(SDL_VideoDevice *_this, bool initial_check)
  835. {
  836. PRAWINPUTDEVICELIST raw_devices = NULL;
  837. UINT raw_device_count = 0;
  838. int old_keyboard_count = 0;
  839. SDL_KeyboardID *old_keyboards = NULL;
  840. int new_keyboard_count = 0;
  841. SDL_KeyboardID *new_keyboards = NULL;
  842. int old_mouse_count = 0;
  843. SDL_MouseID *old_mice = NULL;
  844. int new_mouse_count = 0;
  845. SDL_MouseID *new_mice = NULL;
  846. bool send_event = !initial_check;
  847. // Check to see if anything has changed
  848. static Uint64 s_last_device_change;
  849. Uint64 last_device_change = WIN_GetLastDeviceNotification();
  850. if (!initial_check && last_device_change == s_last_device_change) {
  851. return;
  852. }
  853. s_last_device_change = last_device_change;
  854. if ((GetRawInputDeviceList(NULL, &raw_device_count, sizeof(RAWINPUTDEVICELIST)) == -1) || (!raw_device_count)) {
  855. return; // oh well.
  856. }
  857. raw_devices = (PRAWINPUTDEVICELIST)SDL_malloc(sizeof(RAWINPUTDEVICELIST) * raw_device_count);
  858. if (!raw_devices) {
  859. return; // oh well.
  860. }
  861. raw_device_count = GetRawInputDeviceList(raw_devices, &raw_device_count, sizeof(RAWINPUTDEVICELIST));
  862. if (raw_device_count == (UINT)-1) {
  863. SDL_free(raw_devices);
  864. raw_devices = NULL;
  865. return; // oh well.
  866. }
  867. HDEVINFO devinfo = SetupDiGetClassDevsA(NULL, NULL, NULL, (DIGCF_ALLCLASSES | DIGCF_PRESENT));
  868. old_keyboards = SDL_GetKeyboards(&old_keyboard_count);
  869. old_mice = SDL_GetMice(&old_mouse_count);
  870. bool hid_loaded = WIN_LoadHIDDLL();
  871. for (UINT i = 0; i < raw_device_count; i++) {
  872. RID_DEVICE_INFO rdi;
  873. char devName[MAX_PATH] = { 0 };
  874. UINT rdiSize = sizeof(rdi);
  875. UINT nameSize = SDL_arraysize(devName);
  876. int vendor = 0, product = 0;
  877. DWORD dwType = raw_devices[i].dwType;
  878. char *instance, *ptr, *name;
  879. if (dwType != RIM_TYPEKEYBOARD && dwType != RIM_TYPEMOUSE) {
  880. continue;
  881. }
  882. rdi.cbSize = sizeof(rdi);
  883. if (GetRawInputDeviceInfoA(raw_devices[i].hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) == ((UINT)-1) ||
  884. GetRawInputDeviceInfoA(raw_devices[i].hDevice, RIDI_DEVICENAME, devName, &nameSize) == ((UINT)-1)) {
  885. continue;
  886. }
  887. // Extract the device instance
  888. instance = devName;
  889. while (*instance == '\\' || *instance == '?') {
  890. ++instance;
  891. }
  892. for (ptr = instance; *ptr; ++ptr) {
  893. if (*ptr == '#') {
  894. *ptr = '\\';
  895. }
  896. if (*ptr == '{') {
  897. if (ptr > instance && ptr[-1] == '\\') {
  898. --ptr;
  899. }
  900. break;
  901. }
  902. }
  903. *ptr = '\0';
  904. SDL_sscanf(instance, "HID\\VID_%X&PID_%X&", &vendor, &product);
  905. switch (dwType) {
  906. case RIM_TYPEKEYBOARD:
  907. if (SDL_IsKeyboard((Uint16)vendor, (Uint16)product, rdi.keyboard.dwNumberOfKeysTotal)) {
  908. SDL_KeyboardID keyboardID = (Uint32)(uintptr_t)raw_devices[i].hDevice;
  909. AddDeviceID(keyboardID, &new_keyboards, &new_keyboard_count);
  910. if (!HasDeviceID(keyboardID, old_keyboards, old_keyboard_count)) {
  911. name = GetDeviceName(raw_devices[i].hDevice, devinfo, instance, "Keyboard", hid_loaded);
  912. SDL_AddKeyboard(keyboardID, name, send_event);
  913. SDL_free(name);
  914. }
  915. }
  916. break;
  917. case RIM_TYPEMOUSE:
  918. if (SDL_IsMouse((Uint16)vendor, (Uint16)product)) {
  919. SDL_MouseID mouseID = (Uint32)(uintptr_t)raw_devices[i].hDevice;
  920. AddDeviceID(mouseID, &new_mice, &new_mouse_count);
  921. if (!HasDeviceID(mouseID, old_mice, old_mouse_count)) {
  922. name = GetDeviceName(raw_devices[i].hDevice, devinfo, instance, "Mouse", hid_loaded);
  923. SDL_AddMouse(mouseID, name, send_event);
  924. SDL_free(name);
  925. }
  926. }
  927. break;
  928. default:
  929. break;
  930. }
  931. }
  932. if (hid_loaded) {
  933. WIN_UnloadHIDDLL();
  934. }
  935. for (int i = old_keyboard_count; i--;) {
  936. if (!HasDeviceID(old_keyboards[i], new_keyboards, new_keyboard_count)) {
  937. SDL_RemoveKeyboard(old_keyboards[i], send_event);
  938. }
  939. }
  940. for (int i = old_mouse_count; i--;) {
  941. if (!HasDeviceID(old_mice[i], new_mice, new_mouse_count)) {
  942. SDL_RemoveMouse(old_mice[i], send_event);
  943. }
  944. }
  945. SDL_free(old_keyboards);
  946. SDL_free(new_keyboards);
  947. SDL_free(old_mice);
  948. SDL_free(new_mice);
  949. SetupDiDestroyDeviceInfoList(devinfo);
  950. SDL_free(raw_devices);
  951. }
  952. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  953. // Return true if spurious LCtrl is pressed
  954. // LCtrl is sent when RAltGR is pressed
  955. static bool SkipAltGrLeftControl(WPARAM wParam, LPARAM lParam)
  956. {
  957. if (wParam != VK_CONTROL) {
  958. return false;
  959. }
  960. // Is this an extended key (i.e. right key)?
  961. if (lParam & 0x01000000) {
  962. return false;
  963. }
  964. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  965. // Here is a trick: "Alt Gr" sends LCTRL, then RALT. We only
  966. // want the RALT message, so we try to see if the next message
  967. // is a RALT message. In that case, this is a false LCTRL!
  968. MSG next_msg;
  969. DWORD msg_time = GetMessageTime();
  970. if (PeekMessage(&next_msg, NULL, 0, 0, PM_NOREMOVE)) {
  971. if (next_msg.message == WM_KEYDOWN ||
  972. next_msg.message == WM_SYSKEYDOWN) {
  973. if (next_msg.wParam == VK_MENU && (next_msg.lParam & 0x01000000) && next_msg.time == msg_time) {
  974. // Next message is a RALT down message, which means that this is NOT a proper LCTRL message!
  975. return true;
  976. }
  977. }
  978. }
  979. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  980. return false;
  981. }
  982. static bool DispatchModalLoopMessageHook(HWND *hwnd, UINT *msg, WPARAM *wParam, LPARAM *lParam)
  983. {
  984. MSG dummy;
  985. SDL_zero(dummy);
  986. dummy.hwnd = *hwnd;
  987. dummy.message = *msg;
  988. dummy.wParam = *wParam;
  989. dummy.lParam = *lParam;
  990. if (g_WindowsMessageHook(g_WindowsMessageHookData, &dummy)) {
  991. // Can't modify the hwnd, but everything else is fair game
  992. *msg = dummy.message;
  993. *wParam = dummy.wParam;
  994. *lParam = dummy.lParam;
  995. return true;
  996. }
  997. return false;
  998. }
  999. LRESULT CALLBACK WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  1000. {
  1001. SDL_WindowData *data;
  1002. LRESULT returnCode = -1;
  1003. // Get the window data for the window
  1004. data = WIN_GetWindowDataFromHWND(hwnd);
  1005. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  1006. if (!data) {
  1007. // Fallback
  1008. data = (SDL_WindowData *)GetProp(hwnd, TEXT("SDL_WindowData"));
  1009. }
  1010. #endif
  1011. if (!data) {
  1012. return CallWindowProc(DefWindowProc, hwnd, msg, wParam, lParam);
  1013. }
  1014. #ifdef WMMSG_DEBUG
  1015. {
  1016. char message[1024];
  1017. if (msg > MAX_WMMSG) {
  1018. SDL_snprintf(message, sizeof(message), "Received windows message: %p UNKNOWN (%d) -- 0x%x, 0x%x\r\n", hwnd, msg, wParam, lParam);
  1019. } else {
  1020. SDL_snprintf(message, sizeof(message), "Received windows message: %p %s -- 0x%x, 0x%x\r\n", hwnd, wmtab[msg], wParam, lParam);
  1021. }
  1022. OutputDebugStringA(message);
  1023. }
  1024. #endif // WMMSG_DEBUG
  1025. if (g_WindowsMessageHook && data->in_modal_loop) {
  1026. // Synthesize a message for window hooks so they can modify the message if desired
  1027. if (!DispatchModalLoopMessageHook(&hwnd, &msg, &wParam, &lParam)) {
  1028. return 0;
  1029. }
  1030. }
  1031. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  1032. if (WIN_HandleIMEMessage(hwnd, msg, wParam, &lParam, data->videodata)) {
  1033. return 0;
  1034. }
  1035. #endif
  1036. switch (msg) {
  1037. case WM_SHOWWINDOW:
  1038. {
  1039. if (wParam) {
  1040. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_SHOWN, 0, 0);
  1041. } else {
  1042. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_HIDDEN, 0, 0);
  1043. }
  1044. } break;
  1045. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  1046. case WM_NCACTIVATE:
  1047. {
  1048. // Don't immediately clip the cursor in case we're clicking minimize/maximize buttons
  1049. data->postpone_clipcursor = true;
  1050. data->clipcursor_queued = true;
  1051. /* Update the focus here, since it's possible to get WM_ACTIVATE and WM_SETFOCUS without
  1052. actually being the foreground window, but this appears to get called in all cases where
  1053. the global foreground window changes to and from this window. */
  1054. WIN_UpdateFocus(data->window, !!wParam, GetMessagePos());
  1055. } break;
  1056. case WM_ACTIVATE:
  1057. {
  1058. // Update the focus in case we changed focus to a child window and then away from the application
  1059. WIN_UpdateFocus(data->window, !!LOWORD(wParam), GetMessagePos());
  1060. } break;
  1061. case WM_MOUSEACTIVATE:
  1062. {
  1063. if (SDL_WINDOW_IS_POPUP(data->window)) {
  1064. return MA_NOACTIVATE;
  1065. }
  1066. // Check parents to see if they are in relative mouse mode and focused
  1067. SDL_Window *parent = data->window->parent;
  1068. while (parent) {
  1069. if ((parent->flags & SDL_WINDOW_INPUT_FOCUS) &&
  1070. (parent->flags & SDL_WINDOW_MOUSE_RELATIVE_MODE)) {
  1071. return MA_NOACTIVATE;
  1072. }
  1073. parent = parent->parent;
  1074. }
  1075. } break;
  1076. case WM_SETFOCUS:
  1077. {
  1078. // Update the focus in case it's changing between top-level windows in the same application
  1079. WIN_UpdateFocus(data->window, true, GetMessagePos());
  1080. } break;
  1081. case WM_KILLFOCUS:
  1082. case WM_ENTERIDLE:
  1083. {
  1084. // Update the focus in case it's changing between top-level windows in the same application
  1085. WIN_UpdateFocus(data->window, false, GetMessagePos());
  1086. } break;
  1087. case WM_POINTERENTER:
  1088. {
  1089. if (!data->videodata->GetPointerType) {
  1090. break; // Not on Windows8 or later? We shouldn't get this event, but just in case...
  1091. }
  1092. const UINT32 pointerid = GET_POINTERID_WPARAM(wParam);
  1093. void *hpointer = (void *) (size_t) pointerid;
  1094. POINTER_INPUT_TYPE pointer_type = PT_POINTER;
  1095. if (!data->videodata->GetPointerType(pointerid, &pointer_type)) {
  1096. break; // oh well.
  1097. } else if (pointer_type != PT_PEN) {
  1098. break; // we only care about pens here.
  1099. } else if (SDL_FindPenByHandle(hpointer)) {
  1100. break; // we already have this one, don't readd it.
  1101. }
  1102. // one can use GetPointerPenInfo() to get the current state of the pen, and check POINTER_PEN_INFO::penMask,
  1103. // but the docs aren't clear if these masks are _always_ set for pens with specific features, or if they
  1104. // could be unset at this moment because Windows is still deciding what capabilities the pen has, and/or
  1105. // doesn't yet have valid data for them. As such, just say everything that the interface supports is
  1106. // available...we don't expose this information through the public API at the moment anyhow.
  1107. SDL_PenInfo info;
  1108. SDL_zero(info);
  1109. info.capabilities = SDL_PEN_CAPABILITY_PRESSURE | SDL_PEN_CAPABILITY_XTILT | SDL_PEN_CAPABILITY_YTILT | SDL_PEN_CAPABILITY_DISTANCE | SDL_PEN_CAPABILITY_ROTATION | SDL_PEN_CAPABILITY_ERASER;
  1110. info.max_tilt = 90.0f;
  1111. info.num_buttons = 1;
  1112. info.subtype = SDL_PEN_TYPE_PENCIL;
  1113. SDL_AddPenDevice(0, NULL, &info, hpointer);
  1114. returnCode = 0;
  1115. } break;
  1116. case WM_POINTERCAPTURECHANGED:
  1117. case WM_POINTERLEAVE:
  1118. {
  1119. const UINT32 pointerid = GET_POINTERID_WPARAM(wParam);
  1120. void *hpointer = (void *) (size_t) pointerid;
  1121. const SDL_PenID pen = SDL_FindPenByHandle(hpointer);
  1122. if (pen == 0) {
  1123. break; // not a pen, or not a pen we already knew about.
  1124. }
  1125. // if this just left the _window_, we don't care. If this is no longer visible to the tablet, time to remove it!
  1126. if ((msg == WM_POINTERCAPTURECHANGED) || !IS_POINTER_INCONTACT_WPARAM(wParam)) {
  1127. SDL_RemovePenDevice(WIN_GetEventTimestamp(), pen);
  1128. }
  1129. returnCode = 0;
  1130. } break;
  1131. case WM_POINTERUPDATE: {
  1132. POINTER_INPUT_TYPE pointer_type = PT_POINTER;
  1133. if (!data->videodata->GetPointerType || !data->videodata->GetPointerType(GET_POINTERID_WPARAM(wParam), &pointer_type)) {
  1134. break; // oh well.
  1135. }
  1136. if (pointer_type == PT_MOUSE) {
  1137. data->last_pointer_update = lParam;
  1138. returnCode = 0;
  1139. break;
  1140. }
  1141. }
  1142. SDL_FALLTHROUGH;
  1143. case WM_POINTERDOWN:
  1144. case WM_POINTERUP: {
  1145. POINTER_PEN_INFO pen_info;
  1146. const UINT32 pointerid = GET_POINTERID_WPARAM(wParam);
  1147. void *hpointer = (void *) (size_t) pointerid;
  1148. const SDL_PenID pen = SDL_FindPenByHandle(hpointer);
  1149. if (pen == 0) {
  1150. break; // not a pen, or not a pen we already knew about.
  1151. } else if (!data->videodata->GetPointerPenInfo || !data->videodata->GetPointerPenInfo(pointerid, &pen_info)) {
  1152. break; // oh well.
  1153. }
  1154. const Uint64 timestamp = WIN_GetEventTimestamp();
  1155. SDL_Window *window = data->window;
  1156. const bool istouching = IS_POINTER_INCONTACT_WPARAM(wParam) && IS_POINTER_FIRSTBUTTON_WPARAM(wParam);
  1157. // if lifting off, do it first, so any motion changes don't cause app issues.
  1158. if (!istouching) {
  1159. SDL_SendPenTouch(timestamp, pen, window, (pen_info.penFlags & PEN_FLAG_INVERTED) != 0, false);
  1160. }
  1161. POINT position;
  1162. position.x = (LONG) GET_X_LPARAM(lParam);
  1163. position.y = (LONG) GET_Y_LPARAM(lParam);
  1164. ScreenToClient(data->hwnd, &position);
  1165. SDL_SendPenMotion(timestamp, pen, window, (float) position.x, (float) position.y);
  1166. SDL_SendPenButton(timestamp, pen, window, 1, (pen_info.penFlags & PEN_FLAG_BARREL) != 0);
  1167. SDL_SendPenButton(timestamp, pen, window, 2, (pen_info.penFlags & PEN_FLAG_ERASER) != 0);
  1168. if (pen_info.penMask & PEN_MASK_PRESSURE) {
  1169. SDL_SendPenAxis(timestamp, pen, window, SDL_PEN_AXIS_PRESSURE, ((float) pen_info.pressure) / 1024.0f); // pen_info.pressure is in the range 0..1024.
  1170. }
  1171. if (pen_info.penMask & PEN_MASK_ROTATION) {
  1172. SDL_SendPenAxis(timestamp, pen, window, SDL_PEN_AXIS_ROTATION, ((float) pen_info.rotation)); // it's already in the range of 0 to 359.
  1173. }
  1174. if (pen_info.penMask & PEN_MASK_TILT_X) {
  1175. SDL_SendPenAxis(timestamp, pen, window, SDL_PEN_AXIS_XTILT, ((float) pen_info.tiltX)); // it's already in the range of -90 to 90..
  1176. }
  1177. if (pen_info.penMask & PEN_MASK_TILT_Y) {
  1178. SDL_SendPenAxis(timestamp, pen, window, SDL_PEN_AXIS_YTILT, ((float) pen_info.tiltY)); // it's already in the range of -90 to 90..
  1179. }
  1180. // if setting down, do it last, so the pen is positioned correctly from the first contact.
  1181. if (istouching) {
  1182. SDL_SendPenTouch(timestamp, pen, window, (pen_info.penFlags & PEN_FLAG_INVERTED) != 0, true);
  1183. }
  1184. returnCode = 0;
  1185. } break;
  1186. case WM_MOUSEMOVE:
  1187. {
  1188. SDL_Window *window = data->window;
  1189. if (window->flags & SDL_WINDOW_INPUT_FOCUS) {
  1190. bool wish_clip_cursor = (
  1191. window->flags & (SDL_WINDOW_MOUSE_RELATIVE_MODE | SDL_WINDOW_MOUSE_GRABBED) ||
  1192. (window->mouse_rect.w > 0 && window->mouse_rect.h > 0)
  1193. );
  1194. if (wish_clip_cursor) { // queue clipcursor refresh on pump finish
  1195. data->clipcursor_queued = true;
  1196. }
  1197. }
  1198. if (!data->mouse_tracked) {
  1199. TRACKMOUSEEVENT trackMouseEvent;
  1200. trackMouseEvent.cbSize = sizeof(TRACKMOUSEEVENT);
  1201. trackMouseEvent.dwFlags = TME_LEAVE;
  1202. trackMouseEvent.hwndTrack = data->hwnd;
  1203. if (TrackMouseEvent(&trackMouseEvent)) {
  1204. data->mouse_tracked = true;
  1205. }
  1206. WIN_CheckAsyncMouseRelease(WIN_GetEventTimestamp(), data);
  1207. }
  1208. if (!data->videodata->raw_mouse_enabled) {
  1209. // Only generate mouse events for real mouse
  1210. if (GetMouseMessageSource((ULONG)GetMessageExtraInfo()) == SDL_MOUSE_EVENT_SOURCE_MOUSE &&
  1211. lParam != data->last_pointer_update) {
  1212. SDL_SendMouseMotion(WIN_GetEventTimestamp(), window, SDL_GLOBAL_MOUSE_ID, false, (float)GET_X_LPARAM(lParam), (float)GET_Y_LPARAM(lParam));
  1213. }
  1214. }
  1215. } break;
  1216. case WM_LBUTTONUP:
  1217. case WM_RBUTTONUP:
  1218. case WM_MBUTTONUP:
  1219. case WM_XBUTTONUP:
  1220. case WM_LBUTTONDOWN:
  1221. case WM_LBUTTONDBLCLK:
  1222. case WM_RBUTTONDOWN:
  1223. case WM_RBUTTONDBLCLK:
  1224. case WM_MBUTTONDOWN:
  1225. case WM_MBUTTONDBLCLK:
  1226. case WM_XBUTTONDOWN:
  1227. case WM_XBUTTONDBLCLK:
  1228. {
  1229. /* SDL_Mouse *mouse = SDL_GetMouse(); */
  1230. if (!data->videodata->raw_mouse_enabled) {
  1231. if (GetMouseMessageSource((ULONG)GetMessageExtraInfo()) == SDL_MOUSE_EVENT_SOURCE_MOUSE &&
  1232. lParam != data->last_pointer_update) {
  1233. WIN_CheckWParamMouseButtons(WIN_GetEventTimestamp(), wParam, data, SDL_GLOBAL_MOUSE_ID);
  1234. }
  1235. }
  1236. } break;
  1237. #if 0 // We handle raw input all at once instead of using a syscall for each mouse event
  1238. case WM_INPUT:
  1239. {
  1240. HRAWINPUT hRawInput = (HRAWINPUT)lParam;
  1241. RAWINPUT inp;
  1242. UINT size = sizeof(inp);
  1243. // Relative mouse motion is delivered to the window with keyboard focus
  1244. if (data->window != SDL_GetKeyboardFocus()) {
  1245. break;
  1246. }
  1247. GetRawInputData(hRawInput, RID_INPUT, &inp, &size, sizeof(RAWINPUTHEADER));
  1248. if (inp.header.dwType == RIM_TYPEMOUSE) {
  1249. WIN_HandleRawMouseInput(WIN_GetEventTimestamp(), data, inp.header.hDevice, &inp.data.mouse);
  1250. } else if (inp.header.dwType == RIM_TYPEKEYBOARD) {
  1251. WIN_HandleRawKeyboardInput(WIN_GetEventTimestamp(), data, inp.header.hDevice, &inp.data.keyboard);
  1252. }
  1253. } break;
  1254. #endif
  1255. case WM_MOUSEWHEEL:
  1256. case WM_MOUSEHWHEEL:
  1257. {
  1258. if (!data->videodata->raw_mouse_enabled) {
  1259. short amount = GET_WHEEL_DELTA_WPARAM(wParam);
  1260. float fAmount = (float)amount / WHEEL_DELTA;
  1261. if (msg == WM_MOUSEWHEEL) {
  1262. SDL_SendMouseWheel(WIN_GetEventTimestamp(), data->window, SDL_GLOBAL_MOUSE_ID, 0.0f, fAmount, SDL_MOUSEWHEEL_NORMAL);
  1263. } else {
  1264. SDL_SendMouseWheel(WIN_GetEventTimestamp(), data->window, SDL_GLOBAL_MOUSE_ID, fAmount, 0.0f, SDL_MOUSEWHEEL_NORMAL);
  1265. }
  1266. }
  1267. } break;
  1268. case WM_MOUSELEAVE:
  1269. if (!(data->window->flags & SDL_WINDOW_MOUSE_CAPTURE)) {
  1270. if (SDL_GetMouseFocus() == data->window && !SDL_GetMouse()->relative_mode && !IsIconic(hwnd)) {
  1271. SDL_Mouse *mouse;
  1272. DWORD pos = GetMessagePos();
  1273. POINT cursorPos;
  1274. cursorPos.x = GET_X_LPARAM(pos);
  1275. cursorPos.y = GET_Y_LPARAM(pos);
  1276. ScreenToClient(hwnd, &cursorPos);
  1277. mouse = SDL_GetMouse();
  1278. if (!mouse->was_touch_mouse_events) { // we're not a touch handler causing a mouse leave?
  1279. SDL_SendMouseMotion(WIN_GetEventTimestamp(), data->window, SDL_GLOBAL_MOUSE_ID, false, (float)cursorPos.x, (float)cursorPos.y);
  1280. } else { // touch handling?
  1281. mouse->was_touch_mouse_events = false; // not anymore
  1282. if (mouse->touch_mouse_events) { // convert touch to mouse events
  1283. SDL_SendMouseMotion(WIN_GetEventTimestamp(), data->window, SDL_TOUCH_MOUSEID, false, (float)cursorPos.x, (float)cursorPos.y);
  1284. } else { // normal handling
  1285. SDL_SendMouseMotion(WIN_GetEventTimestamp(), data->window, SDL_GLOBAL_MOUSE_ID, false, (float)cursorPos.x, (float)cursorPos.y);
  1286. }
  1287. }
  1288. }
  1289. if (!SDL_GetMouse()->relative_mode) {
  1290. // When WM_MOUSELEAVE is fired we can be assured that the cursor has left the window
  1291. SDL_SetMouseFocus(NULL);
  1292. }
  1293. }
  1294. // Once we get WM_MOUSELEAVE we're guaranteed that the window is no longer tracked
  1295. data->mouse_tracked = false;
  1296. returnCode = 0;
  1297. break;
  1298. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  1299. case WM_KEYDOWN:
  1300. case WM_SYSKEYDOWN:
  1301. {
  1302. if (SkipAltGrLeftControl(wParam, lParam)) {
  1303. returnCode = 0;
  1304. break;
  1305. }
  1306. bool virtual_key = false;
  1307. Uint16 rawcode = 0;
  1308. SDL_Scancode code = WindowsScanCodeToSDLScanCode(lParam, wParam, &rawcode, &virtual_key);
  1309. // Detect relevant keyboard shortcuts
  1310. if (code == SDL_SCANCODE_F4 && (SDL_GetModState() & SDL_KMOD_ALT)) {
  1311. // ALT+F4: Close window
  1312. if (ShouldGenerateWindowCloseOnAltF4()) {
  1313. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_CLOSE_REQUESTED, 0, 0);
  1314. }
  1315. }
  1316. if (virtual_key || !data->videodata->raw_keyboard_enabled || data->window->text_input_active) {
  1317. SDL_SendKeyboardKey(WIN_GetEventTimestamp(), SDL_GLOBAL_KEYBOARD_ID, rawcode, code, true);
  1318. }
  1319. }
  1320. returnCode = 0;
  1321. break;
  1322. case WM_SYSKEYUP:
  1323. case WM_KEYUP:
  1324. {
  1325. if (SkipAltGrLeftControl(wParam, lParam)) {
  1326. returnCode = 0;
  1327. break;
  1328. }
  1329. bool virtual_key = false;
  1330. Uint16 rawcode = 0;
  1331. SDL_Scancode code = WindowsScanCodeToSDLScanCode(lParam, wParam, &rawcode, &virtual_key);
  1332. const bool *keyboardState = SDL_GetKeyboardState(NULL);
  1333. if (virtual_key || !data->videodata->raw_keyboard_enabled || data->window->text_input_active) {
  1334. if (code == SDL_SCANCODE_PRINTSCREEN && !keyboardState[code]) {
  1335. SDL_SendKeyboardKey(WIN_GetEventTimestamp(), SDL_GLOBAL_KEYBOARD_ID, rawcode, code, true);
  1336. }
  1337. SDL_SendKeyboardKey(WIN_GetEventTimestamp(), SDL_GLOBAL_KEYBOARD_ID, rawcode, code, false);
  1338. }
  1339. }
  1340. returnCode = 0;
  1341. break;
  1342. case WM_UNICHAR:
  1343. if (wParam == UNICODE_NOCHAR) {
  1344. returnCode = 1;
  1345. } else {
  1346. if (SDL_TextInputActive(data->window)) {
  1347. char text[5];
  1348. char *end = SDL_UCS4ToUTF8((Uint32)wParam, text);
  1349. *end = '\0';
  1350. SDL_SendKeyboardText(text);
  1351. }
  1352. returnCode = 0;
  1353. }
  1354. break;
  1355. case WM_CHAR:
  1356. if (SDL_TextInputActive(data->window)) {
  1357. /* Characters outside Unicode Basic Multilingual Plane (BMP)
  1358. * are coded as so called "surrogate pair" in two separate UTF-16 character events.
  1359. * Cache high surrogate until next character event. */
  1360. if (IS_HIGH_SURROGATE(wParam)) {
  1361. data->high_surrogate = (WCHAR)wParam;
  1362. } else {
  1363. WCHAR utf16[3];
  1364. utf16[0] = data->high_surrogate ? data->high_surrogate : (WCHAR)wParam;
  1365. utf16[1] = data->high_surrogate ? (WCHAR)wParam : L'\0';
  1366. utf16[2] = L'\0';
  1367. char utf8[5];
  1368. int result = WIN_WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, utf16, -1, utf8, sizeof(utf8), NULL, NULL);
  1369. if (result > 0) {
  1370. SDL_SendKeyboardText(utf8);
  1371. }
  1372. data->high_surrogate = L'\0';
  1373. }
  1374. } else {
  1375. data->high_surrogate = L'\0';
  1376. }
  1377. returnCode = 0;
  1378. break;
  1379. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  1380. #ifdef WM_INPUTLANGCHANGE
  1381. case WM_INPUTLANGCHANGE:
  1382. {
  1383. WIN_UpdateKeymap(true);
  1384. }
  1385. returnCode = 1;
  1386. break;
  1387. #endif // WM_INPUTLANGCHANGE
  1388. case WM_NCLBUTTONDOWN:
  1389. {
  1390. data->in_title_click = true;
  1391. // Fix for 500ms hang after user clicks on the title bar, but before moving mouse
  1392. // Reference: https://gamedev.net/forums/topic/672094-keeping-things-moving-during-win32-moveresize-events/5254386/
  1393. if (SendMessage(hwnd, WM_NCHITTEST, wParam, lParam) == HTCAPTION) {
  1394. POINT cursorPos;
  1395. GetCursorPos(&cursorPos); // want the most current pos so as to not cause position change
  1396. ScreenToClient(hwnd, &cursorPos);
  1397. PostMessage(hwnd, WM_MOUSEMOVE, 0, cursorPos.x | (((Uint32)((Sint16)cursorPos.y)) << 16));
  1398. }
  1399. } break;
  1400. case WM_CAPTURECHANGED:
  1401. {
  1402. data->in_title_click = false;
  1403. // The mouse may have been released during a modal loop
  1404. WIN_CheckAsyncMouseRelease(WIN_GetEventTimestamp(), data);
  1405. } break;
  1406. #ifdef WM_GETMINMAXINFO
  1407. case WM_GETMINMAXINFO:
  1408. {
  1409. MINMAXINFO *info;
  1410. RECT size;
  1411. int x, y;
  1412. int w, h;
  1413. int min_w, min_h;
  1414. int max_w, max_h;
  1415. BOOL constrain_max_size;
  1416. // If this is an expected size change, allow it
  1417. if (data->expected_resize) {
  1418. break;
  1419. }
  1420. // Get the current position of our window
  1421. GetWindowRect(hwnd, &size);
  1422. x = size.left;
  1423. y = size.top;
  1424. // Calculate current size of our window
  1425. SDL_GetWindowSize(data->window, &w, &h);
  1426. SDL_GetWindowMinimumSize(data->window, &min_w, &min_h);
  1427. SDL_GetWindowMaximumSize(data->window, &max_w, &max_h);
  1428. /* Store in min_w and min_h difference between current size and minimal
  1429. size so we don't need to call AdjustWindowRectEx twice */
  1430. min_w -= w;
  1431. min_h -= h;
  1432. if (max_w && max_h) {
  1433. max_w -= w;
  1434. max_h -= h;
  1435. constrain_max_size = TRUE;
  1436. } else {
  1437. constrain_max_size = FALSE;
  1438. }
  1439. if (!(SDL_GetWindowFlags(data->window) & SDL_WINDOW_BORDERLESS) && !SDL_WINDOW_IS_POPUP(data->window)) {
  1440. size.top = 0;
  1441. size.left = 0;
  1442. size.bottom = h;
  1443. size.right = w;
  1444. WIN_AdjustWindowRectForHWND(hwnd, &size, 0);
  1445. w = size.right - size.left;
  1446. h = size.bottom - size.top;
  1447. #ifdef HIGHDPI_DEBUG
  1448. SDL_Log("WM_GETMINMAXINFO: max window size: %dx%d using dpi: %u", w, h, dpi);
  1449. #endif
  1450. }
  1451. // Fix our size to the current size
  1452. info = (MINMAXINFO *)lParam;
  1453. if (SDL_GetWindowFlags(data->window) & SDL_WINDOW_RESIZABLE) {
  1454. if (SDL_GetWindowFlags(data->window) & SDL_WINDOW_BORDERLESS) {
  1455. int screenW = GetSystemMetrics(SM_CXSCREEN);
  1456. int screenH = GetSystemMetrics(SM_CYSCREEN);
  1457. info->ptMaxSize.x = SDL_max(w, screenW);
  1458. info->ptMaxSize.y = SDL_max(h, screenH);
  1459. info->ptMaxPosition.x = SDL_min(0, ((screenW - w) / 2));
  1460. info->ptMaxPosition.y = SDL_min(0, ((screenH - h) / 2));
  1461. }
  1462. info->ptMinTrackSize.x = (LONG)w + min_w;
  1463. info->ptMinTrackSize.y = (LONG)h + min_h;
  1464. if (constrain_max_size) {
  1465. info->ptMaxTrackSize.x = (LONG)w + max_w;
  1466. info->ptMaxTrackSize.y = (LONG)h + max_h;
  1467. }
  1468. } else {
  1469. info->ptMaxSize.x = w;
  1470. info->ptMaxSize.y = h;
  1471. info->ptMaxPosition.x = x;
  1472. info->ptMaxPosition.y = y;
  1473. info->ptMinTrackSize.x = w;
  1474. info->ptMinTrackSize.y = h;
  1475. info->ptMaxTrackSize.x = w;
  1476. info->ptMaxTrackSize.y = h;
  1477. }
  1478. }
  1479. returnCode = 0;
  1480. break;
  1481. #endif // WM_GETMINMAXINFO
  1482. case WM_WINDOWPOSCHANGING:
  1483. if (data->expected_resize) {
  1484. returnCode = 0;
  1485. }
  1486. break;
  1487. case WM_WINDOWPOSCHANGED:
  1488. {
  1489. SDL_Window *win;
  1490. const SDL_DisplayID original_displayID = data->last_displayID;
  1491. const WINDOWPOS *windowpos = (WINDOWPOS *)lParam;
  1492. bool iconic;
  1493. bool zoomed;
  1494. RECT rect;
  1495. int x, y;
  1496. int w, h;
  1497. if (windowpos->flags & SWP_SHOWWINDOW) {
  1498. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_SHOWN, 0, 0);
  1499. }
  1500. // These must be set after sending SDL_EVENT_WINDOW_SHOWN as that may apply pending
  1501. // window operations that change the window state.
  1502. iconic = IsIconic(hwnd);
  1503. zoomed = IsZoomed(hwnd);
  1504. if (iconic) {
  1505. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_MINIMIZED, 0, 0);
  1506. } else if (zoomed) {
  1507. if (data->window->flags & SDL_WINDOW_MINIMIZED) {
  1508. // If going from minimized to maximized, send the restored event first.
  1509. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_RESTORED, 0, 0);
  1510. }
  1511. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_MAXIMIZED, 0, 0);
  1512. data->force_ws_maximizebox = true;
  1513. } else if (data->window->flags & (SDL_WINDOW_MAXIMIZED | SDL_WINDOW_MINIMIZED)) {
  1514. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_RESTORED, 0, 0);
  1515. /* If resizable was forced on for the maximized window, clear the style flags now,
  1516. * but not if the window is fullscreen, as this needs to be preserved in that case.
  1517. */
  1518. if (!(data->window->flags & SDL_WINDOW_FULLSCREEN)) {
  1519. data->force_ws_maximizebox = false;
  1520. WIN_SetWindowResizable(SDL_GetVideoDevice(), data->window, !!(data->window->flags & SDL_WINDOW_RESIZABLE));
  1521. }
  1522. }
  1523. if (windowpos->flags & SWP_HIDEWINDOW) {
  1524. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_HIDDEN, 0, 0);
  1525. }
  1526. // When the window is minimized it's resized to the dock icon size, ignore this
  1527. if (iconic) {
  1528. break;
  1529. }
  1530. if (data->initializing) {
  1531. break;
  1532. }
  1533. if (!data->disable_move_size_events) {
  1534. if (GetClientRect(hwnd, &rect) && WIN_WindowRectValid(&rect)) {
  1535. ClientToScreen(hwnd, (LPPOINT) &rect);
  1536. ClientToScreen(hwnd, (LPPOINT) &rect + 1);
  1537. x = rect.left;
  1538. y = rect.top;
  1539. SDL_GlobalToRelativeForWindow(data->window, x, y, &x, &y);
  1540. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_MOVED, x, y);
  1541. }
  1542. // Moving the window from one display to another can change the size of the window (in the handling of SDL_EVENT_WINDOW_MOVED), so we need to re-query the bounds
  1543. if (GetClientRect(hwnd, &rect) && WIN_WindowRectValid(&rect)) {
  1544. w = rect.right;
  1545. h = rect.bottom;
  1546. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_RESIZED, w, h);
  1547. }
  1548. }
  1549. WIN_UpdateClipCursor(data->window);
  1550. // Update the window display position
  1551. data->last_displayID = SDL_GetDisplayForWindow(data->window);
  1552. if (data->last_displayID != original_displayID) {
  1553. // Display changed, check ICC profile
  1554. WIN_UpdateWindowICCProfile(data->window, true);
  1555. }
  1556. // Update the position of any child windows
  1557. for (win = data->window->first_child; win; win = win->next_sibling) {
  1558. // Don't update hidden child popup windows, their relative position doesn't change
  1559. if (SDL_WINDOW_IS_POPUP(win) && !(win->flags & SDL_WINDOW_HIDDEN)) {
  1560. WIN_SetWindowPositionInternal(win, SWP_NOCOPYBITS | SWP_NOACTIVATE, SDL_WINDOWRECT_CURRENT);
  1561. }
  1562. }
  1563. // Forces a WM_PAINT event
  1564. InvalidateRect(hwnd, NULL, FALSE);
  1565. } break;
  1566. case WM_ENTERSIZEMOVE:
  1567. case WM_ENTERMENULOOP:
  1568. {
  1569. if (g_WindowsMessageHook) {
  1570. if (!DispatchModalLoopMessageHook(&hwnd, &msg, &wParam, &lParam)) {
  1571. return 0;
  1572. }
  1573. }
  1574. ++data->in_modal_loop;
  1575. if (data->in_modal_loop == 1) {
  1576. data->initial_size_rect.left = data->window->x;
  1577. data->initial_size_rect.right = data->window->x + data->window->w;
  1578. data->initial_size_rect.top = data->window->y;
  1579. data->initial_size_rect.bottom = data->window->y + data->window->h;
  1580. SetTimer(hwnd, (UINT_PTR)SDL_IterateMainCallbacks, USER_TIMER_MINIMUM, NULL);
  1581. // Reset the keyboard, as we won't get any key up events during the modal loop
  1582. SDL_ResetKeyboard();
  1583. }
  1584. } break;
  1585. case WM_TIMER:
  1586. {
  1587. if (wParam == (UINT_PTR)SDL_IterateMainCallbacks) {
  1588. SDL_OnWindowLiveResizeUpdate(data->window);
  1589. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  1590. #if 0 // This locks up the Windows compositor when called by Steam; disabling until we understand why
  1591. // Make sure graphics operations are complete for smooth refresh
  1592. if (data->videodata->DwmFlush) {
  1593. data->videodata->DwmFlush();
  1594. }
  1595. #endif
  1596. #endif
  1597. return 0;
  1598. }
  1599. } break;
  1600. case WM_EXITSIZEMOVE:
  1601. case WM_EXITMENULOOP:
  1602. {
  1603. --data->in_modal_loop;
  1604. if (data->in_modal_loop == 0) {
  1605. KillTimer(hwnd, (UINT_PTR)SDL_IterateMainCallbacks);
  1606. }
  1607. } break;
  1608. case WM_SIZING:
  1609. {
  1610. WPARAM edge = wParam;
  1611. RECT* dragRect = (RECT*)lParam;
  1612. RECT clientDragRect = *dragRect;
  1613. bool lock_aspect_ratio = (data->window->max_aspect == data->window->min_aspect) ? true : false;
  1614. RECT rc;
  1615. LONG w, h;
  1616. float new_aspect;
  1617. // if aspect ratio constraints are not enabled then skip this message
  1618. if (data->window->min_aspect <= 0 && data->window->max_aspect <= 0) {
  1619. break;
  1620. }
  1621. // unadjust the dragRect from the window rect to the client rect
  1622. SetRectEmpty(&rc);
  1623. if (!AdjustWindowRectEx(&rc, GetWindowStyle(hwnd), GetMenu(hwnd) != NULL, GetWindowExStyle(hwnd))) {
  1624. break;
  1625. }
  1626. clientDragRect.left -= rc.left;
  1627. clientDragRect.top -= rc.top;
  1628. clientDragRect.right -= rc.right;
  1629. clientDragRect.bottom -= rc.bottom;
  1630. w = clientDragRect.right - clientDragRect.left;
  1631. h = clientDragRect.bottom - clientDragRect.top;
  1632. new_aspect = w / (float)h;
  1633. // handle the special case in which the min ar and max ar are the same so the window can size symmetrically
  1634. if (lock_aspect_ratio) {
  1635. switch (edge) {
  1636. case WMSZ_LEFT:
  1637. case WMSZ_RIGHT:
  1638. h = (int)SDL_roundf(w / data->window->max_aspect);
  1639. break;
  1640. default:
  1641. // resizing via corners or top or bottom
  1642. w = (int)SDL_roundf(h * data->window->max_aspect);
  1643. break;
  1644. }
  1645. } else {
  1646. switch (edge) {
  1647. case WMSZ_LEFT:
  1648. case WMSZ_RIGHT:
  1649. if (data->window->max_aspect > 0.0f && new_aspect > data->window->max_aspect) {
  1650. w = (int)SDL_roundf(h * data->window->max_aspect);
  1651. } else if (data->window->min_aspect > 0.0f && new_aspect < data->window->min_aspect) {
  1652. w = (int)SDL_roundf(h * data->window->min_aspect);
  1653. }
  1654. break;
  1655. case WMSZ_TOP:
  1656. case WMSZ_BOTTOM:
  1657. if (data->window->min_aspect > 0.0f && new_aspect < data->window->min_aspect) {
  1658. h = (int)SDL_roundf(w / data->window->min_aspect);
  1659. } else if (data->window->max_aspect > 0.0f && new_aspect > data->window->max_aspect) {
  1660. h = (int)SDL_roundf(w / data->window->max_aspect);
  1661. }
  1662. break;
  1663. default:
  1664. // resizing via corners
  1665. if (data->window->max_aspect > 0.0f && new_aspect > data->window->max_aspect) {
  1666. w = (int)SDL_roundf(h * data->window->max_aspect);
  1667. } else if (data->window->min_aspect > 0.0f && new_aspect < data->window->min_aspect) {
  1668. h = (int)SDL_roundf(w / data->window->min_aspect);
  1669. }
  1670. break;
  1671. }
  1672. }
  1673. switch (edge) {
  1674. case WMSZ_LEFT:
  1675. clientDragRect.left = clientDragRect.right - w;
  1676. if (lock_aspect_ratio) {
  1677. clientDragRect.top = (data->initial_size_rect.bottom + data->initial_size_rect.top - h) / 2;
  1678. }
  1679. clientDragRect.bottom = h + clientDragRect.top;
  1680. break;
  1681. case WMSZ_BOTTOMLEFT:
  1682. clientDragRect.left = clientDragRect.right - w;
  1683. clientDragRect.bottom = h + clientDragRect.top;
  1684. break;
  1685. case WMSZ_RIGHT:
  1686. clientDragRect.right = w + clientDragRect.left;
  1687. if (lock_aspect_ratio) {
  1688. clientDragRect.top = (data->initial_size_rect.bottom + data->initial_size_rect.top - h) / 2;
  1689. }
  1690. clientDragRect.bottom = h + clientDragRect.top;
  1691. break;
  1692. case WMSZ_TOPRIGHT:
  1693. clientDragRect.right = w + clientDragRect.left;
  1694. clientDragRect.top = clientDragRect.bottom - h;
  1695. break;
  1696. case WMSZ_TOP:
  1697. if (lock_aspect_ratio) {
  1698. clientDragRect.left = (data->initial_size_rect.right + data->initial_size_rect.left - w) / 2;
  1699. }
  1700. clientDragRect.right = w + clientDragRect.left;
  1701. clientDragRect.top = clientDragRect.bottom - h;
  1702. break;
  1703. case WMSZ_TOPLEFT:
  1704. clientDragRect.left = clientDragRect.right - w;
  1705. clientDragRect.top = clientDragRect.bottom - h;
  1706. break;
  1707. case WMSZ_BOTTOM:
  1708. if (lock_aspect_ratio) {
  1709. clientDragRect.left = (data->initial_size_rect.right + data->initial_size_rect.left - w) / 2;
  1710. }
  1711. clientDragRect.right = w + clientDragRect.left;
  1712. clientDragRect.bottom = h + clientDragRect.top;
  1713. break;
  1714. case WMSZ_BOTTOMRIGHT:
  1715. clientDragRect.right = w + clientDragRect.left;
  1716. clientDragRect.bottom = h + clientDragRect.top;
  1717. break;
  1718. }
  1719. // convert the client rect to a window rect
  1720. if (!AdjustWindowRectEx(&clientDragRect, GetWindowStyle(hwnd), GetMenu(hwnd) != NULL, GetWindowExStyle(hwnd))) {
  1721. break;
  1722. }
  1723. *dragRect = clientDragRect;
  1724. }
  1725. break;
  1726. case WM_SETCURSOR:
  1727. {
  1728. Uint16 hittest;
  1729. hittest = LOWORD(lParam);
  1730. if (hittest == HTCLIENT) {
  1731. SetCursor(SDL_cursor);
  1732. returnCode = TRUE;
  1733. } else if (!g_WindowFrameUsableWhileCursorHidden && !SDL_cursor) {
  1734. SetCursor(NULL);
  1735. returnCode = TRUE;
  1736. }
  1737. } break;
  1738. // We were occluded, refresh our display
  1739. case WM_PAINT:
  1740. {
  1741. RECT rect;
  1742. if (GetUpdateRect(hwnd, &rect, FALSE)) {
  1743. const LONG style = GetWindowLong(hwnd, GWL_EXSTYLE);
  1744. /* Composited windows will continue to receive WM_PAINT messages for update
  1745. regions until the window is actually painted through Begin/EndPaint */
  1746. if (style & WS_EX_COMPOSITED) {
  1747. PAINTSTRUCT ps;
  1748. BeginPaint(hwnd, &ps);
  1749. EndPaint(hwnd, &ps);
  1750. }
  1751. ValidateRect(hwnd, NULL);
  1752. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_EXPOSED, 0, 0);
  1753. }
  1754. }
  1755. returnCode = 0;
  1756. break;
  1757. // We'll do our own drawing, prevent flicker
  1758. case WM_ERASEBKGND:
  1759. if (ShouldClearWindowOnEraseBackground(data)) {
  1760. RECT client_rect;
  1761. HBRUSH brush;
  1762. data->videodata->cleared = true;
  1763. GetClientRect(hwnd, &client_rect);
  1764. brush = CreateSolidBrush(0);
  1765. FillRect(GetDC(hwnd), &client_rect, brush);
  1766. DeleteObject(brush);
  1767. }
  1768. return 1;
  1769. case WM_SYSCOMMAND:
  1770. {
  1771. if (!g_WindowsEnableMenuMnemonics) {
  1772. if ((wParam & 0xFFF0) == SC_KEYMENU) {
  1773. return 0;
  1774. }
  1775. }
  1776. #if defined(SC_SCREENSAVE) || defined(SC_MONITORPOWER)
  1777. // Don't start the screensaver or blank the monitor in fullscreen apps
  1778. if ((wParam & 0xFFF0) == SC_SCREENSAVE ||
  1779. (wParam & 0xFFF0) == SC_MONITORPOWER) {
  1780. if (SDL_GetVideoDevice()->suspend_screensaver) {
  1781. return 0;
  1782. }
  1783. }
  1784. #endif // System has screensaver support
  1785. } break;
  1786. case WM_CLOSE:
  1787. {
  1788. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_CLOSE_REQUESTED, 0, 0);
  1789. }
  1790. returnCode = 0;
  1791. break;
  1792. case WM_TOUCH:
  1793. if (data->videodata->GetTouchInputInfo && data->videodata->CloseTouchInputHandle) {
  1794. UINT i, num_inputs = LOWORD(wParam);
  1795. bool isstack;
  1796. PTOUCHINPUT inputs = SDL_small_alloc(TOUCHINPUT, num_inputs, &isstack);
  1797. if (inputs && data->videodata->GetTouchInputInfo((HTOUCHINPUT)lParam, num_inputs, inputs, sizeof(TOUCHINPUT))) {
  1798. RECT rect;
  1799. float x, y;
  1800. if (!GetClientRect(hwnd, &rect) || !WIN_WindowRectValid(&rect)) {
  1801. if (inputs) {
  1802. SDL_small_free(inputs, isstack);
  1803. }
  1804. break;
  1805. }
  1806. ClientToScreen(hwnd, (LPPOINT)&rect);
  1807. ClientToScreen(hwnd, (LPPOINT)&rect + 1);
  1808. rect.top *= 100;
  1809. rect.left *= 100;
  1810. rect.bottom *= 100;
  1811. rect.right *= 100;
  1812. for (i = 0; i < num_inputs; ++i) {
  1813. PTOUCHINPUT input = &inputs[i];
  1814. const int w = (rect.right - rect.left);
  1815. const int h = (rect.bottom - rect.top);
  1816. const SDL_TouchID touchId = (SDL_TouchID)((uintptr_t)input->hSource);
  1817. const SDL_FingerID fingerId = (input->dwID + 1);
  1818. /* TODO: Can we use GetRawInputDeviceInfo and HID info to
  1819. determine if this is a direct or indirect touch device?
  1820. */
  1821. if (SDL_AddTouch(touchId, SDL_TOUCH_DEVICE_DIRECT, (input->dwFlags & TOUCHEVENTF_PEN) == TOUCHEVENTF_PEN ? "pen" : "touch") < 0) {
  1822. continue;
  1823. }
  1824. // Get the normalized coordinates for the window
  1825. if (w <= 1) {
  1826. x = 0.5f;
  1827. } else {
  1828. x = (float)(input->x - rect.left) / (w - 1);
  1829. }
  1830. if (h <= 1) {
  1831. y = 0.5f;
  1832. } else {
  1833. y = (float)(input->y - rect.top) / (h - 1);
  1834. }
  1835. // FIXME: Should we use the input->dwTime field for the tick source of the timestamp?
  1836. if (input->dwFlags & TOUCHEVENTF_DOWN) {
  1837. SDL_SendTouch(WIN_GetEventTimestamp(), touchId, fingerId, data->window, SDL_EVENT_FINGER_DOWN, x, y, 1.0f);
  1838. }
  1839. if (input->dwFlags & TOUCHEVENTF_MOVE) {
  1840. SDL_SendTouchMotion(WIN_GetEventTimestamp(), touchId, fingerId, data->window, x, y, 1.0f);
  1841. }
  1842. if (input->dwFlags & TOUCHEVENTF_UP) {
  1843. SDL_SendTouch(WIN_GetEventTimestamp(), touchId, fingerId, data->window, SDL_EVENT_FINGER_UP, x, y, 1.0f);
  1844. }
  1845. }
  1846. }
  1847. SDL_small_free(inputs, isstack);
  1848. data->videodata->CloseTouchInputHandle((HTOUCHINPUT)lParam);
  1849. return 0;
  1850. }
  1851. break;
  1852. #ifdef HAVE_TPCSHRD_H
  1853. case WM_TABLET_QUERYSYSTEMGESTURESTATUS:
  1854. /* See https://msdn.microsoft.com/en-us/library/windows/desktop/bb969148(v=vs.85).aspx .
  1855. * If we're handling our own touches, we don't want any gestures.
  1856. * Not all of these settings are documented.
  1857. * The use of the undocumented ones was suggested by https://github.com/bjarkeck/GCGJ/blob/master/Monogame/Windows/WinFormsGameForm.cs . */
  1858. return TABLET_DISABLE_PRESSANDHOLD | TABLET_DISABLE_PENTAPFEEDBACK | TABLET_DISABLE_PENBARRELFEEDBACK | TABLET_DISABLE_TOUCHUIFORCEON | TABLET_DISABLE_TOUCHUIFORCEOFF | TABLET_DISABLE_TOUCHSWITCH | TABLET_DISABLE_FLICKS | TABLET_DISABLE_SMOOTHSCROLLING | TABLET_DISABLE_FLICKFALLBACKKEYS; // disables press and hold (right-click) gesture
  1859. // disables UI feedback on pen up (waves)
  1860. // disables UI feedback on pen button down (circle)
  1861. // disables pen flicks (back, forward, drag down, drag up)
  1862. #endif // HAVE_TPCSHRD_H
  1863. case WM_DROPFILES:
  1864. {
  1865. UINT i;
  1866. HDROP drop = (HDROP)wParam;
  1867. UINT count = DragQueryFile(drop, 0xFFFFFFFF, NULL, 0);
  1868. for (i = 0; i < count; ++i) {
  1869. UINT size = DragQueryFile(drop, i, NULL, 0) + 1;
  1870. LPTSTR buffer = (LPTSTR)SDL_malloc(sizeof(TCHAR) * size);
  1871. if (buffer) {
  1872. if (DragQueryFile(drop, i, buffer, size)) {
  1873. char *file = WIN_StringToUTF8(buffer);
  1874. SDL_SendDropFile(data->window, NULL, file);
  1875. SDL_free(file);
  1876. }
  1877. SDL_free(buffer);
  1878. }
  1879. }
  1880. SDL_SendDropComplete(data->window);
  1881. DragFinish(drop);
  1882. return 0;
  1883. } break;
  1884. case WM_DISPLAYCHANGE:
  1885. {
  1886. // Reacquire displays if any were added or removed
  1887. WIN_RefreshDisplays(SDL_GetVideoDevice());
  1888. } break;
  1889. case WM_NCCALCSIZE:
  1890. {
  1891. SDL_WindowFlags window_flags = SDL_GetWindowFlags(data->window);
  1892. if (wParam == TRUE && (window_flags & SDL_WINDOW_BORDERLESS) && !(window_flags & SDL_WINDOW_FULLSCREEN)) {
  1893. // When borderless, need to tell windows that the size of the non-client area is 0
  1894. NCCALCSIZE_PARAMS *params = (NCCALCSIZE_PARAMS *)lParam;
  1895. WINDOWPLACEMENT placement;
  1896. if (GetWindowPlacement(hwnd, &placement) && placement.showCmd == SW_MAXIMIZE) {
  1897. // Maximized borderless windows should use the monitor work area.
  1898. HMONITOR hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONULL);
  1899. if (!hMonitor) {
  1900. // The returned monitor can be null when restoring from minimized, so use the last coordinates.
  1901. const POINT pt = { data->window->windowed.x, data->window->windowed.y };
  1902. hMonitor = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
  1903. }
  1904. if (hMonitor) {
  1905. MONITORINFO info;
  1906. SDL_zero(info);
  1907. info.cbSize = sizeof(info);
  1908. if (GetMonitorInfo(hMonitor, &info)) {
  1909. params->rgrc[0] = info.rcWork;
  1910. }
  1911. }
  1912. } else if (!(window_flags & SDL_WINDOW_RESIZABLE) && !data->force_ws_maximizebox) {
  1913. int w, h;
  1914. if (data->window->last_size_pending) {
  1915. w = data->window->pending.w;
  1916. h = data->window->pending.h;
  1917. } else {
  1918. w = data->window->floating.w;
  1919. h = data->window->floating.h;
  1920. }
  1921. params->rgrc[0].right = params->rgrc[0].left + w;
  1922. params->rgrc[0].bottom = params->rgrc[0].top + h;
  1923. }
  1924. return 0;
  1925. }
  1926. } break;
  1927. case WM_NCHITTEST:
  1928. {
  1929. SDL_Window *window = data->window;
  1930. if (window->flags & SDL_WINDOW_TOOLTIP) {
  1931. return HTTRANSPARENT;
  1932. }
  1933. if (window->hit_test) {
  1934. POINT winpoint;
  1935. winpoint.x = GET_X_LPARAM(lParam);
  1936. winpoint.y = GET_Y_LPARAM(lParam);
  1937. if (ScreenToClient(hwnd, &winpoint)) {
  1938. SDL_Point point;
  1939. SDL_HitTestResult rc;
  1940. point.x = winpoint.x;
  1941. point.y = winpoint.y;
  1942. rc = window->hit_test(window, &point, window->hit_test_data);
  1943. switch (rc) {
  1944. #define POST_HIT_TEST(ret) \
  1945. { \
  1946. SDL_SendWindowEvent(data->window, SDL_EVENT_WINDOW_HIT_TEST, 0, 0); \
  1947. return ret; \
  1948. }
  1949. case SDL_HITTEST_DRAGGABLE:
  1950. {
  1951. /* If the mouse button state is something other than none or left button down,
  1952. * return HTCLIENT, or Windows will eat the button press.
  1953. */
  1954. SDL_MouseButtonFlags buttonState = SDL_GetGlobalMouseState(NULL, NULL);
  1955. if (buttonState && !(buttonState & SDL_BUTTON_LMASK)) {
  1956. // Set focus in case it was lost while previously moving over a draggable area.
  1957. SDL_SetMouseFocus(window);
  1958. return HTCLIENT;
  1959. }
  1960. POST_HIT_TEST(HTCAPTION);
  1961. }
  1962. case SDL_HITTEST_RESIZE_TOPLEFT:
  1963. POST_HIT_TEST(HTTOPLEFT);
  1964. case SDL_HITTEST_RESIZE_TOP:
  1965. POST_HIT_TEST(HTTOP);
  1966. case SDL_HITTEST_RESIZE_TOPRIGHT:
  1967. POST_HIT_TEST(HTTOPRIGHT);
  1968. case SDL_HITTEST_RESIZE_RIGHT:
  1969. POST_HIT_TEST(HTRIGHT);
  1970. case SDL_HITTEST_RESIZE_BOTTOMRIGHT:
  1971. POST_HIT_TEST(HTBOTTOMRIGHT);
  1972. case SDL_HITTEST_RESIZE_BOTTOM:
  1973. POST_HIT_TEST(HTBOTTOM);
  1974. case SDL_HITTEST_RESIZE_BOTTOMLEFT:
  1975. POST_HIT_TEST(HTBOTTOMLEFT);
  1976. case SDL_HITTEST_RESIZE_LEFT:
  1977. POST_HIT_TEST(HTLEFT);
  1978. #undef POST_HIT_TEST
  1979. case SDL_HITTEST_NORMAL:
  1980. return HTCLIENT;
  1981. }
  1982. }
  1983. // If we didn't return, this will call DefWindowProc below.
  1984. }
  1985. } break;
  1986. case WM_GETDPISCALEDSIZE:
  1987. // Windows 10 Creators Update+
  1988. /* Documented as only being sent to windows that are per-monitor V2 DPI aware.
  1989. Experimentation shows it's only sent during interactive dragging, not in response to
  1990. SetWindowPos. */
  1991. if (data->videodata->GetDpiForWindow && data->videodata->AdjustWindowRectExForDpi) {
  1992. /* Windows expects applications to scale their window rects linearly
  1993. when dragging between monitors with different DPI's.
  1994. e.g. a 100x100 window dragged to a 200% scaled monitor
  1995. becomes 200x200.
  1996. For SDL, we instead want the client size to scale linearly.
  1997. This is not the same as the window rect scaling linearly,
  1998. because Windows doesn't scale the non-client area (titlebar etc.)
  1999. linearly. So, we need to handle this message to request custom
  2000. scaling. */
  2001. const int nextDPI = (int)wParam;
  2002. const int prevDPI = (int)data->videodata->GetDpiForWindow(hwnd);
  2003. SIZE *sizeInOut = (SIZE *)lParam;
  2004. int frame_w, frame_h;
  2005. int query_client_w_win, query_client_h_win;
  2006. #ifdef HIGHDPI_DEBUG
  2007. SDL_Log("WM_GETDPISCALEDSIZE: current DPI: %d potential DPI: %d input size: (%dx%d)",
  2008. prevDPI, nextDPI, sizeInOut->cx, sizeInOut->cy);
  2009. #endif
  2010. // Subtract the window frame size that would have been used at prevDPI
  2011. {
  2012. RECT rect = { 0 };
  2013. if (!(data->window->flags & SDL_WINDOW_BORDERLESS) && !SDL_WINDOW_IS_POPUP(data->window)) {
  2014. WIN_AdjustWindowRectForHWND(hwnd, &rect, prevDPI);
  2015. }
  2016. frame_w = -rect.left + rect.right;
  2017. frame_h = -rect.top + rect.bottom;
  2018. query_client_w_win = sizeInOut->cx - frame_w;
  2019. query_client_h_win = sizeInOut->cy - frame_h;
  2020. }
  2021. // Add the window frame size that would be used at nextDPI
  2022. {
  2023. RECT rect = { 0 };
  2024. rect.right = query_client_w_win;
  2025. rect.bottom = query_client_h_win;
  2026. if (!(data->window->flags & SDL_WINDOW_BORDERLESS) && !SDL_WINDOW_IS_POPUP(data->window)) {
  2027. WIN_AdjustWindowRectForHWND(hwnd, &rect, nextDPI);
  2028. }
  2029. // This is supposed to control the suggested rect param of WM_DPICHANGED
  2030. sizeInOut->cx = rect.right - rect.left;
  2031. sizeInOut->cy = rect.bottom - rect.top;
  2032. }
  2033. #ifdef HIGHDPI_DEBUG
  2034. SDL_Log("WM_GETDPISCALEDSIZE: output size: (%dx%d)", sizeInOut->cx, sizeInOut->cy);
  2035. #endif
  2036. return TRUE;
  2037. }
  2038. break;
  2039. case WM_DPICHANGED:
  2040. // Windows 8.1+
  2041. {
  2042. const int newDPI = HIWORD(wParam);
  2043. RECT *const suggestedRect = (RECT *)lParam;
  2044. int w, h;
  2045. #ifdef HIGHDPI_DEBUG
  2046. SDL_Log("WM_DPICHANGED: to %d\tsuggested rect: (%d, %d), (%dx%d)", newDPI,
  2047. suggestedRect->left, suggestedRect->top, suggestedRect->right - suggestedRect->left, suggestedRect->bottom - suggestedRect->top);
  2048. #endif
  2049. if (data->expected_resize) {
  2050. /* This DPI change is coming from an explicit SetWindowPos call within SDL.
  2051. Assume all call sites are calculating the DPI-aware frame correctly, so
  2052. we don't need to do any further adjustment. */
  2053. #ifdef HIGHDPI_DEBUG
  2054. SDL_Log("WM_DPICHANGED: Doing nothing, assuming window is already sized correctly");
  2055. #endif
  2056. return 0;
  2057. }
  2058. // Interactive user-initiated resizing/movement
  2059. {
  2060. /* Calculate the new frame w/h such that
  2061. the client area size is maintained. */
  2062. RECT rect = { 0 };
  2063. rect.right = data->window->w;
  2064. rect.bottom = data->window->h;
  2065. if (!(data->window->flags & SDL_WINDOW_BORDERLESS)) {
  2066. WIN_AdjustWindowRectForHWND(hwnd, &rect, newDPI);
  2067. }
  2068. w = rect.right - rect.left;
  2069. h = rect.bottom - rect.top;
  2070. }
  2071. #ifdef HIGHDPI_DEBUG
  2072. SDL_Log("WM_DPICHANGED: current SDL window size: (%dx%d)\tcalling SetWindowPos: (%d, %d), (%dx%d)",
  2073. data->window->w, data->window->h,
  2074. suggestedRect->left, suggestedRect->top, w, h);
  2075. #endif
  2076. data->expected_resize = true;
  2077. SetWindowPos(hwnd,
  2078. NULL,
  2079. suggestedRect->left,
  2080. suggestedRect->top,
  2081. w,
  2082. h,
  2083. SWP_NOZORDER | SWP_NOACTIVATE);
  2084. data->expected_resize = false;
  2085. return 0;
  2086. }
  2087. break;
  2088. case WM_SETTINGCHANGE:
  2089. if (wParam == 0 && lParam != 0 && SDL_wcscmp((wchar_t *)lParam, L"ImmersiveColorSet") == 0) {
  2090. SDL_SetSystemTheme(WIN_GetSystemTheme());
  2091. WIN_UpdateDarkModeForHWND(hwnd);
  2092. }
  2093. if (wParam == SPI_SETMOUSE || wParam == SPI_SETMOUSESPEED) {
  2094. WIN_UpdateMouseSystemScale();
  2095. }
  2096. break;
  2097. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2098. }
  2099. #ifdef HAVE_SHOBJIDL_CORE_H
  2100. if (msg == data->videodata->WM_TASKBAR_BUTTON_CREATED) {
  2101. data->taskbar_button_created = true;
  2102. WIN_ApplyWindowProgress(SDL_GetVideoDevice(), data->window);
  2103. }
  2104. #endif
  2105. // If there's a window proc, assume it's going to handle messages
  2106. if (data->wndproc) {
  2107. return CallWindowProc(data->wndproc, hwnd, msg, wParam, lParam);
  2108. } else if (returnCode >= 0) {
  2109. return returnCode;
  2110. } else {
  2111. return CallWindowProc(DefWindowProc, hwnd, msg, wParam, lParam);
  2112. }
  2113. }
  2114. int WIN_WaitEventTimeout(SDL_VideoDevice *_this, Sint64 timeoutNS)
  2115. {
  2116. if (g_WindowsEnableMessageLoop) {
  2117. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2118. DWORD timeout, ret;
  2119. timeout = timeoutNS < 0 ? INFINITE : (DWORD)SDL_NS_TO_MS(timeoutNS);
  2120. ret = MsgWaitForMultipleObjects(0, NULL, FALSE, timeout, QS_ALLINPUT);
  2121. if (ret == WAIT_OBJECT_0) {
  2122. return 1;
  2123. } else {
  2124. return 0;
  2125. }
  2126. #else
  2127. // MsgWaitForMultipleObjects is desktop-only.
  2128. MSG msg;
  2129. BOOL message_result;
  2130. UINT_PTR timer_id = 0;
  2131. if (timeoutNS > 0) {
  2132. timer_id = SetTimer(NULL, 0, (UINT)SDL_NS_TO_MS(timeoutNS), NULL);
  2133. message_result = GetMessage(&msg, 0, 0, 0);
  2134. KillTimer(NULL, timer_id);
  2135. } else if (timeoutNS == 0) {
  2136. message_result = PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
  2137. } else {
  2138. message_result = GetMessage(&msg, 0, 0, 0);
  2139. }
  2140. if (message_result) {
  2141. if (msg.message == WM_TIMER && !msg.hwnd && msg.wParam == timer_id) {
  2142. return 0;
  2143. }
  2144. if (g_WindowsMessageHook) {
  2145. if (!g_WindowsMessageHook(g_WindowsMessageHookData, &msg)) {
  2146. return 1;
  2147. }
  2148. }
  2149. // Always translate the message in case it's a non-SDL window (e.g. with Qt integration)
  2150. TranslateMessage(&msg);
  2151. DispatchMessage(&msg);
  2152. return 1;
  2153. } else {
  2154. return 0;
  2155. }
  2156. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2157. } else {
  2158. // Fail the wait so the caller falls back to polling
  2159. return -1;
  2160. }
  2161. }
  2162. void WIN_SendWakeupEvent(SDL_VideoDevice *_this, SDL_Window *window)
  2163. {
  2164. SDL_WindowData *data = window->internal;
  2165. PostMessage(data->hwnd, data->videodata->_SDL_WAKEUP, 0, 0);
  2166. }
  2167. void WIN_PumpEvents(SDL_VideoDevice *_this)
  2168. {
  2169. MSG msg;
  2170. #ifdef _MSC_VER // We explicitly want to use GetTickCount(), not GetTickCount64()
  2171. #pragma warning(push)
  2172. #pragma warning(disable : 28159)
  2173. #endif
  2174. DWORD end_ticks = GetTickCount() + 1;
  2175. #ifdef _MSC_VER
  2176. #pragma warning(pop)
  2177. #endif
  2178. int new_messages = 0;
  2179. if (_this->internal->gameinput_context) {
  2180. WIN_UpdateGameInput(_this);
  2181. }
  2182. if (g_WindowsEnableMessageLoop) {
  2183. SDL_processing_messages = true;
  2184. while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
  2185. if (g_WindowsMessageHook) {
  2186. if (!g_WindowsMessageHook(g_WindowsMessageHookData, &msg)) {
  2187. continue;
  2188. }
  2189. }
  2190. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2191. // Don't dispatch any mouse motion queued prior to or including the last mouse warp
  2192. if (msg.message == WM_MOUSEMOVE && SDL_last_warp_time) {
  2193. if (!SDL_TICKS_PASSED(msg.time, (SDL_last_warp_time + 1))) {
  2194. continue;
  2195. }
  2196. // This mouse message happened after the warp
  2197. SDL_last_warp_time = 0;
  2198. }
  2199. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2200. WIN_SetMessageTick(msg.time);
  2201. // Always translate the message in case it's a non-SDL window (e.g. with Qt integration)
  2202. TranslateMessage(&msg);
  2203. DispatchMessage(&msg);
  2204. // Make sure we don't busy loop here forever if there are lots of events coming in
  2205. if (SDL_TICKS_PASSED(msg.time, end_ticks)) {
  2206. /* We might get a few new messages generated by the Steam overlay or other application hooks
  2207. In this case those messages will be processed before any pending input, so we want to continue after those messages.
  2208. (thanks to Peter Deayton for his investigation here)
  2209. */
  2210. const int MAX_NEW_MESSAGES = 3;
  2211. ++new_messages;
  2212. if (new_messages > MAX_NEW_MESSAGES) {
  2213. break;
  2214. }
  2215. }
  2216. }
  2217. SDL_processing_messages = false;
  2218. }
  2219. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2220. /* Windows loses a shift KEYUP event when you have both pressed at once and let go of one.
  2221. You won't get a KEYUP until both are released, and that keyup will only be for the second
  2222. key you released. Take heroic measures and check the keystate as of the last handled event,
  2223. and if we think a key is pressed when Windows doesn't, unstick it in SDL's state. */
  2224. const bool *keystate = SDL_GetKeyboardState(NULL);
  2225. if (keystate[SDL_SCANCODE_LSHIFT] && !(GetKeyState(VK_LSHIFT) & 0x8000)) {
  2226. SDL_SendKeyboardKey(0, SDL_GLOBAL_KEYBOARD_ID, 0, SDL_SCANCODE_LSHIFT, false);
  2227. }
  2228. if (keystate[SDL_SCANCODE_RSHIFT] && !(GetKeyState(VK_RSHIFT) & 0x8000)) {
  2229. SDL_SendKeyboardKey(0, SDL_GLOBAL_KEYBOARD_ID, 0, SDL_SCANCODE_RSHIFT, false);
  2230. }
  2231. /* The Windows key state gets lost when using Windows+Space or Windows+G shortcuts and
  2232. not grabbing the keyboard. Note: If we *are* grabbing the keyboard, GetKeyState()
  2233. will return inaccurate results for VK_LWIN and VK_RWIN but we don't need it anyway. */
  2234. SDL_Window *focusWindow = SDL_GetKeyboardFocus();
  2235. if (!focusWindow || !(focusWindow->flags & SDL_WINDOW_KEYBOARD_GRABBED)) {
  2236. if (keystate[SDL_SCANCODE_LGUI] && !(GetKeyState(VK_LWIN) & 0x8000)) {
  2237. SDL_SendKeyboardKey(0, SDL_GLOBAL_KEYBOARD_ID, 0, SDL_SCANCODE_LGUI, false);
  2238. }
  2239. if (keystate[SDL_SCANCODE_RGUI] && !(GetKeyState(VK_RWIN) & 0x8000)) {
  2240. SDL_SendKeyboardKey(0, SDL_GLOBAL_KEYBOARD_ID, 0, SDL_SCANCODE_RGUI, false);
  2241. }
  2242. }
  2243. // fire queued clipcursor refreshes
  2244. if (_this) {
  2245. SDL_Window *window = _this->windows;
  2246. while (window) {
  2247. bool refresh_clipcursor = false;
  2248. SDL_WindowData *data = window->internal;
  2249. if (data) {
  2250. refresh_clipcursor = data->clipcursor_queued;
  2251. data->clipcursor_queued = false; // Must be cleared unconditionally.
  2252. data->postpone_clipcursor = false; // Must be cleared unconditionally.
  2253. // Must happen before UpdateClipCursor.
  2254. // Although its occurrence currently
  2255. // always coincides with the queuing of
  2256. // clipcursor, it is logically distinct
  2257. // and this coincidence might no longer
  2258. // be true in the future.
  2259. // Ergo this placement concordantly
  2260. // conveys its unconditionality
  2261. // vis-a-vis the queuing of clipcursor.
  2262. }
  2263. if (refresh_clipcursor) {
  2264. WIN_UpdateClipCursor(window);
  2265. }
  2266. window = window->next;
  2267. }
  2268. }
  2269. // Synchronize internal mouse capture state to the most current cursor state
  2270. // since for whatever reason we are not depending exclusively on SetCapture/
  2271. // ReleaseCapture to pipe in out-of-window mouse events.
  2272. // Formerly WIN_UpdateMouseCapture().
  2273. // TODO: can this go before clipcursor?
  2274. focusWindow = SDL_GetKeyboardFocus();
  2275. if (focusWindow && (focusWindow->flags & SDL_WINDOW_MOUSE_CAPTURE)) {
  2276. SDL_WindowData *data = focusWindow->internal;
  2277. if (!data->mouse_tracked) {
  2278. POINT cursorPos;
  2279. if (GetCursorPos(&cursorPos) && ScreenToClient(data->hwnd, &cursorPos)) {
  2280. bool swapButtons = GetSystemMetrics(SM_SWAPBUTTON) != 0;
  2281. SDL_MouseID mouseID = SDL_GLOBAL_MOUSE_ID;
  2282. SDL_SendMouseMotion(WIN_GetEventTimestamp(), data->window, mouseID, false, (float)cursorPos.x, (float)cursorPos.y);
  2283. SDL_SendMouseButton(WIN_GetEventTimestamp(), data->window, mouseID,
  2284. !swapButtons ? SDL_BUTTON_LEFT : SDL_BUTTON_RIGHT,
  2285. (GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0);
  2286. SDL_SendMouseButton(WIN_GetEventTimestamp(), data->window, mouseID,
  2287. !swapButtons ? SDL_BUTTON_RIGHT : SDL_BUTTON_LEFT,
  2288. (GetAsyncKeyState(VK_RBUTTON) & 0x8000) != 0);
  2289. SDL_SendMouseButton(WIN_GetEventTimestamp(), data->window, mouseID,
  2290. SDL_BUTTON_MIDDLE,
  2291. (GetAsyncKeyState(VK_MBUTTON) & 0x8000) != 0);
  2292. SDL_SendMouseButton(WIN_GetEventTimestamp(), data->window, mouseID,
  2293. SDL_BUTTON_X1,
  2294. (GetAsyncKeyState(VK_XBUTTON1) & 0x8000) != 0);
  2295. SDL_SendMouseButton(WIN_GetEventTimestamp(), data->window, mouseID,
  2296. SDL_BUTTON_X2,
  2297. (GetAsyncKeyState(VK_XBUTTON2) & 0x8000) != 0);
  2298. }
  2299. }
  2300. }
  2301. if (!_this->internal->gameinput_context) {
  2302. WIN_CheckKeyboardAndMouseHotplug(_this, false);
  2303. }
  2304. WIN_UpdateIMECandidates(_this);
  2305. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2306. #ifdef SDL_PLATFORM_GDK
  2307. GDK_DispatchTaskQueue();
  2308. #endif
  2309. }
  2310. static int app_registered = 0;
  2311. LPTSTR SDL_Appname = NULL;
  2312. Uint32 SDL_Appstyle = 0;
  2313. HINSTANCE SDL_Instance = NULL;
  2314. static void WIN_CleanRegisterApp(WNDCLASSEX wcex)
  2315. {
  2316. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2317. if (wcex.hIcon) {
  2318. DestroyIcon(wcex.hIcon);
  2319. }
  2320. if (wcex.hIconSm) {
  2321. DestroyIcon(wcex.hIconSm);
  2322. }
  2323. #endif
  2324. SDL_free(SDL_Appname);
  2325. SDL_Appname = NULL;
  2326. }
  2327. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2328. static BOOL CALLBACK WIN_ResourceNameCallback(HMODULE hModule, LPCTSTR lpType, LPTSTR lpName, LONG_PTR lParam)
  2329. {
  2330. WNDCLASSEX *wcex = (WNDCLASSEX *)lParam;
  2331. (void)lpType; // We already know that the resource type is RT_GROUP_ICON.
  2332. /* We leave hIconSm as NULL as it will allow Windows to automatically
  2333. choose the appropriate small icon size to suit the current DPI. */
  2334. wcex->hIcon = LoadIcon(hModule, lpName);
  2335. // Do not bother enumerating any more.
  2336. return FALSE;
  2337. }
  2338. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2339. // Register the class for this application
  2340. bool SDL_RegisterApp(const char *name, Uint32 style, void *hInst)
  2341. {
  2342. WNDCLASSEX wcex;
  2343. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2344. const char *hint;
  2345. #endif
  2346. // Only do this once...
  2347. if (app_registered) {
  2348. ++app_registered;
  2349. return true;
  2350. }
  2351. SDL_assert(!SDL_Appname);
  2352. if (!name) {
  2353. name = "SDL_app";
  2354. #if defined(CS_BYTEALIGNCLIENT) || defined(CS_OWNDC)
  2355. style = (CS_BYTEALIGNCLIENT | CS_OWNDC);
  2356. #endif
  2357. }
  2358. SDL_Appname = WIN_UTF8ToString(name);
  2359. SDL_Appstyle = style;
  2360. SDL_Instance = hInst ? (HINSTANCE)hInst : GetModuleHandle(NULL);
  2361. // Register the application class
  2362. wcex.cbSize = sizeof(WNDCLASSEX);
  2363. wcex.hCursor = NULL;
  2364. wcex.hIcon = NULL;
  2365. wcex.hIconSm = NULL;
  2366. wcex.lpszMenuName = NULL;
  2367. wcex.lpszClassName = SDL_Appname;
  2368. wcex.style = SDL_Appstyle;
  2369. wcex.hbrBackground = NULL;
  2370. wcex.lpfnWndProc = WIN_WindowProc;
  2371. wcex.hInstance = SDL_Instance;
  2372. wcex.cbClsExtra = 0;
  2373. wcex.cbWndExtra = 0;
  2374. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2375. hint = SDL_GetHint(SDL_HINT_WINDOWS_INTRESOURCE_ICON);
  2376. if (hint && *hint) {
  2377. wcex.hIcon = LoadIcon(SDL_Instance, MAKEINTRESOURCE(SDL_atoi(hint)));
  2378. hint = SDL_GetHint(SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL);
  2379. if (hint && *hint) {
  2380. wcex.hIconSm = LoadIcon(SDL_Instance, MAKEINTRESOURCE(SDL_atoi(hint)));
  2381. }
  2382. } else {
  2383. // Use the first icon as a default icon, like in the Explorer.
  2384. EnumResourceNames(SDL_Instance, RT_GROUP_ICON, WIN_ResourceNameCallback, (LONG_PTR)&wcex);
  2385. }
  2386. #endif // !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2387. if (!RegisterClassEx(&wcex)) {
  2388. WIN_CleanRegisterApp(wcex);
  2389. return SDL_SetError("Couldn't register application class");
  2390. }
  2391. app_registered = 1;
  2392. return true;
  2393. }
  2394. // Unregisters the windowclass registered in SDL_RegisterApp above.
  2395. void SDL_UnregisterApp(void)
  2396. {
  2397. WNDCLASSEX wcex;
  2398. // SDL_RegisterApp might not have been called before
  2399. if (!app_registered) {
  2400. return;
  2401. }
  2402. --app_registered;
  2403. if (app_registered == 0) {
  2404. // Ensure the icons are initialized.
  2405. wcex.hIcon = NULL;
  2406. wcex.hIconSm = NULL;
  2407. // Check for any registered window classes.
  2408. #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  2409. if (GetClassInfoEx(SDL_Instance, SDL_Appname, &wcex)) {
  2410. UnregisterClass(SDL_Appname, SDL_Instance);
  2411. }
  2412. #endif
  2413. WIN_CleanRegisterApp(wcex);
  2414. }
  2415. }
  2416. #endif // SDL_VIDEO_DRIVER_WINDOWS