SDL_windowsevents.c 96 KB

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