Path: blob/master/thirdparty/sdl/events/SDL_events.c
10278 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);1096return SDL_InvalidParamError("events");1097}1098for (i = 0; i < numevents; ++i) {1099used += SDL_AddEvent(&events[i]);1100}1101} else {1102SDL_EventEntry *entry, *next;1103Uint32 type;11041105for (entry = SDL_EventQ.head; entry && (events == NULL || used < numevents); entry = next) {1106next = entry->next;1107type = entry->event.type;1108if (minType <= type && type <= maxType) {1109if (events) {1110SDL_copyp(&events[used], &entry->event);11111112if (action == SDL_GETEVENT) {1113SDL_CutEvent(entry);1114}1115}1116if (type == SDL_EVENT_POLL_SENTINEL) {1117// Special handling for the sentinel event1118if (!include_sentinel) {1119// Skip it, we don't want to include it1120continue;1121}1122if (events == NULL || action != SDL_GETEVENT) {1123++sentinels_expected;1124}1125if (SDL_GetAtomicInt(&SDL_sentinel_pending) > sentinels_expected) {1126// Skip it, there's another one pending1127continue;1128}1129}1130++used;1131}1132}1133}1134}1135SDL_UnlockMutex(SDL_EventQ.lock);11361137if (used > 0 && action == SDL_ADDEVENT) {1138SDL_SendWakeupEvent();1139}11401141return used;1142}1143int SDL_PeepEvents(SDL_Event *events, int numevents, SDL_EventAction action,1144Uint32 minType, Uint32 maxType)1145{1146return SDL_PeepEventsInternal(events, numevents, action, minType, maxType, false);1147}11481149bool SDL_HasEvent(Uint32 type)1150{1151return SDL_HasEvents(type, type);1152}11531154bool SDL_HasEvents(Uint32 minType, Uint32 maxType)1155{1156bool found = false;11571158SDL_LockMutex(SDL_EventQ.lock);1159{1160if (SDL_EventQ.active) {1161for (SDL_EventEntry *entry = SDL_EventQ.head; entry; entry = entry->next) {1162const Uint32 type = entry->event.type;1163if (minType <= type && type <= maxType) {1164found = true;1165break;1166}1167}1168}1169}1170SDL_UnlockMutex(SDL_EventQ.lock);11711172return found;1173}11741175void SDL_FlushEvent(Uint32 type)1176{1177SDL_FlushEvents(type, type);1178}11791180void SDL_FlushEvents(Uint32 minType, Uint32 maxType)1181{1182SDL_EventEntry *entry, *next;1183Uint32 type;11841185// Make sure the events are current1186#if 01187/* Actually, we can't do this since we might be flushing while processing1188a resize event, and calling this might trigger further resize events.1189*/1190SDL_PumpEvents();1191#endif11921193// Lock the event queue1194SDL_LockMutex(SDL_EventQ.lock);1195{1196// Don't look after we've quit1197if (!SDL_EventQ.active) {1198SDL_UnlockMutex(SDL_EventQ.lock);1199return;1200}1201for (entry = SDL_EventQ.head; entry; entry = next) {1202next = entry->next;1203type = entry->event.type;1204if (minType <= type && type <= maxType) {1205SDL_CutEvent(entry);1206}1207}1208}1209SDL_UnlockMutex(SDL_EventQ.lock);1210}12111212typedef enum1213{1214SDL_MAIN_CALLBACK_WAITING,1215SDL_MAIN_CALLBACK_COMPLETE,1216SDL_MAIN_CALLBACK_CANCELED,1217} SDL_MainThreadCallbackState;12181219typedef struct SDL_MainThreadCallbackEntry1220{1221SDL_MainThreadCallback callback;1222void *userdata;1223SDL_AtomicInt state;1224SDL_Semaphore *semaphore;1225struct SDL_MainThreadCallbackEntry *next;1226} SDL_MainThreadCallbackEntry;12271228static SDL_Mutex *SDL_main_callbacks_lock;1229static SDL_MainThreadCallbackEntry *SDL_main_callbacks_head;1230static SDL_MainThreadCallbackEntry *SDL_main_callbacks_tail;12311232static SDL_MainThreadCallbackEntry *SDL_CreateMainThreadCallback(SDL_MainThreadCallback callback, void *userdata, bool wait_complete)1233{1234SDL_MainThreadCallbackEntry *entry = (SDL_MainThreadCallbackEntry *)SDL_malloc(sizeof(*entry));1235if (!entry) {1236return NULL;1237}12381239entry->callback = callback;1240entry->userdata = userdata;1241SDL_SetAtomicInt(&entry->state, SDL_MAIN_CALLBACK_WAITING);1242if (wait_complete) {1243entry->semaphore = SDL_CreateSemaphore(0);1244if (!entry->semaphore) {1245SDL_free(entry);1246return NULL;1247}1248} else {1249entry->semaphore = NULL;1250}1251entry->next = NULL;12521253return entry;1254}12551256static void SDL_DestroyMainThreadCallback(SDL_MainThreadCallbackEntry *entry)1257{1258if (entry->semaphore) {1259SDL_DestroySemaphore(entry->semaphore);1260}1261SDL_free(entry);1262}12631264static void SDL_InitMainThreadCallbacks(void)1265{1266SDL_main_callbacks_lock = SDL_CreateMutex();1267SDL_assert(SDL_main_callbacks_head == NULL &&1268SDL_main_callbacks_tail == NULL);1269}12701271static void SDL_QuitMainThreadCallbacks(void)1272{1273SDL_MainThreadCallbackEntry *entry;12741275SDL_LockMutex(SDL_main_callbacks_lock);1276{1277entry = SDL_main_callbacks_head;1278SDL_main_callbacks_head = NULL;1279SDL_main_callbacks_tail = NULL;1280}1281SDL_UnlockMutex(SDL_main_callbacks_lock);12821283while (entry) {1284SDL_MainThreadCallbackEntry *next = entry->next;12851286if (entry->semaphore) {1287// Let the waiting thread know this is canceled1288SDL_SetAtomicInt(&entry->state, SDL_MAIN_CALLBACK_CANCELED);1289SDL_SignalSemaphore(entry->semaphore);1290} else {1291// Nobody's waiting for this, clean it up1292SDL_DestroyMainThreadCallback(entry);1293}1294entry = next;1295}12961297SDL_DestroyMutex(SDL_main_callbacks_lock);1298SDL_main_callbacks_lock = NULL;1299}13001301static void SDL_RunMainThreadCallbacks(void)1302{1303SDL_MainThreadCallbackEntry *entry;13041305SDL_LockMutex(SDL_main_callbacks_lock);1306{1307entry = SDL_main_callbacks_head;1308SDL_main_callbacks_head = NULL;1309SDL_main_callbacks_tail = NULL;1310}1311SDL_UnlockMutex(SDL_main_callbacks_lock);13121313while (entry) {1314SDL_MainThreadCallbackEntry *next = entry->next;13151316entry->callback(entry->userdata);13171318if (entry->semaphore) {1319// Let the waiting thread know this is done1320SDL_SetAtomicInt(&entry->state, SDL_MAIN_CALLBACK_COMPLETE);1321SDL_SignalSemaphore(entry->semaphore);1322} else {1323// Nobody's waiting for this, clean it up1324SDL_DestroyMainThreadCallback(entry);1325}1326entry = next;1327}1328}13291330bool SDL_RunOnMainThread(SDL_MainThreadCallback callback, void *userdata, bool wait_complete)1331{1332if (SDL_IsMainThread() || !SDL_WasInit(SDL_INIT_EVENTS)) {1333// No need to queue the callback1334callback(userdata);1335return true;1336}13371338SDL_MainThreadCallbackEntry *entry = SDL_CreateMainThreadCallback(callback, userdata, wait_complete);1339if (!entry) {1340return false;1341}13421343SDL_LockMutex(SDL_main_callbacks_lock);1344{1345if (SDL_main_callbacks_tail) {1346SDL_main_callbacks_tail->next = entry;1347SDL_main_callbacks_tail = entry;1348} else {1349SDL_main_callbacks_head = entry;1350SDL_main_callbacks_tail = entry;1351}1352}1353SDL_UnlockMutex(SDL_main_callbacks_lock);13541355// If the main thread is waiting for events, wake it up1356SDL_SendWakeupEvent();13571358if (!wait_complete) {1359// Queued for execution, wait not requested1360return true;1361}13621363SDL_WaitSemaphore(entry->semaphore);13641365switch (SDL_GetAtomicInt(&entry->state)) {1366case SDL_MAIN_CALLBACK_COMPLETE:1367// Execution complete!1368SDL_DestroyMainThreadCallback(entry);1369return true;13701371case SDL_MAIN_CALLBACK_CANCELED:1372// The callback was canceled on the main thread1373SDL_DestroyMainThreadCallback(entry);1374return SDL_SetError("Callback canceled");13751376default:1377// Probably hit a deadlock in the callback1378// We can't destroy the entry as the semaphore will be signaled1379// if it ever comes back, just leak it here.1380return SDL_SetError("Callback timed out");1381}1382}13831384void SDL_PumpEventMaintenance(void)1385{1386#ifndef SDL_AUDIO_DISABLED1387SDL_UpdateAudio();1388#endif13891390#ifndef SDL_CAMERA_DISABLED1391SDL_UpdateCamera();1392#endif13931394#ifndef SDL_SENSOR_DISABLED1395// Check for sensor state change1396if (SDL_update_sensors) {1397SDL_UpdateSensors();1398}1399#endif14001401#ifndef SDL_JOYSTICK_DISABLED1402// Check for joystick state change1403if (SDL_update_joysticks) {1404SDL_UpdateJoysticks();1405}1406#endif14071408//SDL_UpdateTrays();14091410//SDL_SendPendingSignalEvents(); // in case we had a signal handler fire, etc.1411}14121413// Run the system dependent event loops1414static void SDL_PumpEventsInternal(bool push_sentinel)1415{1416// Free any temporary memory from old events1417SDL_FreeTemporaryMemory();14181419// Release any keys held down from last frame1420//SDL_ReleaseAutoReleaseKeys();14211422// Run any pending main thread callbacks1423SDL_RunMainThreadCallbacks();14241425#ifdef SDL_PLATFORM_ANDROID1426// Android event processing is independent of the video subsystem1427Android_PumpEvents(0);1428#endif14291430SDL_PumpEventMaintenance();14311432if (push_sentinel && SDL_EventEnabled(SDL_EVENT_POLL_SENTINEL)) {1433SDL_Event sentinel;14341435// Make sure we don't already have a sentinel in the queue, and add one to the end1436if (SDL_GetAtomicInt(&SDL_sentinel_pending) > 0) {1437SDL_PeepEventsInternal(&sentinel, 1, SDL_GETEVENT, SDL_EVENT_POLL_SENTINEL, SDL_EVENT_POLL_SENTINEL, true);1438}14391440sentinel.type = SDL_EVENT_POLL_SENTINEL;1441sentinel.common.timestamp = 0;1442SDL_PushEvent(&sentinel);1443}1444}14451446void SDL_PumpEvents(void)1447{1448SDL_PumpEventsInternal(false);1449}14501451// Public functions14521453bool SDL_PollEvent(SDL_Event *event)1454{1455return SDL_WaitEventTimeoutNS(event, 0);1456}14571458bool SDL_WaitEvent(SDL_Event *event)1459{1460return SDL_WaitEventTimeoutNS(event, -1);1461}14621463bool SDL_WaitEventTimeout(SDL_Event *event, Sint32 timeoutMS)1464{1465Sint64 timeoutNS;14661467if (timeoutMS > 0) {1468timeoutNS = SDL_MS_TO_NS(timeoutMS);1469} else {1470timeoutNS = timeoutMS;1471}1472return SDL_WaitEventTimeoutNS(event, timeoutNS);1473}14741475bool SDL_WaitEventTimeoutNS(SDL_Event *event, Sint64 timeoutNS)1476{1477Uint64 start, expiration;1478bool include_sentinel = (timeoutNS == 0);1479int result;14801481if (timeoutNS > 0) {1482start = SDL_GetTicksNS();1483expiration = start + timeoutNS;1484} else {1485start = 0;1486expiration = 0;1487}14881489// If there isn't a poll sentinel event pending, pump events and add one1490if (SDL_GetAtomicInt(&SDL_sentinel_pending) == 0) {1491SDL_PumpEventsInternal(true);1492}14931494// First check for existing events1495result = SDL_PeepEventsInternal(event, 1, SDL_GETEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST, include_sentinel);1496if (result < 0) {1497return false;1498}1499if (include_sentinel) {1500if (event) {1501if (event->type == SDL_EVENT_POLL_SENTINEL) {1502// Reached the end of a poll cycle, and not willing to wait1503return false;1504}1505} else {1506// Need to peek the next event to check for sentinel1507SDL_Event dummy;15081509if (SDL_PeepEventsInternal(&dummy, 1, SDL_PEEKEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST, true) &&1510dummy.type == SDL_EVENT_POLL_SENTINEL) {1511SDL_PeepEventsInternal(&dummy, 1, SDL_GETEVENT, SDL_EVENT_POLL_SENTINEL, SDL_EVENT_POLL_SENTINEL, true);1512// Reached the end of a poll cycle, and not willing to wait1513return false;1514}1515}1516}1517if (result == 0) {1518if (timeoutNS == 0) {1519// No events available, and not willing to wait1520return false;1521}1522} else {1523// Has existing events1524return true;1525}1526// We should have completely handled timeoutNS == 0 above1527SDL_assert(timeoutNS != 0);15281529#ifdef SDL_PLATFORM_ANDROID1530for (;;) {1531if (SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST) > 0) {1532return true;1533}15341535Uint64 delay = -1;1536if (timeoutNS > 0) {1537Uint64 now = SDL_GetTicksNS();1538if (now >= expiration) {1539// Timeout expired and no events1540return false;1541}1542delay = (expiration - now);1543}1544Android_PumpEvents(delay);1545}1546#else1547for (;;) {1548SDL_PumpEventsInternal(true);15491550if (SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_EVENT_FIRST, SDL_EVENT_LAST) > 0) {1551return true;1552}15531554Uint64 delay = EVENT_POLL_INTERVAL_NS;1555if (timeoutNS > 0) {1556Uint64 now = SDL_GetTicksNS();1557if (now >= expiration) {1558// Timeout expired and no events1559return false;1560}1561delay = SDL_min((expiration - now), delay);1562}1563SDL_DelayNS(delay);1564}1565#endif // SDL_PLATFORM_ANDROID1566}15671568static bool SDL_CallEventWatchers(SDL_Event *event)1569{1570if (event->common.type == SDL_EVENT_POLL_SENTINEL) {1571return true;1572}15731574return SDL_DispatchEventWatchList(&SDL_event_watchers, event);1575}15761577bool SDL_PushEvent(SDL_Event *event)1578{1579if (!event->common.timestamp) {1580event->common.timestamp = SDL_GetTicksNS();1581}15821583if (!SDL_CallEventWatchers(event)) {1584SDL_ClearError();1585return false;1586}15871588if (SDL_PeepEvents(event, 1, SDL_ADDEVENT, 0, 0) <= 0) {1589return false;1590}15911592return true;1593}15941595void SDL_SetEventFilter(SDL_EventFilter filter, void *userdata)1596{1597SDL_EventEntry *event, *next;1598SDL_LockMutex(SDL_event_watchers.lock);1599{1600// Set filter and discard pending events1601SDL_event_watchers.filter.callback = filter;1602SDL_event_watchers.filter.userdata = userdata;1603if (filter) {1604// Cut all events not accepted by the filter1605SDL_LockMutex(SDL_EventQ.lock);1606{1607for (event = SDL_EventQ.head; event; event = next) {1608next = event->next;1609if (!filter(userdata, &event->event)) {1610SDL_CutEvent(event);1611}1612}1613}1614SDL_UnlockMutex(SDL_EventQ.lock);1615}1616}1617SDL_UnlockMutex(SDL_event_watchers.lock);1618}16191620bool SDL_GetEventFilter(SDL_EventFilter *filter, void **userdata)1621{1622SDL_EventWatcher event_ok;16231624SDL_LockMutex(SDL_event_watchers.lock);1625{1626event_ok = SDL_event_watchers.filter;1627}1628SDL_UnlockMutex(SDL_event_watchers.lock);16291630if (filter) {1631*filter = event_ok.callback;1632}1633if (userdata) {1634*userdata = event_ok.userdata;1635}1636return event_ok.callback ? true : false;1637}16381639bool SDL_AddEventWatch(SDL_EventFilter filter, void *userdata)1640{1641return SDL_AddEventWatchList(&SDL_event_watchers, filter, userdata);1642}16431644void SDL_RemoveEventWatch(SDL_EventFilter filter, void *userdata)1645{1646SDL_RemoveEventWatchList(&SDL_event_watchers, filter, userdata);1647}16481649void SDL_FilterEvents(SDL_EventFilter filter, void *userdata)1650{1651SDL_LockMutex(SDL_EventQ.lock);1652{1653SDL_EventEntry *entry, *next;1654for (entry = SDL_EventQ.head; entry; entry = next) {1655next = entry->next;1656if (!filter(userdata, &entry->event)) {1657SDL_CutEvent(entry);1658}1659}1660}1661SDL_UnlockMutex(SDL_EventQ.lock);1662}16631664void SDL_SetEventEnabled(Uint32 type, bool enabled)1665{1666bool current_state;1667Uint8 hi = ((type >> 8) & 0xff);1668Uint8 lo = (type & 0xff);16691670if (SDL_disabled_events[hi] &&1671(SDL_disabled_events[hi]->bits[lo / 32] & (1U << (lo & 31)))) {1672current_state = false;1673} else {1674current_state = true;1675}16761677if ((enabled != false) != current_state) {1678if (enabled) {1679SDL_assert(SDL_disabled_events[hi] != NULL);1680SDL_disabled_events[hi]->bits[lo / 32] &= ~(1U << (lo & 31));16811682// Gamepad events depend on joystick events1683switch (type) {1684case SDL_EVENT_GAMEPAD_ADDED:1685SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_ADDED, true);1686break;1687case SDL_EVENT_GAMEPAD_REMOVED:1688SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_REMOVED, true);1689break;1690case SDL_EVENT_GAMEPAD_AXIS_MOTION:1691case SDL_EVENT_GAMEPAD_BUTTON_DOWN:1692case SDL_EVENT_GAMEPAD_BUTTON_UP:1693SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_AXIS_MOTION, true);1694SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_HAT_MOTION, true);1695SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_BUTTON_DOWN, true);1696SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_BUTTON_UP, true);1697break;1698case SDL_EVENT_GAMEPAD_UPDATE_COMPLETE:1699SDL_SetEventEnabled(SDL_EVENT_JOYSTICK_UPDATE_COMPLETE, true);1700break;1701default:1702break;1703}1704} else {1705// Disable this event type and discard pending events1706if (!SDL_disabled_events[hi]) {1707SDL_disabled_events[hi] = (SDL_DisabledEventBlock *)SDL_calloc(1, sizeof(SDL_DisabledEventBlock));1708}1709// Out of memory, nothing we can do...1710if (SDL_disabled_events[hi]) {1711SDL_disabled_events[hi]->bits[lo / 32] |= (1U << (lo & 31));1712SDL_FlushEvent(type);1713}1714}17151716/* turn off drag'n'drop support if we've disabled the events.1717This might change some UI details at the OS level. */1718if (type == SDL_EVENT_DROP_FILE || type == SDL_EVENT_DROP_TEXT) {1719//SDL_ToggleDragAndDropSupport();1720}1721}1722}17231724bool SDL_EventEnabled(Uint32 type)1725{1726Uint8 hi = ((type >> 8) & 0xff);1727Uint8 lo = (type & 0xff);17281729if (SDL_disabled_events[hi] &&1730(SDL_disabled_events[hi]->bits[lo / 32] & (1U << (lo & 31)))) {1731return false;1732} else {1733return true;1734}1735}17361737Uint32 SDL_RegisterEvents(int numevents)1738{1739Uint32 event_base = 0;17401741if (numevents > 0) {1742int value = SDL_AddAtomicInt(&SDL_userevents, numevents);1743if (value >= 0 && value <= (SDL_EVENT_LAST - SDL_EVENT_USER)) {1744event_base = (Uint32)(SDL_EVENT_USER + value);1745}1746}1747return event_base;1748}17491750void SDL_SendAppEvent(SDL_EventType eventType)1751{1752if (SDL_EventEnabled(eventType)) {1753SDL_Event event;1754event.type = eventType;1755event.common.timestamp = 0;17561757switch (eventType) {1758case SDL_EVENT_TERMINATING:1759case SDL_EVENT_LOW_MEMORY:1760case SDL_EVENT_WILL_ENTER_BACKGROUND:1761case SDL_EVENT_DID_ENTER_BACKGROUND:1762case SDL_EVENT_WILL_ENTER_FOREGROUND:1763case SDL_EVENT_DID_ENTER_FOREGROUND:1764// We won't actually queue this event, it needs to be handled in this call stack by an event watcher1765if (SDL_EventLoggingVerbosity > 0) {1766SDL_LogEvent(&event);1767}1768SDL_CallEventWatchers(&event);1769break;1770default:1771SDL_PushEvent(&event);1772break;1773}1774}1775}17761777void SDL_SendKeymapChangedEvent(void)1778{1779SDL_SendAppEvent(SDL_EVENT_KEYMAP_CHANGED);1780}17811782void SDL_SendLocaleChangedEvent(void)1783{1784SDL_SendAppEvent(SDL_EVENT_LOCALE_CHANGED);1785}17861787void SDL_SendSystemThemeChangedEvent(void)1788{1789SDL_SendAppEvent(SDL_EVENT_SYSTEM_THEME_CHANGED);1790}17911792bool SDL_InitEvents(void)1793{1794#ifdef SDL_PLATFORM_ANDROID1795Android_InitEvents();1796#endif1797#ifndef SDL_JOYSTICK_DISABLED1798SDL_AddHintCallback(SDL_HINT_AUTO_UPDATE_JOYSTICKS, SDL_AutoUpdateJoysticksChanged, NULL);1799#endif1800#ifndef SDL_SENSOR_DISABLED1801SDL_AddHintCallback(SDL_HINT_AUTO_UPDATE_SENSORS, SDL_AutoUpdateSensorsChanged, NULL);1802#endif1803SDL_AddHintCallback(SDL_HINT_EVENT_LOGGING, SDL_EventLoggingChanged, NULL);1804SDL_AddHintCallback(SDL_HINT_POLL_SENTINEL, SDL_PollSentinelChanged, NULL);1805SDL_InitMainThreadCallbacks();1806if (!SDL_StartEventLoop()) {1807SDL_RemoveHintCallback(SDL_HINT_EVENT_LOGGING, SDL_EventLoggingChanged, NULL);1808return false;1809}18101811//SDL_InitQuit();18121813return true;1814}18151816void SDL_QuitEvents(void)1817{1818//SDL_QuitQuit();1819SDL_StopEventLoop();1820SDL_QuitMainThreadCallbacks();1821SDL_RemoveHintCallback(SDL_HINT_POLL_SENTINEL, SDL_PollSentinelChanged, NULL);1822SDL_RemoveHintCallback(SDL_HINT_EVENT_LOGGING, SDL_EventLoggingChanged, NULL);1823#ifndef SDL_JOYSTICK_DISABLED1824SDL_RemoveHintCallback(SDL_HINT_AUTO_UPDATE_JOYSTICKS, SDL_AutoUpdateJoysticksChanged, NULL);1825#endif1826#ifndef SDL_SENSOR_DISABLED1827SDL_RemoveHintCallback(SDL_HINT_AUTO_UPDATE_SENSORS, SDL_AutoUpdateSensorsChanged, NULL);1828#endif1829#ifdef SDL_PLATFORM_ANDROID1830Android_QuitEvents();1831#endif1832}183318341835