Path: blob/master/thirdparty/sdl/events/SDL_events.c
22240 views
/*1Simple DirectMedia Layer2Copyright (C) 1997-2025 Sam Lantinga <[email protected]>34This software is provided 'as-is', without any express or implied5warranty. In no event will the authors be held liable for any damages6arising from the use of this software.78Permission is granted to anyone to use this software for any purpose,9including commercial applications, and to alter it and redistribute it10freely, subject to the following restrictions:11121. The origin of this software must not be misrepresented; you must not13claim that you wrote the original software. If you use this software14in a product, an acknowledgment in the product documentation would be15appreciated but is not required.162. Altered source versions must be plainly marked as such, and must not be17misrepresented as being the original software.183. This notice may not be removed or altered from any source distribution.19*/20#include "SDL_internal.h"2122// General event handling code for SDL2324#include "SDL_events_c.h"25#include "SDL_eventwatch_c.h"26#include "../SDL_hints_c.h"27#include "../timer/SDL_timer_c.h"28#ifndef SDL_JOYSTICK_DISABLED29#include "../joystick/SDL_joystick_c.h"30#endif31#ifndef SDL_SENSOR_DISABLED32#include "../sensor/SDL_sensor_c.h"33#endif34//#include "../video/SDL_sysvideo.h"3536#ifdef SDL_PLATFORM_ANDROID37#include "../core/android/SDL_android.h"38#include "../video/android/SDL_androidevents.h"39#endif4041// An arbitrary limit so we don't have unbounded growth42#define SDL_MAX_QUEUED_EVENTS 655354344// Determines how often we pump events if joystick or sensor subsystems are active45#define ENUMERATION_POLL_INTERVAL_NS (3 * SDL_NS_PER_SECOND)4647// Determines how often to pump events if joysticks or sensors are actively being read48#define EVENT_POLL_INTERVAL_NS SDL_MS_TO_NS(1)4950// Make sure the type in the SDL_Event aligns properly across the union51SDL_COMPILE_TIME_ASSERT(SDL_Event_type, sizeof(Uint32) == sizeof(SDL_EventType));5253#define SDL2_SYSWMEVENT 0x2015455#ifdef SDL_VIDEO_DRIVER_WINDOWS56#include "../core/windows/SDL_windows.h"57#endif5859#ifdef SDL_VIDEO_DRIVER_X1160#include <X11/Xlib.h>61#endif6263typedef struct SDL2_version64{65Uint8 major;66Uint8 minor;67Uint8 patch;68} SDL2_version;6970typedef enum71{72SDL2_SYSWM_UNKNOWN73} SDL2_SYSWM_TYPE;7475typedef struct SDL2_SysWMmsg76{77SDL2_version version;78SDL2_SYSWM_TYPE subsystem;79union80{81#ifdef SDL_VIDEO_DRIVER_WINDOWS82struct {83HWND hwnd; /**< The window for the message */84UINT msg; /**< The type of message */85WPARAM wParam; /**< WORD message parameter */86LPARAM lParam; /**< LONG message parameter */87} win;88#endif89#ifdef SDL_VIDEO_DRIVER_X1190struct {91XEvent event;92} x11;93#endif94/* Can't have an empty union */95int dummy;96} msg;97} SDL2_SysWMmsg;9899static SDL_EventWatchList SDL_event_watchers;100static SDL_AtomicInt SDL_sentinel_pending;101static Uint32 SDL_last_event_id = 0;102103typedef struct104{105Uint32 bits[8];106} SDL_DisabledEventBlock;107108static SDL_DisabledEventBlock *SDL_disabled_events[256];109static SDL_AtomicInt SDL_userevents;110111typedef struct SDL_TemporaryMemory112{113void *memory;114struct SDL_TemporaryMemory *prev;115struct SDL_TemporaryMemory *next;116} SDL_TemporaryMemory;117118typedef struct SDL_TemporaryMemoryState119{120SDL_TemporaryMemory *head;121SDL_TemporaryMemory *tail;122} SDL_TemporaryMemoryState;123124static SDL_TLSID SDL_temporary_memory;125126typedef struct SDL_EventEntry127{128SDL_Event event;129SDL_TemporaryMemory *memory;130struct SDL_EventEntry *prev;131struct SDL_EventEntry *next;132} SDL_EventEntry;133134static struct135{136SDL_Mutex *lock;137bool active;138SDL_AtomicInt count;139int max_events_seen;140SDL_EventEntry *head;141SDL_EventEntry *tail;142SDL_EventEntry *free;143} SDL_EventQ = { NULL, false, { 0 }, 0, NULL, NULL, NULL };144145146static void SDL_CleanupTemporaryMemory(void *data)147{148SDL_TemporaryMemoryState *state = (SDL_TemporaryMemoryState *)data;149150SDL_FreeTemporaryMemory();151SDL_free(state);152}153154static SDL_TemporaryMemoryState *SDL_GetTemporaryMemoryState(bool create)155{156SDL_TemporaryMemoryState *state;157158state = (SDL_TemporaryMemoryState *)SDL_GetTLS(&SDL_temporary_memory);159if (!state) {160if (!create) {161return NULL;162}163164state = (SDL_TemporaryMemoryState *)SDL_calloc(1, sizeof(*state));165if (!state) {166return NULL;167}168169if (!SDL_SetTLS(&SDL_temporary_memory, state, SDL_CleanupTemporaryMemory)) {170SDL_free(state);171return NULL;172}173}174return state;175}176177static SDL_TemporaryMemory *SDL_GetTemporaryMemoryEntry(SDL_TemporaryMemoryState *state, const void *mem)178{179SDL_TemporaryMemory *entry;180181// Start from the end, it's likely to have been recently allocated182for (entry = state->tail; entry; entry = entry->prev) {183if (mem == entry->memory) {184return entry;185}186}187return NULL;188}189190static void SDL_LinkTemporaryMemoryEntry(SDL_TemporaryMemoryState *state, SDL_TemporaryMemory *entry)191{192entry->prev = state->tail;193entry->next = NULL;194195if (state->tail) {196state->tail->next = entry;197} else {198state->head = entry;199}200state->tail = entry;201}202203static void SDL_UnlinkTemporaryMemoryEntry(SDL_TemporaryMemoryState *state, SDL_TemporaryMemory *entry)204{205if (state->head == entry) {206state->head = entry->next;207}208if (state->tail == entry) {209state->tail = entry->prev;210}211212if (entry->prev) {213entry->prev->next = entry->next;214}215if (entry->next) {216entry->next->prev = entry->prev;217}218219entry->prev = NULL;220entry->next = NULL;221}222223static void SDL_FreeTemporaryMemoryEntry(SDL_TemporaryMemoryState *state, SDL_TemporaryMemory *entry, bool free_data)224{225if (free_data) {226SDL_free(entry->memory);227}228SDL_free(entry);229}230231static void SDL_LinkTemporaryMemoryToEvent(SDL_EventEntry *event, const void *mem)232{233SDL_TemporaryMemoryState *state;234SDL_TemporaryMemory *entry;235236state = SDL_GetTemporaryMemoryState(false);237if (!state) {238return;239}240241entry = SDL_GetTemporaryMemoryEntry(state, mem);242if (entry) {243SDL_UnlinkTemporaryMemoryEntry(state, entry);244entry->next = event->memory;245event->memory = entry;246}247}248249static void SDL_TransferSysWMMemoryToEvent(SDL_EventEntry *event)250{251SDL2_SysWMmsg **wmmsg = (SDL2_SysWMmsg **)((&event->event.common)+1);252SDL2_SysWMmsg *mem = SDL_AllocateTemporaryMemory(sizeof(*mem));253if (mem) {254SDL_copyp(mem, *wmmsg);255*wmmsg = mem;256SDL_LinkTemporaryMemoryToEvent(event, mem);257}258}259260// Transfer the event memory from the thread-local event memory list to the event261static void SDL_TransferTemporaryMemoryToEvent(SDL_EventEntry *event)262{263switch (event->event.type) {264case SDL_EVENT_TEXT_EDITING:265SDL_LinkTemporaryMemoryToEvent(event, event->event.edit.text);266break;267case SDL_EVENT_TEXT_EDITING_CANDIDATES:268SDL_LinkTemporaryMemoryToEvent(event, event->event.edit_candidates.candidates);269break;270case SDL_EVENT_TEXT_INPUT:271SDL_LinkTemporaryMemoryToEvent(event, event->event.text.text);272break;273case SDL_EVENT_DROP_BEGIN:274case SDL_EVENT_DROP_FILE:275case SDL_EVENT_DROP_TEXT:276case SDL_EVENT_DROP_COMPLETE:277case SDL_EVENT_DROP_POSITION:278SDL_LinkTemporaryMemoryToEvent(event, event->event.drop.source);279SDL_LinkTemporaryMemoryToEvent(event, event->event.drop.data);280break;281case SDL_EVENT_CLIPBOARD_UPDATE:282SDL_LinkTemporaryMemoryToEvent(event, event->event.clipboard.mime_types);283break;284case SDL2_SYSWMEVENT:285// We need to copy the stack pointer into temporary memory286SDL_TransferSysWMMemoryToEvent(event);287break;288default:289break;290}291}292293// Transfer the event memory from the event to the thread-local event memory list294static void SDL_TransferTemporaryMemoryFromEvent(SDL_EventEntry *event)295{296SDL_TemporaryMemoryState *state;297SDL_TemporaryMemory *entry, *next;298299if (!event->memory) {300return;301}302303state = SDL_GetTemporaryMemoryState(true);304if (!state) {305return; // this is now a leak, but you probably have bigger problems if malloc failed.306}307308for (entry = event->memory; entry; entry = next) {309next = entry->next;310SDL_LinkTemporaryMemoryEntry(state, entry);311}312event->memory = NULL;313}314315static void *SDL_FreeLater(void *memory)316{317SDL_TemporaryMemoryState *state;318319if (memory == NULL) {320return NULL;321}322323// Make sure we're not adding this to the list twice324//SDL_assert(!SDL_ClaimTemporaryMemory(memory));325326state = SDL_GetTemporaryMemoryState(true);327if (!state) {328return memory; // this is now a leak, but you probably have bigger problems if malloc failed.329}330331SDL_TemporaryMemory *entry = (SDL_TemporaryMemory *)SDL_malloc(sizeof(*entry));332if (!entry) {333return memory; // this is now a leak, but you probably have bigger problems if malloc failed. We could probably pool up and reuse entries, though.334}335336entry->memory = memory;337338SDL_LinkTemporaryMemoryEntry(state, entry);339340return memory;341}342343void *SDL_AllocateTemporaryMemory(size_t size)344{345return SDL_FreeLater(SDL_malloc(size));346}347348const char *SDL_CreateTemporaryString(const char *string)349{350if (string) {351return (const char *)SDL_FreeLater(SDL_strdup(string));352}353return NULL;354}355356void *SDL_ClaimTemporaryMemory(const void *mem)357{358SDL_TemporaryMemoryState *state;359360state = SDL_GetTemporaryMemoryState(false);361if (state && mem) {362SDL_TemporaryMemory *entry = SDL_GetTemporaryMemoryEntry(state, mem);363if (entry) {364SDL_UnlinkTemporaryMemoryEntry(state, entry);365SDL_FreeTemporaryMemoryEntry(state, entry, false);366return (void *)mem;367}368}369return NULL;370}371372void SDL_FreeTemporaryMemory(void)373{374SDL_TemporaryMemoryState *state;375376state = SDL_GetTemporaryMemoryState(false);377if (!state) {378return;379}380381while (state->head) {382SDL_TemporaryMemory *entry = state->head;383384SDL_UnlinkTemporaryMemoryEntry(state, entry);385SDL_FreeTemporaryMemoryEntry(state, entry, true);386}387}388389#ifndef SDL_JOYSTICK_DISABLED390391static bool SDL_update_joysticks = true;392393static void SDLCALL SDL_AutoUpdateJoysticksChanged(void *userdata, const char *name, const char *oldValue, const char *hint)394{395SDL_update_joysticks = SDL_GetStringBoolean(hint, true);396}397398#endif // !SDL_JOYSTICK_DISABLED399400#ifndef SDL_SENSOR_DISABLED401402static bool SDL_update_sensors = true;403404static void SDLCALL SDL_AutoUpdateSensorsChanged(void *userdata, const char *name, const char *oldValue, const char *hint)405{406SDL_update_sensors = SDL_GetStringBoolean(hint, true);407}408409#endif // !SDL_SENSOR_DISABLED410411static void SDLCALL SDL_PollSentinelChanged(void *userdata, const char *name, const char *oldValue, const char *hint)412{413SDL_SetEventEnabled(SDL_EVENT_POLL_SENTINEL, SDL_GetStringBoolean(hint, true));414}415416/**417* Verbosity of logged events as defined in SDL_HINT_EVENT_LOGGING:418* - 0: (default) no logging419* - 1: logging of most events420* - 2: as above, plus mouse, pen, and finger motion421*/422static int SDL_EventLoggingVerbosity = 0;423424static void SDLCALL SDL_EventLoggingChanged(void *userdata, const char *name, const char *oldValue, const char *hint)425{426SDL_EventLoggingVerbosity = (hint && *hint) ? SDL_clamp(SDL_atoi(hint), 0, 3) : 0;427}428429static void SDL_LogEvent(const SDL_Event *event)430{431static const char *pen_axisnames[] = { "PRESSURE", "XTILT", "YTILT", "DISTANCE", "ROTATION", "SLIDER", "TANGENTIAL_PRESSURE" };432SDL_COMPILE_TIME_ASSERT(pen_axisnames_array_matches, SDL_arraysize(pen_axisnames) == SDL_PEN_AXIS_COUNT);433434char name[64];435char details[128];436437// sensor/mouse/pen/finger motion are spammy, ignore these if they aren't demanded.438if ((SDL_EventLoggingVerbosity < 2) &&439((event->type == SDL_EVENT_MOUSE_MOTION) ||440(event->type == SDL_EVENT_FINGER_MOTION) ||441(event->type == SDL_EVENT_PEN_AXIS) ||442(event->type == SDL_EVENT_PEN_MOTION) ||443(event->type == SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION) ||444(event->type == SDL_EVENT_GAMEPAD_SENSOR_UPDATE) ||445(event->type == SDL_EVENT_SENSOR_UPDATE))) {446return;447}448449// this is to make (void)SDL_snprintf() calls cleaner.450#define uint unsigned int451452name[0] = '\0';453details[0] = '\0';454455// !!! FIXME: This code is kinda ugly, sorry.456457if ((event->type >= SDL_EVENT_USER) && (event->type <= SDL_EVENT_LAST)) {458char plusstr[16];459SDL_strlcpy(name, "SDL_EVENT_USER", sizeof(name));460if (event->type > SDL_EVENT_USER) {461(void)SDL_snprintf(plusstr, sizeof(plusstr), "+%u", ((uint)event->type) - SDL_EVENT_USER);462} else {463plusstr[0] = '\0';464}465(void)SDL_snprintf(details, sizeof(details), "%s (timestamp=%u windowid=%u code=%d data1=%p data2=%p)",466plusstr, (uint)event->user.timestamp, (uint)event->user.windowID,467(int)event->user.code, event->user.data1, event->user.data2);468}469470switch (event->type) {471#define SDL_EVENT_CASE(x) \472case x: \473SDL_strlcpy(name, #x, sizeof(name));474SDL_EVENT_CASE(SDL_EVENT_FIRST)475SDL_strlcpy(details, " (THIS IS PROBABLY A BUG!)", sizeof(details));476break;477SDL_EVENT_CASE(SDL_EVENT_QUIT)478(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u)", (uint)event->quit.timestamp);479break;480SDL_EVENT_CASE(SDL_EVENT_TERMINATING)481break;482SDL_EVENT_CASE(SDL_EVENT_LOW_MEMORY)483break;484SDL_EVENT_CASE(SDL_EVENT_WILL_ENTER_BACKGROUND)485break;486SDL_EVENT_CASE(SDL_EVENT_DID_ENTER_BACKGROUND)487break;488SDL_EVENT_CASE(SDL_EVENT_WILL_ENTER_FOREGROUND)489break;490SDL_EVENT_CASE(SDL_EVENT_DID_ENTER_FOREGROUND)491break;492SDL_EVENT_CASE(SDL_EVENT_LOCALE_CHANGED)493break;494SDL_EVENT_CASE(SDL_EVENT_SYSTEM_THEME_CHANGED)495break;496SDL_EVENT_CASE(SDL_EVENT_KEYMAP_CHANGED)497break;498SDL_EVENT_CASE(SDL_EVENT_CLIPBOARD_UPDATE)499break;500501#define SDL_RENDEREVENT_CASE(x) \502case x: \503SDL_strlcpy(name, #x, sizeof(name)); \504(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u event=%s windowid=%u)", \505(uint)event->display.timestamp, name, (uint)event->render.windowID); \506break507SDL_RENDEREVENT_CASE(SDL_EVENT_RENDER_TARGETS_RESET);508SDL_RENDEREVENT_CASE(SDL_EVENT_RENDER_DEVICE_RESET);509SDL_RENDEREVENT_CASE(SDL_EVENT_RENDER_DEVICE_LOST);510511#define SDL_DISPLAYEVENT_CASE(x) \512case x: \513SDL_strlcpy(name, #x, sizeof(name)); \514(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u display=%u event=%s data1=%d, data2=%d)", \515(uint)event->display.timestamp, (uint)event->display.displayID, name, (int)event->display.data1, (int)event->display.data2); \516break517SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_ORIENTATION);518SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_ADDED);519SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_REMOVED);520SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_MOVED);521SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_DESKTOP_MODE_CHANGED);522SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_CURRENT_MODE_CHANGED);523SDL_DISPLAYEVENT_CASE(SDL_EVENT_DISPLAY_CONTENT_SCALE_CHANGED);524#undef SDL_DISPLAYEVENT_CASE525526#define SDL_WINDOWEVENT_CASE(x) \527case x: \528SDL_strlcpy(name, #x, sizeof(name)); \529(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u event=%s data1=%d data2=%d)", \530(uint)event->window.timestamp, (uint)event->window.windowID, name, (int)event->window.data1, (int)event->window.data2); \531break532SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_SHOWN);533SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_HIDDEN);534SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_EXPOSED);535SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_MOVED);536SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_RESIZED);537SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED);538SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_METAL_VIEW_RESIZED);539SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_SAFE_AREA_CHANGED);540SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_MINIMIZED);541SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_MAXIMIZED);542SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_RESTORED);543SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_MOUSE_ENTER);544SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_MOUSE_LEAVE);545SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_FOCUS_GAINED);546SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_FOCUS_LOST);547SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_CLOSE_REQUESTED);548SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_HIT_TEST);549SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_ICCPROF_CHANGED);550SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_DISPLAY_CHANGED);551SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED);552SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_OCCLUDED);553SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_ENTER_FULLSCREEN);554SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_LEAVE_FULLSCREEN);555SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_DESTROYED);556SDL_WINDOWEVENT_CASE(SDL_EVENT_WINDOW_HDR_STATE_CHANGED);557#undef SDL_WINDOWEVENT_CASE558559#define PRINT_KEYDEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%u)", (uint)event->kdevice.timestamp, (uint)event->kdevice.which)560SDL_EVENT_CASE(SDL_EVENT_KEYBOARD_ADDED)561PRINT_KEYDEV_EVENT(event);562break;563SDL_EVENT_CASE(SDL_EVENT_KEYBOARD_REMOVED)564PRINT_KEYDEV_EVENT(event);565break;566#undef PRINT_KEYDEV_EVENT567568#define PRINT_KEY_EVENT(event) \569(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u state=%s repeat=%s scancode=%u keycode=%u mod=0x%x)", \570(uint)event->key.timestamp, (uint)event->key.windowID, (uint)event->key.which, \571event->key.down ? "pressed" : "released", \572event->key.repeat ? "true" : "false", \573(uint)event->key.scancode, \574(uint)event->key.key, \575(uint)event->key.mod)576SDL_EVENT_CASE(SDL_EVENT_KEY_DOWN)577PRINT_KEY_EVENT(event);578break;579SDL_EVENT_CASE(SDL_EVENT_KEY_UP)580PRINT_KEY_EVENT(event);581break;582#undef PRINT_KEY_EVENT583584SDL_EVENT_CASE(SDL_EVENT_TEXT_EDITING)585(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u text='%s' start=%d length=%d)",586(uint)event->edit.timestamp, (uint)event->edit.windowID,587event->edit.text, (int)event->edit.start, (int)event->edit.length);588break;589590SDL_EVENT_CASE(SDL_EVENT_TEXT_EDITING_CANDIDATES)591(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u num_candidates=%d selected_candidate=%d)",592(uint)event->edit_candidates.timestamp, (uint)event->edit_candidates.windowID,593(int)event->edit_candidates.num_candidates, (int)event->edit_candidates.selected_candidate);594break;595596SDL_EVENT_CASE(SDL_EVENT_TEXT_INPUT)597(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u text='%s')", (uint)event->text.timestamp, (uint)event->text.windowID, event->text.text);598break;599600#define PRINT_MOUSEDEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%u)", (uint)event->mdevice.timestamp, (uint)event->mdevice.which)601SDL_EVENT_CASE(SDL_EVENT_MOUSE_ADDED)602PRINT_MOUSEDEV_EVENT(event);603break;604SDL_EVENT_CASE(SDL_EVENT_MOUSE_REMOVED)605PRINT_MOUSEDEV_EVENT(event);606break;607#undef PRINT_MOUSEDEV_EVENT608609SDL_EVENT_CASE(SDL_EVENT_MOUSE_MOTION)610(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u state=%u x=%g y=%g xrel=%g yrel=%g)",611(uint)event->motion.timestamp, (uint)event->motion.windowID,612(uint)event->motion.which, (uint)event->motion.state,613event->motion.x, event->motion.y,614event->motion.xrel, event->motion.yrel);615break;616617#define PRINT_MBUTTON_EVENT(event) \618(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u button=%u state=%s clicks=%u x=%g y=%g)", \619(uint)event->button.timestamp, (uint)event->button.windowID, \620(uint)event->button.which, (uint)event->button.button, \621event->button.down ? "pressed" : "released", \622(uint)event->button.clicks, event->button.x, event->button.y)623SDL_EVENT_CASE(SDL_EVENT_MOUSE_BUTTON_DOWN)624PRINT_MBUTTON_EVENT(event);625break;626SDL_EVENT_CASE(SDL_EVENT_MOUSE_BUTTON_UP)627PRINT_MBUTTON_EVENT(event);628break;629#undef PRINT_MBUTTON_EVENT630631SDL_EVENT_CASE(SDL_EVENT_MOUSE_WHEEL)632(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u x=%g y=%g integer_x=%d integer_y=%d direction=%s)",633(uint)event->wheel.timestamp, (uint)event->wheel.windowID,634(uint)event->wheel.which, event->wheel.x, event->wheel.y,635(int)event->wheel.integer_x, (int)event->wheel.integer_y,636event->wheel.direction == SDL_MOUSEWHEEL_NORMAL ? "normal" : "flipped");637break;638639SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_AXIS_MOTION)640(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d axis=%u value=%d)",641(uint)event->jaxis.timestamp, (int)event->jaxis.which,642(uint)event->jaxis.axis, (int)event->jaxis.value);643break;644645SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_BALL_MOTION)646(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d ball=%u xrel=%d yrel=%d)",647(uint)event->jball.timestamp, (int)event->jball.which,648(uint)event->jball.ball, (int)event->jball.xrel, (int)event->jball.yrel);649break;650651SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_HAT_MOTION)652(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d hat=%u value=%u)",653(uint)event->jhat.timestamp, (int)event->jhat.which,654(uint)event->jhat.hat, (uint)event->jhat.value);655break;656657#define PRINT_JBUTTON_EVENT(event) \658(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d button=%u state=%s)", \659(uint)event->jbutton.timestamp, (int)event->jbutton.which, \660(uint)event->jbutton.button, event->jbutton.down ? "pressed" : "released")661SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_BUTTON_DOWN)662PRINT_JBUTTON_EVENT(event);663break;664SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_BUTTON_UP)665PRINT_JBUTTON_EVENT(event);666break;667#undef PRINT_JBUTTON_EVENT668669SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_BATTERY_UPDATED)670(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d state=%u percent=%d)",671(uint)event->jbattery.timestamp, (int)event->jbattery.which,672event->jbattery.state, event->jbattery.percent);673break;674675#define PRINT_JOYDEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d)", (uint)event->jdevice.timestamp, (int)event->jdevice.which)676SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_ADDED)677PRINT_JOYDEV_EVENT(event);678break;679SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_REMOVED)680PRINT_JOYDEV_EVENT(event);681break;682SDL_EVENT_CASE(SDL_EVENT_JOYSTICK_UPDATE_COMPLETE)683PRINT_JOYDEV_EVENT(event);684break;685#undef PRINT_JOYDEV_EVENT686687SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_AXIS_MOTION)688(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d axis=%u value=%d)",689(uint)event->gaxis.timestamp, (int)event->gaxis.which,690(uint)event->gaxis.axis, (int)event->gaxis.value);691break;692693#define PRINT_CBUTTON_EVENT(event) \694(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d button=%u state=%s)", \695(uint)event->gbutton.timestamp, (int)event->gbutton.which, \696(uint)event->gbutton.button, event->gbutton.down ? "pressed" : "released")697SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_BUTTON_DOWN)698PRINT_CBUTTON_EVENT(event);699break;700SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_BUTTON_UP)701PRINT_CBUTTON_EVENT(event);702break;703#undef PRINT_CBUTTON_EVENT704705#define PRINT_GAMEPADDEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d)", (uint)event->gdevice.timestamp, (int)event->gdevice.which)706SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_ADDED)707PRINT_GAMEPADDEV_EVENT(event);708break;709SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_REMOVED)710PRINT_GAMEPADDEV_EVENT(event);711break;712SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_REMAPPED)713PRINT_GAMEPADDEV_EVENT(event);714break;715SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_UPDATE_COMPLETE)716PRINT_GAMEPADDEV_EVENT(event);717break;718SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_STEAM_HANDLE_UPDATED)719PRINT_GAMEPADDEV_EVENT(event);720break;721#undef PRINT_GAMEPADDEV_EVENT722723#define PRINT_CTOUCHPAD_EVENT(event) \724(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d touchpad=%d finger=%d x=%f y=%f pressure=%f)", \725(uint)event->gtouchpad.timestamp, (int)event->gtouchpad.which, \726(int)event->gtouchpad.touchpad, (int)event->gtouchpad.finger, \727event->gtouchpad.x, event->gtouchpad.y, event->gtouchpad.pressure)728SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN)729PRINT_CTOUCHPAD_EVENT(event);730break;731SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_TOUCHPAD_UP)732PRINT_CTOUCHPAD_EVENT(event);733break;734SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION)735PRINT_CTOUCHPAD_EVENT(event);736break;737#undef PRINT_CTOUCHPAD_EVENT738739SDL_EVENT_CASE(SDL_EVENT_GAMEPAD_SENSOR_UPDATE)740(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d sensor=%d data[0]=%f data[1]=%f data[2]=%f)",741(uint)event->gsensor.timestamp, (int)event->gsensor.which, (int)event->gsensor.sensor,742event->gsensor.data[0], event->gsensor.data[1], event->gsensor.data[2]);743break;744745#define PRINT_FINGER_EVENT(event) \746(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u touchid=%" SDL_PRIu64 " fingerid=%" SDL_PRIu64 " x=%f y=%f dx=%f dy=%f pressure=%f)", \747(uint)event->tfinger.timestamp, event->tfinger.touchID, \748event->tfinger.fingerID, event->tfinger.x, event->tfinger.y, \749event->tfinger.dx, event->tfinger.dy, event->tfinger.pressure)750SDL_EVENT_CASE(SDL_EVENT_FINGER_DOWN)751PRINT_FINGER_EVENT(event);752break;753SDL_EVENT_CASE(SDL_EVENT_FINGER_UP)754PRINT_FINGER_EVENT(event);755break;756SDL_EVENT_CASE(SDL_EVENT_FINGER_CANCELED)757PRINT_FINGER_EVENT(event);758break;759SDL_EVENT_CASE(SDL_EVENT_FINGER_MOTION)760PRINT_FINGER_EVENT(event);761break;762#undef PRINT_FINGER_EVENT763764#define PRINT_PTOUCH_EVENT(event) \765(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u pen_state=%u x=%g y=%g eraser=%s state=%s)", \766(uint)event->ptouch.timestamp, (uint)event->ptouch.windowID, (uint)event->ptouch.which, (uint)event->ptouch.pen_state, event->ptouch.x, event->ptouch.y, \767event->ptouch.eraser ? "yes" : "no", event->ptouch.down ? "down" : "up");768SDL_EVENT_CASE(SDL_EVENT_PEN_DOWN)769PRINT_PTOUCH_EVENT(event);770break;771SDL_EVENT_CASE(SDL_EVENT_PEN_UP)772PRINT_PTOUCH_EVENT(event);773break;774#undef PRINT_PTOUCH_EVENT775776#define PRINT_PPROXIMITY_EVENT(event) \777(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u)", \778(uint)event->pproximity.timestamp, (uint)event->pproximity.windowID, (uint)event->pproximity.which);779SDL_EVENT_CASE(SDL_EVENT_PEN_PROXIMITY_IN)780PRINT_PPROXIMITY_EVENT(event);781break;782SDL_EVENT_CASE(SDL_EVENT_PEN_PROXIMITY_OUT)783PRINT_PPROXIMITY_EVENT(event);784break;785#undef PRINT_PPROXIMITY_EVENT786787SDL_EVENT_CASE(SDL_EVENT_PEN_AXIS)788(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u pen_state=%u x=%g y=%g axis=%s value=%g)",789(uint)event->paxis.timestamp, (uint)event->paxis.windowID, (uint)event->paxis.which, (uint)event->paxis.pen_state, event->paxis.x, event->paxis.y,790((((int) event->paxis.axis) >= 0) && (event->paxis.axis < SDL_arraysize(pen_axisnames))) ? pen_axisnames[event->paxis.axis] : "[UNKNOWN]", event->paxis.value);791break;792793SDL_EVENT_CASE(SDL_EVENT_PEN_MOTION)794(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u pen_state=%u x=%g y=%g)",795(uint)event->pmotion.timestamp, (uint)event->pmotion.windowID, (uint)event->pmotion.which, (uint)event->pmotion.pen_state, event->pmotion.x, event->pmotion.y);796break;797798#define PRINT_PBUTTON_EVENT(event) \799(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u windowid=%u which=%u pen_state=%u x=%g y=%g button=%u state=%s)", \800(uint)event->pbutton.timestamp, (uint)event->pbutton.windowID, (uint)event->pbutton.which, (uint)event->pbutton.pen_state, event->pbutton.x, event->pbutton.y, \801(uint)event->pbutton.button, event->pbutton.down ? "down" : "up");802SDL_EVENT_CASE(SDL_EVENT_PEN_BUTTON_DOWN)803PRINT_PBUTTON_EVENT(event);804break;805SDL_EVENT_CASE(SDL_EVENT_PEN_BUTTON_UP)806PRINT_PBUTTON_EVENT(event);807break;808#undef PRINT_PBUTTON_EVENT809810#define PRINT_DROP_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (data='%s' timestamp=%u windowid=%u x=%f y=%f)", event->drop.data, (uint)event->drop.timestamp, (uint)event->drop.windowID, event->drop.x, event->drop.y)811SDL_EVENT_CASE(SDL_EVENT_DROP_FILE)812PRINT_DROP_EVENT(event);813break;814SDL_EVENT_CASE(SDL_EVENT_DROP_TEXT)815PRINT_DROP_EVENT(event);816break;817SDL_EVENT_CASE(SDL_EVENT_DROP_BEGIN)818PRINT_DROP_EVENT(event);819break;820SDL_EVENT_CASE(SDL_EVENT_DROP_COMPLETE)821PRINT_DROP_EVENT(event);822break;823SDL_EVENT_CASE(SDL_EVENT_DROP_POSITION)824PRINT_DROP_EVENT(event);825break;826#undef PRINT_DROP_EVENT827828#define PRINT_AUDIODEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%u recording=%s)", (uint)event->adevice.timestamp, (uint)event->adevice.which, event->adevice.recording ? "true" : "false")829SDL_EVENT_CASE(SDL_EVENT_AUDIO_DEVICE_ADDED)830PRINT_AUDIODEV_EVENT(event);831break;832SDL_EVENT_CASE(SDL_EVENT_AUDIO_DEVICE_REMOVED)833PRINT_AUDIODEV_EVENT(event);834break;835SDL_EVENT_CASE(SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED)836PRINT_AUDIODEV_EVENT(event);837break;838#undef PRINT_AUDIODEV_EVENT839840#define PRINT_CAMERADEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%u)", (uint)event->cdevice.timestamp, (uint)event->cdevice.which)841SDL_EVENT_CASE(SDL_EVENT_CAMERA_DEVICE_ADDED)842PRINT_CAMERADEV_EVENT(event);843break;844SDL_EVENT_CASE(SDL_EVENT_CAMERA_DEVICE_REMOVED)845PRINT_CAMERADEV_EVENT(event);846break;847SDL_EVENT_CASE(SDL_EVENT_CAMERA_DEVICE_APPROVED)848PRINT_CAMERADEV_EVENT(event);849break;850SDL_EVENT_CASE(SDL_EVENT_CAMERA_DEVICE_DENIED)851PRINT_CAMERADEV_EVENT(event);852break;853#undef PRINT_CAMERADEV_EVENT854855SDL_EVENT_CASE(SDL_EVENT_SENSOR_UPDATE)856(void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%d data[0]=%f data[1]=%f data[2]=%f data[3]=%f data[4]=%f data[5]=%f)",857(uint)event->sensor.timestamp, (int)event->sensor.which,858event->sensor.data[0], event->sensor.data[1], event->sensor.data[2],859event->sensor.data[3], event->sensor.data[4], event->sensor.data[5]);860break;861862#undef SDL_EVENT_CASE863864case SDL_EVENT_POLL_SENTINEL:865// No logging necessary for this one866break;867868default:869if (!name[0]) {870if (event->type >= SDL_EVENT_USER) {871SDL_strlcpy(name, "USER", sizeof(name));872} else {873SDL_strlcpy(name, "UNKNOWN", sizeof(name));874}875(void)SDL_snprintf(details, sizeof(details), " 0x%x", (uint)event->type);876}877break;878}879880if (name[0]) {881SDL_Log("SDL EVENT: %s%s", name, details);882}883884#undef uint885}886887void SDL_StopEventLoop(void)888{889const char *report = SDL_GetHint("SDL_EVENT_QUEUE_STATISTICS");890int i;891SDL_EventEntry *entry;892893SDL_LockMutex(SDL_EventQ.lock);894895SDL_EventQ.active = false;896897if (report && SDL_atoi(report)) {898SDL_Log("SDL EVENT QUEUE: Maximum events in-flight: %d",899SDL_EventQ.max_events_seen);900}901902// Clean out EventQ903for (entry = SDL_EventQ.head; entry;) {904SDL_EventEntry *next = entry->next;905SDL_TransferTemporaryMemoryFromEvent(entry);906SDL_free(entry);907entry = next;908}909for (entry = SDL_EventQ.free; entry;) {910SDL_EventEntry *next = entry->next;911SDL_free(entry);912entry = next;913}914915SDL_SetAtomicInt(&SDL_EventQ.count, 0);916SDL_EventQ.max_events_seen = 0;917SDL_EventQ.head = NULL;918SDL_EventQ.tail = NULL;919SDL_EventQ.free = NULL;920SDL_SetAtomicInt(&SDL_sentinel_pending, 0);921922// Clear disabled event state923for (i = 0; i < SDL_arraysize(SDL_disabled_events); ++i) {924SDL_free(SDL_disabled_events[i]);925SDL_disabled_events[i] = NULL;926}927928SDL_QuitEventWatchList(&SDL_event_watchers);929//SDL_QuitWindowEventWatch();930931SDL_Mutex *lock = NULL;932if (SDL_EventQ.lock) {933lock = SDL_EventQ.lock;934SDL_EventQ.lock = NULL;935}936937SDL_UnlockMutex(lock);938939if (lock) {940SDL_DestroyMutex(lock);941}942}943944// This function (and associated calls) may be called more than once945bool SDL_StartEventLoop(void)946{947/* We'll leave the event queue alone, since we might have gotten948some important events at launch (like SDL_EVENT_DROP_FILE)949950FIXME: Does this introduce any other bugs with events at startup?951*/952953// Create the lock and set ourselves active954#ifndef SDL_THREADS_DISABLED955if (!SDL_EventQ.lock) {956SDL_EventQ.lock = SDL_CreateMutex();957if (SDL_EventQ.lock == NULL) {958return false;959}960}961SDL_LockMutex(SDL_EventQ.lock);962963if (!SDL_InitEventWatchList(&SDL_event_watchers)) {964SDL_UnlockMutex(SDL_EventQ.lock);965return false;966}967#endif // !SDL_THREADS_DISABLED968969//SDL_InitWindowEventWatch();970971SDL_EventQ.active = true;972973#ifndef SDL_THREADS_DISABLED974SDL_UnlockMutex(SDL_EventQ.lock);975#endif976return true;977}978979// Add an event to the event queue -- called with the queue locked980static int SDL_AddEvent(SDL_Event *event)981{982SDL_EventEntry *entry;983const int initial_count = SDL_GetAtomicInt(&SDL_EventQ.count);984int final_count;985986if (initial_count >= SDL_MAX_QUEUED_EVENTS) {987SDL_SetError("Event queue is full (%d events)", initial_count);988return 0;989}990991if (SDL_EventQ.free == NULL) {992entry = (SDL_EventEntry *)SDL_malloc(sizeof(*entry));993if (entry == NULL) {994return 0;995}996} else {997entry = SDL_EventQ.free;998SDL_EventQ.free = entry->next;999}10001001if (SDL_EventLoggingVerbosity > 0) {1002SDL_LogEvent(event);1003}10041005SDL_copyp(&entry->event, event);1006if (event->type == SDL_EVENT_POLL_SENTINEL) {1007SDL_AddAtomicInt(&SDL_sentinel_pending, 1);1008}1009entry->memory = NULL;1010SDL_TransferTemporaryMemoryToEvent(entry);10111012if (SDL_EventQ.tail) {1013SDL_EventQ.tail->next = entry;1014entry->prev = SDL_EventQ.tail;1015SDL_EventQ.tail = entry;1016entry->next = NULL;1017} else {1018SDL_assert(!SDL_EventQ.head);1019SDL_EventQ.head = entry;1020SDL_EventQ.tail = entry;1021entry->prev = NULL;1022entry->next = NULL;1023}10241025final_count = SDL_AddAtomicInt(&SDL_EventQ.count, 1) + 1;1026if (final_count > SDL_EventQ.max_events_seen) {1027SDL_EventQ.max_events_seen = final_count;1028}10291030++SDL_last_event_id;10311032return 1;1033}10341035// Remove an event from the queue -- called with the queue locked1036static void SDL_CutEvent(SDL_EventEntry *entry)1037{1038SDL_TransferTemporaryMemoryFromEvent(entry);10391040if (entry->prev) {1041entry->prev->next = entry->next;1042}1043if (entry->next) {1044entry->next->prev = entry->prev;1045}10461047if (entry == SDL_EventQ.head) {1048SDL_assert(entry->prev == NULL);1049SDL_EventQ.head = entry->next;1050}1051if (entry == SDL_EventQ.tail) {1052SDL_assert(entry->next == NULL);1053SDL_EventQ.tail = entry->prev;1054}10551056if (entry->event.type == SDL_EVENT_POLL_SENTINEL) {1057SDL_AddAtomicInt(&SDL_sentinel_pending, -1);1058}10591060entry->next = SDL_EventQ.free;1061SDL_EventQ.free = entry;1062SDL_assert(SDL_GetAtomicInt(&SDL_EventQ.count) > 0);1063SDL_AddAtomicInt(&SDL_EventQ.count, -1);1064}10651066static void SDL_SendWakeupEvent(void)1067{1068#ifdef SDL_PLATFORM_ANDROID1069Android_SendLifecycleEvent(SDL_ANDROID_LIFECYCLE_WAKE);1070#endif1071}10721073// Lock the event queue, take a peep at it, and unlock it1074static int SDL_PeepEventsInternal(SDL_Event *events, int numevents, SDL_EventAction action,1075Uint32 minType, Uint32 maxType, bool include_sentinel)1076{1077int i, used, sentinels_expected = 0;10781079// Lock the event queue1080used = 0;10811082SDL_LockMutex(SDL_EventQ.lock);1083{1084// Don't look after we've quit1085if (!SDL_EventQ.active) {1086// We get a few spurious events at shutdown, so don't warn then1087if (action == SDL_GETEVENT) {1088SDL_SetError("The event system has been shut down");1089}1090SDL_UnlockMutex(SDL_EventQ.lock);1091return -1;1092}1093if (action == SDL_ADDEVENT) {1094if (!events) {1095SDL_UnlockMutex(SDL_EventQ.lock);1096SDL_InvalidParamError("events");1097return -1;1098}1099for (i = 0; i < numevents; ++i) {1100used += SDL_AddEvent(&events[i]);1101}1102} else {1103SDL_EventEntry *entry, *next;1104Uint32 type;11051106for (entry = SDL_EventQ.head; entry && (events == NULL || used < numevents); entry = next) {1107next = entry->next;1108type = entry->event.type;1109if (minType <= type && type <= maxType) {1110if (events) {1111SDL_copyp(&events[used], &entry->event);11121113if (action == SDL_GETEVENT) {1114SDL_CutEvent(entry);1115}1116}1117if (type == SDL_EVENT_POLL_SENTINEL) {1118// Special handling for the sentinel event1119if (!include_sentinel) {1120// Skip it, we don't want to include it1121continue;1122}1123if (events == NULL || action != SDL_GETEVENT) {1124++sentinels_expected;1125}1126if (SDL_GetAtomicInt(&SDL_sentinel_pending) > sentinels_expected) {1127// Skip it, there's another one pending1128continue;1129}1130}1131++used;1132}1133}1134}1135}1136SDL_UnlockMutex(SDL_EventQ.lock);11371138if (used > 0 && action == SDL_ADDEVENT) {1139SDL_SendWakeupEvent();1140}11411142return used;1143}1144int SDL_PeepEvents(SDL_Event *events, int numevents, SDL_EventAction action,1145Uint32 minType, Uint32 maxType)1146{1147return SDL_PeepEventsInternal(events, numevents, action, minType, maxType, false);1148}11491150bool SDL_HasEvent(Uint32 type)1151{1152return SDL_HasEvents(type, type);1153}11541155bool SDL_HasEvents(Uint32 minType, Uint32 maxType)1156{1157bool found = false;11581159SDL_LockMutex(SDL_EventQ.lock);1160{1161if (SDL_EventQ.active) {1162for (SDL_EventEntry *entry = SDL_EventQ.head; entry; entry = entry->next) {1163const Uint32 type = entry->event.type;1164if (minType <= type && type <= maxType) {1165found = true;1166break;1167}1168}1169}1170}1171SDL_UnlockMutex(SDL_EventQ.lock);11721173return found;1174}11751176void SDL_FlushEvent(Uint32 type)1177{1178SDL_FlushEvents(type, type);1179}11801181void SDL_FlushEvents(Uint32 minType, Uint32 maxType)1182{1183SDL_EventEntry *entry, *next;1184Uint32 type;11851186// Make sure the events are current1187#if 01188/* Actually, we can't do this since we might be flushing while processing1189a resize event, and calling this might trigger further resize events.1190*/1191SDL_PumpEvents();1192#endif11931194// Lock the event queue1195SDL_LockMutex(SDL_EventQ.lock);1196{1197// Don't look after we've quit1198if (!SDL_EventQ.active) {1199SDL_UnlockMutex(SDL_EventQ.lock);1200return;1201}1202for (entry = SDL_EventQ.head; entry; entry = next) {1203next = entry->next;1204type = entry->event.type;1205if (minType <= type && type <= maxType) {1206SDL_CutEvent(entry);1207}1208}1209}1210SDL_UnlockMutex(SDL_EventQ.lock);1211}12121213typedef enum1214{1215SDL_MAIN_CALLBACK_WAITING,1216SDL_MAIN_CALLBACK_COMPLETE,1217SDL_MAIN_CALLBACK_CANCELED,1218} SDL_MainThreadCallbackState;12191220typedef struct SDL_MainThreadCallbackEntry1221{1222SDL_MainThreadCallback callback;1223void *userdata;1224SDL_AtomicInt state;1225SDL_Semaphore *semaphore;1226struct SDL_MainThreadCallbackEntry *next;1227} SDL_MainThreadCallbackEntry;12281229static SDL_Mutex *SDL_main_callbacks_lock;1230static SDL_MainThreadCallbackEntry *SDL_main_callbacks_head;1231static SDL_MainThreadCallbackEntry *SDL_main_callbacks_tail;12321233static SDL_MainThreadCallbackEntry *SDL_CreateMainThreadCallback(SDL_MainThreadCallback callback, void *userdata, bool wait_complete)1234{1235SDL_MainThreadCallbackEntry *entry = (SDL_MainThreadCallbackEntry *)SDL_malloc(sizeof(*entry));1236if (!entry) {1237return NULL;1238}12391240entry->callback = callback;1241entry->userdata = userdata;1242SDL_SetAtomicInt(&entry->state, SDL_MAIN_CALLBACK_WAITING);1243if (wait_complete) {1244entry->semaphore = SDL_CreateSemaphore(0);1245if (!entry->semaphore) {1246SDL_free(entry);1247return NULL;1248}1249} else {1250entry->semaphore = NULL;1251}1252entry->next = NULL;12531254return entry;1255}12561257static void SDL_DestroyMainThreadCallback(SDL_MainThreadCallbackEntry *entry)1258{1259if (entry->semaphore) {1260SDL_DestroySemaphore(entry->semaphore);1261}1262SDL_free(entry);1263}12641265static void SDL_InitMainThreadCallbacks(void)1266{1267SDL_main_callbacks_lock = SDL_CreateMutex();1268SDL_assert(SDL_main_callbacks_head == NULL &&1269SDL_main_callbacks_tail == NULL);1270}12711272static void SDL_QuitMainThreadCallbacks(void)1273{1274SDL_MainThreadCallbackEntry *entry;12751276SDL_LockMutex(SDL_main_callbacks_lock);1277{1278entry = SDL_main_callbacks_head;1279SDL_main_callbacks_head = NULL;1280SDL_main_callbacks_tail = NULL;1281}1282SDL_UnlockMutex(SDL_main_callbacks_lock);12831284while (entry) {1285SDL_MainThreadCallbackEntry *next = entry->next;12861287if (entry->semaphore) {1288// Let the waiting thread know this is canceled1289SDL_SetAtomicInt(&entry->state, SDL_MAIN_CALLBACK_CANCELED);1290SDL_SignalSemaphore(entry->semaphore);1291} else {1292// Nobody's waiting for this, clean it up1293SDL_DestroyMainThreadCallback(entry);1294}1295entry = next;1296}12971298SDL_DestroyMutex(SDL_main_callbacks_lock);1299SDL_main_callbacks_lock = NULL;1300}13011302static void SDL_RunMainThreadCallbacks(void)1303{1304SDL_MainThreadCallbackEntry *entry;13051306SDL_LockMutex(SDL_main_callbacks_lock);1307{1308entry = SDL_main_callbacks_head;1309SDL_main_callbacks_head = NULL;1310SDL_main_callbacks_tail = NULL;1311}1312SDL_UnlockMutex(SDL_main_callbacks_lock);13131314while (entry) {1315SDL_MainThreadCallbackEntry *next = entry->next;13161317entry->callback(entry->userdata);13181319if (entry->semaphore) {1320// Let the waiting thread know this is done1321SDL_SetAtomicInt(&entry->state, SDL_MAIN_CALLBACK_COMPLETE);1322SDL_SignalSemaphore(entry->semaphore);1323} else {1324// Nobody's waiting for this, clean it up1325SDL_DestroyMainThreadCallback(entry);1326}1327entry = next;1328}1329}13301331bool SDL_RunOnMainThread(SDL_MainThreadCallback callback, void *userdata, bool wait_complete)1332{1333if (SDL_IsMainThread() || !SDL_WasInit(SDL_INIT_EVENTS)) {1334// No need to queue the callback1335callback(userdata);1336return true;1337}13381339SDL_MainThreadCallbackEntry *entry = SDL_CreateMainThreadCallback(callback, userdata, wait_complete);1340if (!entry) {1341return false;1342}13431344SDL_LockMutex(SDL_main_callbacks_lock);1345{1346if (SDL_main_callbacks_tail) {1347SDL_main_callbacks_tail->next = entry;1348SDL_main_callbacks_tail = entry;1349} else {1350SDL_main_callbacks_head = entry;1351SDL_main_callbacks_tail = entry;1352}1353}1354SDL_UnlockMutex(SDL_main_callbacks_lock);13551356// If the main thread is waiting for events, wake it up1357SDL_SendWakeupEvent();13581359if (!wait_complete) {1360// Queued for execution, wait not requested1361return true;1362}13631364SDL_WaitSemaphore(entry->semaphore);13651366switch (SDL_GetAtomicInt(&entry->state)) {1367case SDL_MAIN_CALLBACK_COMPLETE:1368// Execution complete!1369SDL_DestroyMainThreadCallback(entry);1370return true;13711372case SDL_MAIN_CALLBACK_CANCELED:1373// The callback was canceled on the main thread1374SDL_DestroyMainThreadCallback(entry);1375return SDL_SetError("Callback canceled");13761377default:1378// Probably hit a deadlock in the callback1379// We can't destroy the entry as the semaphore will be signaled1380// if it ever comes back, just leak it here.1381return SDL_SetError("Callback timed out");1382}1383}13841385void SDL_PumpEventMaintenance(void)1386{1387#ifndef SDL_AUDIO_DISABLED1388SDL_UpdateAudio();1389#endif13901391#ifndef SDL_CAMERA_DISABLED1392SDL_UpdateCamera();1393#endif13941395#ifndef SDL_SENSOR_DISABLED1396// Check for sensor state change1397if (SDL_update_sensors) {1398SDL_UpdateSensors();1399}1400#endif14011402#ifndef SDL_JOYSTICK_DISABLED1403// Check for joystick state change1404if (SDL_update_joysticks) {1405SDL_UpdateJoysticks();1406}1407#endif14081409//SDL_UpdateTrays();14101411//SDL_SendPendingSignalEvents(); // in case we had a signal handler fire, etc.1412}14131414// Run the system dependent event loops1415static void SDL_PumpEventsInternal(bool push_sentinel)1416{1417// Free any temporary memory from old events1418SDL_FreeTemporaryMemory();14191420// Release any keys held down from last frame1421//SDL_ReleaseAutoReleaseKeys();14221423// Run any pending main thread callbacks1424SDL_RunMainThreadCallbacks();14251426#ifdef SDL_PLATFORM_ANDROID1427// Android event processing is independent of the video subsystem1428Android_PumpEvents(0);1429#endif14301431SDL_PumpEventMaintenance();14321433if (push_sentinel && SDL_EventEnabled(SDL_EVENT_POLL_SENTINEL)) {1434SDL_Event sentinel;14351436// Make sure we don't already have a sentinel in the queue, and add one to the end1437if (SDL_GetAtomicInt(&SDL_sentinel_pending) > 0) {1438SDL_PeepEventsInternal(&sentinel, 1, SDL_GETEVENT, SDL_EVENT_POLL_SENTINEL, SDL_EVENT_POLL_SENTINEL, true);1439}14401441sentinel.type = SDL_EVENT_POLL_SENTINEL;1442sentinel.common.timestamp = 0;1443SDL_PushEvent(&sentinel);1444}1445}14461447void SDL_PumpEvents(void)1448{1449SDL_PumpEventsInternal(false);1450}14511452// Public functions14531454bool SDL_PollEvent(SDL_Event *event)1455{1456return SDL_WaitEventTimeoutNS(event, 0);1457}14581459bool SDL_WaitEvent(SDL_Event *event)1460{1461return SDL_WaitEventTimeoutNS(event, -1);1462}14631464bool SDL_WaitEventTimeout(SDL_Event *event, Sint32 timeoutMS)1465{1466Sint64 timeoutNS;14671468if (timeoutMS > 0) {1469timeoutNS = SDL_MS_TO_NS(timeoutMS);1470} else {1471timeoutNS = timeoutMS;1472}1473return SDL_WaitEventTimeoutNS(event, timeoutNS);1474}14751476bool SDL_WaitEventTimeoutNS(SDL_Event *event, Sint64 timeoutNS)1477{1478Uint64 start, expiration;1479bool include_sentinel = (timeoutNS == 0);1480int result;14811482if (timeoutNS > 0) {1483start = SDL_GetTicksNS();1484expiration = start + timeoutNS;1485} else {1486start = 0;1487expiration = 0;1488}14891490// If there isn't a poll sentinel event pending, pump events and add one1491if (SDL_GetAtomicInt(&SDL_sentinel_pending) == 0) {1492SDL_PumpEventsInternal(true);1493}14941495// First check for existing events1496result = SDL_PeepEventsInternal(event, 1, SDL_GETEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST, include_sentinel);1497if (result < 0) {1498return false;1499}1500if (include_sentinel) {1501if (event) {1502if (event->type == SDL_EVENT_POLL_SENTINEL) {1503// Reached the end of a poll cycle, and not willing to wait1504return false;1505}1506} else {1507// Need to peek the next event to check for sentinel1508SDL_Event dummy;15091510if (SDL_PeepEventsInternal(&dummy, 1, SDL_PEEKEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST, true) &&1511dummy.type == SDL_EVENT_POLL_SENTINEL) {1512SDL_PeepEventsInternal(&dummy, 1, SDL_GETEVENT, SDL_EVENT_POLL_SENTINEL, SDL_EVENT_POLL_SENTINEL, true);1513// Reached the end of a poll cycle, and not willing to wait1514return false;1515}1516}1517}1518if (result == 0) {1519if (timeoutNS == 0) {1520// No events available, and not willing to wait1521return false;1522}1523} else {1524// Has existing events1525return true;1526}1527// We should have completely handled timeoutNS == 0 above1528SDL_assert(timeoutNS != 0);15291530#ifdef SDL_PLATFORM_ANDROID1531for (;;) {1532SDL_PumpEventsInternal(true);15331534if (SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST) > 0) {1535return true;1536}15371538Uint64 delay = -1;1539if (timeoutNS > 0) {1540Uint64 now = SDL_GetTicksNS();1541if (now >= expiration) {1542// Timeout expired and no events1543return false;1544}1545delay = (expiration - now);1546}1547Android_PumpEvents(delay);1548}1549#else1550for (;;) {1551SDL_PumpEventsInternal(true);15521553if (SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST) > 0) {1554return true;1555}15561557Uint64 delay = EVENT_POLL_INTERVAL_NS;1558if (timeoutNS > 0) {1559Uint64 now = SDL_GetTicksNS();1560if (now >= expiration) {1561// Timeout expired and no events1562return false;1563}1564delay = SDL_min((expiration - now), delay);1565}1566SDL_DelayNS(delay);1567}1568#endif // SDL_PLATFORM_ANDROID1569}15701571static bool SDL_CallEventWatchers(SDL_Event *event)1572{1573if (event->common.type == SDL_EVENT_POLL_SENTINEL) {1574return true;1575}15761577return SDL_DispatchEventWatchList(&SDL_event_watchers, event);1578}15791580bool SDL_PushEvent(SDL_Event *event)1581{1582if (!event->common.timestamp) {1583event->common.timestamp = SDL_GetTicksNS();1584}15851586if (!SDL_CallEventWatchers(event)) {1587SDL_ClearError();1588return false;1589}15901591if (SDL_PeepEvents(event, 1, SDL_ADDEVENT, 0, 0) <= 0) {1592return false;1593}15941595return true;1596}15971598void SDL_SetEventFilter(SDL_EventFilter filter, void *userdata)1599{1600SDL_EventEntry *event, *next;1601SDL_LockMutex(SDL_event_watchers.lock);1602{1603// Set filter and discard pending events1604SDL_event_watchers.filter.callback = filter;1605SDL_event_watchers.filter.userdata = userdata;1606if (filter) {1607// Cut all events not accepted by the filter1608SDL_LockMutex(SDL_EventQ.lock);1609{1610for (event = SDL_EventQ.head; event; event = next) {1611next = event->next;1612if (!filter(userdata, &event->event)) {1613SDL_CutEvent(event);1614}1615}1616}1617SDL_UnlockMutex(SDL_EventQ.lock);1618}1619}1620SDL_UnlockMutex(SDL_event_watchers.lock);1621}16221623bool SDL_GetEventFilter(SDL_EventFilter *filter, void **userdata)1624{1625SDL_EventWatcher event_ok;16261627SDL_LockMutex(SDL_event_watchers.lock);1628{1629event_ok = SDL_event_watchers.filter;1630}1631SDL_UnlockMutex(SDL_event_watchers.lock);16321633if (filter) {1634*filter = event_ok.callback;1635}1636if (userdata) {1637*userdata = event_ok.userdata;1638}1639return event_ok.callback ? true : false;1640}16411642bool SDL_AddEventWatch(SDL_EventFilter filter, void *userdata)1643{1644return SDL_AddEventWatchList(&SDL_event_watchers, filter, userdata);1645}16461647void SDL_RemoveEventWatch(SDL_EventFilter filter, void *userdata)1648{1649SDL_RemoveEventWatchList(&SDL_event_watchers, filter, userdata);1650}16511652void SDL_FilterEvents(SDL_EventFilter filter, void *userdata)1653{1654SDL_LockMutex(SDL_EventQ.lock);1655{1656SDL_EventEntry *entry, *next;1657for (entry = SDL_EventQ.head; entry; entry = next) {1658next = entry->next;1659if (!filter(userdata, &entry->event)) {1660SDL_CutEvent(entry);1661}1662}1663}1664SDL_UnlockMutex(SDL_EventQ.lock);1665}16661667void SDL_SetEventEnabled(Uint32 type, bool enabled)1668{1669bool current_state;1670Uint8 hi = ((type >> 8) & 0xff);1671Uint8 lo = (type & 0xff);16721673if (SDL_disabled_events[hi] &&1674(SDL_disabled_events[hi]->bits[lo / 32] & (1U << (lo & 31)))) {1675current_state = false;1676} else {1677current_state = true;1678}16791680if ((enabled != false) != current_state) {1681if (enabled) {1682SDL_assert(SDL_disabled_events[hi] != NULL);1683SDL_disabled_events[hi]->bits[lo / 32] &= ~(1U << (lo & 31));16841685// Gamepad events depend on joystick events1686switch (type) {1687case SDL_EVENT_GAMEPAD_ADDED:1688SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_ADDED, true);1689break;1690case SDL_EVENT_GAMEPAD_REMOVED:1691SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_REMOVED, true);1692break;1693case SDL_EVENT_GAMEPAD_AXIS_MOTION:1694case SDL_EVENT_GAMEPAD_BUTTON_DOWN:1695case SDL_EVENT_GAMEPAD_BUTTON_UP:1696SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_AXIS_MOTION, true);1697SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_HAT_MOTION, true);1698SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_BUTTON_DOWN, true);1699SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_BUTTON_UP, true);1700break;1701case SDL_EVENT_GAMEPAD_UPDATE_COMPLETE:1702SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_UPDATE_COMPLETE, true);1703break;1704default:1705break;1706}1707} else {1708// Disable this event type and discard pending events1709if (!SDL_disabled_events[hi]) {1710SDL_disabled_events[hi] = (SDL_DisabledEventBlock *)SDL_calloc(1, sizeof(SDL_DisabledEventBlock));1711}1712// Out of memory, nothing we can do...1713if (SDL_disabled_events[hi]) {1714SDL_disabled_events[hi]->bits[lo / 32] |= (1U << (lo & 31));1715SDL_FlushEvent(type);1716}1717}17181719/* turn off drag'n'drop support if we've disabled the events.1720This might change some UI details at the OS level. */1721if (type == SDL_EVENT_DROP_FILE || type == SDL_EVENT_DROP_TEXT) {1722//SDL_ToggleDragAndDropSupport();1723}1724}1725}17261727bool SDL_EventEnabled(Uint32 type)1728{1729Uint8 hi = ((type >> 8) & 0xff);1730Uint8 lo = (type & 0xff);17311732if (SDL_disabled_events[hi] &&1733(SDL_disabled_events[hi]->bits[lo / 32] & (1U << (lo & 31)))) {1734return false;1735} else {1736return true;1737}1738}17391740Uint32 SDL_RegisterEvents(int numevents)1741{1742Uint32 event_base = 0;17431744if (numevents > 0) {1745int value = SDL_AddAtomicInt(&SDL_userevents, numevents);1746if (value >= 0 && value <= (SDL_EVENT_LAST - SDL_EVENT_USER)) {1747event_base = (Uint32)(SDL_EVENT_USER + value);1748}1749}1750return event_base;1751}17521753void SDL_SendAppEvent(SDL_EventType eventType)1754{1755if (SDL_EventEnabled(eventType)) {1756SDL_Event event;1757event.type = eventType;1758event.common.timestamp = 0;17591760switch (eventType) {1761case SDL_EVENT_TERMINATING:1762case SDL_EVENT_LOW_MEMORY:1763case SDL_EVENT_WILL_ENTER_BACKGROUND:1764case SDL_EVENT_DID_ENTER_BACKGROUND:1765case SDL_EVENT_WILL_ENTER_FOREGROUND:1766case SDL_EVENT_DID_ENTER_FOREGROUND:1767// We won't actually queue this event, it needs to be handled in this call stack by an event watcher1768if (SDL_EventLoggingVerbosity > 0) {1769SDL_LogEvent(&event);1770}1771SDL_CallEventWatchers(&event);1772break;1773default:1774SDL_PushEvent(&event);1775break;1776}1777}1778}17791780void SDL_SendKeymapChangedEvent(void)1781{1782SDL_SendAppEvent(SDL_EVENT_KEYMAP_CHANGED);1783}17841785void SDL_SendLocaleChangedEvent(void)1786{1787SDL_SendAppEvent(SDL_EVENT_LOCALE_CHANGED);1788}17891790void SDL_SendSystemThemeChangedEvent(void)1791{1792SDL_SendAppEvent(SDL_EVENT_SYSTEM_THEME_CHANGED);1793}17941795bool SDL_InitEvents(void)1796{1797#ifdef SDL_PLATFORM_ANDROID1798Android_InitEvents();1799#endif1800#ifndef SDL_JOYSTICK_DISABLED1801SDL_AddHintCallback(SDL_HINT_AUTO_UPDATE_JOYSTICKS, SDL_AutoUpdateJoysticksChanged, NULL);1802#endif1803#ifndef SDL_SENSOR_DISABLED1804SDL_AddHintCallback(SDL_HINT_AUTO_UPDATE_SENSORS, SDL_AutoUpdateSensorsChanged, NULL);1805#endif1806SDL_AddHintCallback(SDL_HINT_EVENT_LOGGING, SDL_EventLoggingChanged, NULL);1807SDL_AddHintCallback(SDL_HINT_POLL_SENTINEL, SDL_PollSentinelChanged, NULL);1808SDL_InitMainThreadCallbacks();1809if (!SDL_StartEventLoop()) {1810SDL_RemoveHintCallback(SDL_HINT_EVENT_LOGGING, SDL_EventLoggingChanged, NULL);1811return false;1812}18131814//SDL_InitQuit();18151816return true;1817}18181819void SDL_QuitEvents(void)1820{1821//SDL_QuitQuit();1822SDL_StopEventLoop();1823SDL_QuitMainThreadCallbacks();1824SDL_RemoveHintCallback(SDL_HINT_POLL_SENTINEL, SDL_PollSentinelChanged, NULL);1825SDL_RemoveHintCallback(SDL_HINT_EVENT_LOGGING, SDL_EventLoggingChanged, NULL);1826#ifndef SDL_JOYSTICK_DISABLED1827SDL_RemoveHintCallback(SDL_HINT_AUTO_UPDATE_JOYSTICKS, SDL_AutoUpdateJoysticksChanged, NULL);1828#endif1829#ifndef SDL_SENSOR_DISABLED1830SDL_RemoveHintCallback(SDL_HINT_AUTO_UPDATE_SENSORS, SDL_AutoUpdateSensorsChanged, NULL);1831#endif1832#ifdef SDL_PLATFORM_ANDROID1833Android_QuitEvents();1834#endif1835}183618371838