all repos — mgba @ 3d402f6afda8cb79e84110146d60843cb046708a

mGBA Game Boy Advance Emulator

src/platform/sdl/sdl-events.c (view raw)

  1/* Copyright (c) 2013-2014 Jeffrey Pfau
  2 *
  3 * This Source Code Form is subject to the terms of the Mozilla Public
  4 * License, v. 2.0. If a copy of the MPL was not distributed with this
  5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6#include "sdl-events.h"
  7
  8#include "core/input.h"
  9#include "core/thread.h"
 10#include "debugger/debugger.h"
 11#include "gba/input.h"
 12#include "gba/io.h"
 13#include "gba/rr/rr.h"
 14#include "gba/serialize.h"
 15#include "gba/supervisor/thread.h"
 16#include "gba/video.h"
 17#include "gba/renderers/video-software.h"
 18#include "util/configuration.h"
 19#include "util/formatting.h"
 20#include "util/vfs.h"
 21
 22#if SDL_VERSION_ATLEAST(2, 0, 0) && defined(__APPLE__)
 23#define GUI_MOD KMOD_GUI
 24#else
 25#define GUI_MOD KMOD_CTRL
 26#endif
 27
 28#define GYRO_STEPS 100
 29#define RUMBLE_PWM 20
 30
 31DEFINE_VECTOR(SDL_JoystickList, struct SDL_JoystickCombo);
 32
 33#if SDL_VERSION_ATLEAST(2, 0, 0)
 34static void _mSDLSetRumble(struct mRumble* rumble, int enable);
 35#endif
 36static int32_t _mSDLReadTiltX(struct mRotationSource* rumble);
 37static int32_t _mSDLReadTiltY(struct mRotationSource* rumble);
 38static int32_t _mSDLReadGyroZ(struct mRotationSource* rumble);
 39static void _mSDLRotationSample(struct mRotationSource* source);
 40
 41bool mSDLInitEvents(struct mSDLEvents* context) {
 42#if SDL_VERSION_ATLEAST(2, 0, 4)
 43	SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "1");
 44#endif
 45	if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) {
 46		GBALog(0, GBA_LOG_ERROR, "SDL joystick initialization failed: %s", SDL_GetError());
 47	}
 48
 49#if SDL_VERSION_ATLEAST(2, 0, 0)
 50	SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
 51	if (SDL_InitSubSystem(SDL_INIT_HAPTIC) < 0) {
 52		GBALog(0, GBA_LOG_ERROR, "SDL haptic initialization failed: %s", SDL_GetError());
 53	}
 54	if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
 55		GBALog(0, GBA_LOG_ERROR, "SDL video initialization failed: %s", SDL_GetError());
 56	}
 57#endif
 58
 59	SDL_JoystickEventState(SDL_ENABLE);
 60	int nJoysticks = SDL_NumJoysticks();
 61	SDL_JoystickListInit(&context->joysticks, nJoysticks);
 62	if (nJoysticks > 0) {
 63		mSDLUpdateJoysticks(context);
 64	}
 65
 66	context->playersAttached = 0;
 67
 68	size_t i;
 69	for (i = 0; i < MAX_PLAYERS; ++i) {
 70		context->preferredJoysticks[i] = 0;
 71	}
 72
 73#if !SDL_VERSION_ATLEAST(2, 0, 0)
 74	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
 75#else
 76	context->screensaverSuspendDepth = 0;
 77#endif
 78	return true;
 79}
 80
 81void mSDLDeinitEvents(struct mSDLEvents* context) {
 82	size_t i;
 83	for (i = 0; i < SDL_JoystickListSize(&context->joysticks); ++i) {
 84		struct SDL_JoystickCombo* joystick = SDL_JoystickListGetPointer(&context->joysticks, i);
 85#if SDL_VERSION_ATLEAST(2, 0, 0)
 86		SDL_HapticClose(joystick->haptic);
 87#endif
 88		SDL_JoystickClose(joystick->joystick);
 89	}
 90	SDL_JoystickListDeinit(&context->joysticks);
 91	SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
 92}
 93
 94void mSDLEventsLoadConfig(struct mSDLEvents* context, const struct Configuration* config) {
 95	context->preferredJoysticks[0] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 0);
 96	context->preferredJoysticks[1] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 1);
 97	context->preferredJoysticks[2] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 2);
 98	context->preferredJoysticks[3] = mInputGetPreferredDevice(config, "gba", SDL_BINDING_BUTTON, 3);
 99}
100
101void mSDLInitBindingsGBA(struct mInputMap* inputMap) {
102#ifdef BUILD_PANDORA
103	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_PAGEDOWN, GBA_KEY_A);
104	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_END, GBA_KEY_B);
105	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RSHIFT, GBA_KEY_L);
106	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RCTRL, GBA_KEY_R);
107	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LALT, GBA_KEY_START);
108	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LCTRL, GBA_KEY_SELECT);
109	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_UP, GBA_KEY_UP);
110	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_DOWN, GBA_KEY_DOWN);
111	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LEFT, GBA_KEY_LEFT);
112	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RIGHT, GBA_KEY_RIGHT);
113#elif SDL_VERSION_ATLEAST(2, 0, 0)
114	mInputBindKey(inputMap, SDL_BINDING_KEY, SDL_SCANCODE_X, GBA_KEY_A);
115	mInputBindKey(inputMap, SDL_BINDING_KEY, SDL_SCANCODE_Z, GBA_KEY_B);
116	mInputBindKey(inputMap, SDL_BINDING_KEY, SDL_SCANCODE_A, GBA_KEY_L);
117	mInputBindKey(inputMap, SDL_BINDING_KEY, SDL_SCANCODE_S, GBA_KEY_R);
118	mInputBindKey(inputMap, SDL_BINDING_KEY, SDL_SCANCODE_RETURN, GBA_KEY_START);
119	mInputBindKey(inputMap, SDL_BINDING_KEY, SDL_SCANCODE_BACKSPACE, GBA_KEY_SELECT);
120	mInputBindKey(inputMap, SDL_BINDING_KEY, SDL_SCANCODE_UP, GBA_KEY_UP);
121	mInputBindKey(inputMap, SDL_BINDING_KEY, SDL_SCANCODE_DOWN, GBA_KEY_DOWN);
122	mInputBindKey(inputMap, SDL_BINDING_KEY, SDL_SCANCODE_LEFT, GBA_KEY_LEFT);
123	mInputBindKey(inputMap, SDL_BINDING_KEY, SDL_SCANCODE_RIGHT, GBA_KEY_RIGHT);
124#else
125	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_x, GBA_KEY_A);
126	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_z, GBA_KEY_B);
127	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_a, GBA_KEY_L);
128	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_s, GBA_KEY_R);
129	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RETURN, GBA_KEY_START);
130	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_BACKSPACE, GBA_KEY_SELECT);
131	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_UP, GBA_KEY_UP);
132	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_DOWN, GBA_KEY_DOWN);
133	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_LEFT, GBA_KEY_LEFT);
134	mInputBindKey(inputMap, SDL_BINDING_KEY, SDLK_RIGHT, GBA_KEY_RIGHT);
135#endif
136
137	mInputBindKey(inputMap, SDL_BINDING_BUTTON, 13, GBA_KEY_A);
138	mInputBindKey(inputMap, SDL_BINDING_BUTTON, 14, GBA_KEY_B);
139	mInputBindKey(inputMap, SDL_BINDING_BUTTON, 10, GBA_KEY_L);
140	mInputBindKey(inputMap, SDL_BINDING_BUTTON, 11, GBA_KEY_R);
141	mInputBindKey(inputMap, SDL_BINDING_BUTTON, 3, GBA_KEY_START);
142	mInputBindKey(inputMap, SDL_BINDING_BUTTON, 0, GBA_KEY_SELECT);
143	mInputBindKey(inputMap, SDL_BINDING_BUTTON, 4, GBA_KEY_UP);
144	mInputBindKey(inputMap, SDL_BINDING_BUTTON, 6, GBA_KEY_DOWN);
145	mInputBindKey(inputMap, SDL_BINDING_BUTTON, 7, GBA_KEY_LEFT);
146	mInputBindKey(inputMap, SDL_BINDING_BUTTON, 5, GBA_KEY_RIGHT);
147
148	struct mInputAxis description = { GBA_KEY_RIGHT, GBA_KEY_LEFT, 0x4000, -0x4000 };
149	mInputBindAxis(inputMap, SDL_BINDING_BUTTON, 0, &description);
150	description = (struct mInputAxis) { GBA_KEY_DOWN, GBA_KEY_UP, 0x4000, -0x4000 };
151	mInputBindAxis(inputMap, SDL_BINDING_BUTTON, 1, &description);
152}
153
154bool mSDLAttachPlayer(struct mSDLEvents* events, struct mSDLPlayer* player) {
155	player->joystick = 0;
156
157	if (events->playersAttached >= MAX_PLAYERS) {
158		return false;
159	}
160
161#if SDL_VERSION_ATLEAST(2, 0, 0)
162	player->rumble.d.setRumble = _mSDLSetRumble;
163	CircleBufferInit(&player->rumble.history, RUMBLE_PWM);
164	player->rumble.level = 0;
165	player->rumble.p = player;
166#endif
167
168	player->rotation.d.readTiltX = _mSDLReadTiltX;
169	player->rotation.d.readTiltY = _mSDLReadTiltY;
170	player->rotation.d.readGyroZ = _mSDLReadGyroZ;
171	player->rotation.d.sample = _mSDLRotationSample;
172	player->rotation.axisX = 2;
173	player->rotation.axisY = 3;
174	player->rotation.gyroSensitivity = 2.2e9f;
175	player->rotation.gyroX = 0;
176	player->rotation.gyroY = 1;
177	player->rotation.zDelta = 0;
178	CircleBufferInit(&player->rotation.zHistory, sizeof(float) * GYRO_STEPS);
179	player->rotation.p = player;
180
181	player->playerId = events->playersAttached;
182	events->players[player->playerId] = player;
183	size_t firstUnclaimed = SIZE_MAX;
184	size_t index = SIZE_MAX;
185
186	size_t i;
187	for (i = 0; i < SDL_JoystickListSize(&events->joysticks); ++i) {
188		bool claimed = false;
189
190		int p;
191		for (p = 0; p < events->playersAttached; ++p) {
192			if (events->players[p]->joystick == SDL_JoystickListGetPointer(&events->joysticks, i)) {
193				claimed = true;
194				break;
195			}
196		}
197		if (claimed) {
198			continue;
199		}
200
201		if (firstUnclaimed == SIZE_MAX) {
202			firstUnclaimed = i;
203		}
204
205		const char* joystickName;
206#if SDL_VERSION_ATLEAST(2, 0, 0)
207		joystickName = SDL_JoystickName(SDL_JoystickListGetPointer(&events->joysticks, i)->joystick);
208#else
209		joystickName = SDL_JoystickName(SDL_JoystickIndex(SDL_JoystickListGetPointer(&events->joysticks, i)->joystick));
210#endif
211		if (events->preferredJoysticks[player->playerId] && strcmp(events->preferredJoysticks[player->playerId], joystickName) == 0) {
212			index = i;
213			break;
214		}
215	}
216
217	if (index == SIZE_MAX && firstUnclaimed != SIZE_MAX) {
218		index = firstUnclaimed;
219	}
220
221	if (index != SIZE_MAX) {
222		player->joystick = SDL_JoystickListGetPointer(&events->joysticks, index);
223
224#if SDL_VERSION_ATLEAST(2, 0, 0)
225		if (player->joystick->haptic) {
226			SDL_HapticRumbleInit(player->joystick->haptic);
227		}
228#endif
229	}
230
231	++events->playersAttached;
232	return true;
233}
234
235void mSDLDetachPlayer(struct mSDLEvents* events, struct mSDLPlayer* player) {
236	if (player != events->players[player->playerId]) {
237		return;
238	}
239	int i;
240	for (i = player->playerId; i < events->playersAttached; ++i) {
241		if (i + 1 < MAX_PLAYERS) {
242			events->players[i] = events->players[i + 1];
243		}
244		if (i < events->playersAttached - 1) {
245			events->players[i]->playerId = i;
246		}
247	}
248	--events->playersAttached;
249	CircleBufferDeinit(&player->rotation.zHistory);
250}
251
252void mSDLPlayerLoadConfig(struct mSDLPlayer* context, const struct Configuration* config) {
253	mInputMapLoad(context->bindings, SDL_BINDING_KEY, config);
254	if (context->joystick) {
255		mInputMapLoad(context->bindings, SDL_BINDING_BUTTON, config);
256#if SDL_VERSION_ATLEAST(2, 0, 0)
257		const char* name = SDL_JoystickName(context->joystick->joystick);
258#else
259		const char* name = SDL_JoystickName(SDL_JoystickIndex(context->joystick->joystick));
260#endif
261		mInputProfileLoad(context->bindings, SDL_BINDING_BUTTON, config, name);
262
263		const char* value;
264		char* end;
265		int numAxes = SDL_JoystickNumAxes(context->joystick->joystick);
266		int axis;
267		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisX", name);
268		if (value) {
269			axis = strtol(value, &end, 0);
270			if (axis >= 0 && axis < numAxes && end && !*end) {
271				context->rotation.axisX = axis;
272			}
273		}
274		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisY", name);
275		if (value) {
276			axis = strtol(value, &end, 0);
277			if (axis >= 0 && axis < numAxes && end && !*end) {
278				context->rotation.axisY = axis;
279			}
280		}
281		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisX", name);
282		if (value) {
283			axis = strtol(value, &end, 0);
284			if (axis >= 0 && axis < numAxes && end && !*end) {
285				context->rotation.gyroX = axis;
286			}
287		}
288		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisY", name);
289		if (value) {
290			axis = strtol(value, &end, 0);
291			if (axis >= 0 && axis < numAxes && end && !*end) {
292				context->rotation.gyroY = axis;
293			}
294		}
295		value = mInputGetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroSensitivity", name);
296		if (value) {
297			float sensitivity = strtof_u(value, &end);
298			if (end && !*end) {
299				context->rotation.gyroSensitivity = sensitivity;
300			}
301		}
302	}
303}
304
305void mSDLPlayerSaveConfig(const struct mSDLPlayer* context, struct Configuration* config) {
306	if (context->joystick) {
307#if SDL_VERSION_ATLEAST(2, 0, 0)
308		const char* name = SDL_JoystickName(context->joystick->joystick);
309#else
310		const char* name = SDL_JoystickName(SDL_JoystickIndex(context->joystick->joystick));
311#endif
312		char value[12];
313		snprintf(value, sizeof(value), "%i", context->rotation.axisX);
314		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisX", value, name);
315		snprintf(value, sizeof(value), "%i", context->rotation.axisY);
316		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "tiltAxisY", value, name);
317		snprintf(value, sizeof(value), "%i", context->rotation.gyroX);
318		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisX", value, name);
319		snprintf(value, sizeof(value), "%i", context->rotation.gyroY);
320		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroAxisY", value, name);
321		snprintf(value, sizeof(value), "%g", context->rotation.gyroSensitivity);
322		mInputSetCustomValue(config, "gba", SDL_BINDING_BUTTON, "gyroSensitivity", value, name);
323	}
324}
325
326void mSDLPlayerChangeJoystick(struct mSDLEvents* events, struct mSDLPlayer* player, size_t index) {
327	if (player->playerId >= MAX_PLAYERS || index >= SDL_JoystickListSize(&events->joysticks)) {
328		return;
329	}
330	player->joystick = SDL_JoystickListGetPointer(&events->joysticks, index);
331}
332
333void mSDLUpdateJoysticks(struct mSDLEvents* events) {
334	// Pump SDL joystick events without eating the rest of the events
335	SDL_JoystickUpdate();
336#if SDL_VERSION_ATLEAST(2, 0, 0)
337	SDL_Event event;
338	while (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_JOYDEVICEADDED, SDL_JOYDEVICEREMOVED) > 0) {
339		if (event.type == SDL_JOYDEVICEADDED) {
340			struct SDL_JoystickCombo* joystick = SDL_JoystickListAppend(&events->joysticks);
341			joystick->joystick = SDL_JoystickOpen(event.jdevice.which);
342			joystick->id = SDL_JoystickInstanceID(joystick->joystick);
343			joystick->index = SDL_JoystickListSize(&events->joysticks) - 1;
344#if SDL_VERSION_ATLEAST(2, 0, 0)
345			joystick->haptic = SDL_HapticOpenFromJoystick(joystick->joystick);
346#endif
347		} else if (event.type == SDL_JOYDEVICEREMOVED) {
348			SDL_JoystickID ids[MAX_PLAYERS];
349			size_t i;
350			for (i = 0; (int) i < events->playersAttached; ++i) {
351				if (events->players[i]->joystick) {
352					ids[i] = events->players[i]->joystick->id;
353					events->players[i]->joystick = 0;
354				} else {
355					ids[i] = -1;
356				}
357			}
358			for (i = 0; i < SDL_JoystickListSize(&events->joysticks);) {
359				struct SDL_JoystickCombo* joystick = SDL_JoystickListGetPointer(&events->joysticks, i);
360				if (joystick->id == event.jdevice.which) {
361					SDL_JoystickListShift(&events->joysticks, i, 1);
362					continue;
363				}
364				SDL_JoystickListGetPointer(&events->joysticks, i)->index = i;
365				int p;
366				for (p = 0; p < events->playersAttached; ++p) {
367					if (joystick->id == ids[p]) {
368						events->players[p]->joystick = SDL_JoystickListGetPointer(&events->joysticks, i);
369					}
370				}
371				++i;
372			}
373		}
374	}
375#endif
376}
377
378static void _pauseAfterFrame(struct mCoreThread* context) {
379	context->frameCallback = 0;
380	mCoreThreadPauseFromThread(context);
381}
382
383static void _mSDLHandleKeypressGBA(struct GBAThread* context, struct mSDLPlayer* sdlContext, const struct SDL_KeyboardEvent* event) {
384	enum GBAKey key = GBA_KEY_NONE;
385	if (!event->keysym.mod) {
386#if !defined(BUILD_PANDORA) && SDL_VERSION_ATLEAST(2, 0, 0)
387		key = mInputMapKey(sdlContext->bindings, SDL_BINDING_KEY, event->keysym.scancode);
388#else
389		key = mInputMapKey(sdlContext->bindings, SDL_BINDING_KEY, event->keysym.sym);
390#endif
391	}
392	if (key != GBA_KEY_NONE) {
393		if (event->type == SDL_KEYDOWN) {
394			context->activeKeys |= 1 << key;
395		} else {
396			context->activeKeys &= ~(1 << key);
397		}
398		return;
399	}
400	if (event->keysym.sym == SDLK_TAB) {
401		context->sync.audioWait = event->type != SDL_KEYDOWN;
402		return;
403	}
404	if (event->type == SDL_KEYDOWN) {
405		switch (event->keysym.sym) {
406		case SDLK_F11:
407			if (context->debugger) {
408				ARMDebuggerEnter(context->debugger, DEBUGGER_ENTER_MANUAL, 0);
409			}
410			return;
411#ifdef USE_PNG
412		case SDLK_F12:
413			GBAThreadInterrupt(context);
414			GBAThreadTakeScreenshot(context);
415			GBAThreadContinue(context);
416			return;
417#endif
418		case SDLK_BACKQUOTE:
419			GBAThreadInterrupt(context);
420			GBARewind(context, 10);
421			GBAThreadContinue(context);
422			return;
423#ifdef BUILD_PANDORA
424		case SDLK_ESCAPE:
425			GBAThreadEnd(context);
426			return;
427#endif
428		default:
429			if ((event->keysym.mod & GUI_MOD) && (event->keysym.mod & GUI_MOD) == event->keysym.mod) {
430				switch (event->keysym.sym) {
431#if SDL_VERSION_ATLEAST(2, 0, 0)
432				case SDLK_f:
433					SDL_SetWindowFullscreen(sdlContext->window, sdlContext->fullscreen ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP);
434					sdlContext->fullscreen = !sdlContext->fullscreen;
435					sdlContext->windowUpdated = 1;
436					break;
437#endif
438				case SDLK_p:
439					GBAThreadTogglePause(context);
440					break;
441				case SDLK_r:
442					GBAThreadReset(context);
443					break;
444				default:
445					break;
446				}
447			}
448			if (event->keysym.mod & KMOD_SHIFT) {
449				switch (event->keysym.sym) {
450				case SDLK_F1:
451				case SDLK_F2:
452				case SDLK_F3:
453				case SDLK_F4:
454				case SDLK_F5:
455				case SDLK_F6:
456				case SDLK_F7:
457				case SDLK_F8:
458				case SDLK_F9:
459					GBAThreadInterrupt(context);
460					GBASaveState(context, context->dirs.state, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SCREENSHOT);
461					GBAThreadContinue(context);
462					break;
463				default:
464					break;
465				}
466			} else {
467				switch (event->keysym.sym) {
468				case SDLK_F1:
469				case SDLK_F2:
470				case SDLK_F3:
471				case SDLK_F4:
472				case SDLK_F5:
473				case SDLK_F6:
474				case SDLK_F7:
475				case SDLK_F8:
476				case SDLK_F9:
477					GBAThreadInterrupt(context);
478					GBALoadState(context, context->dirs.state, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SCREENSHOT);
479					GBAThreadContinue(context);
480					break;
481				default:
482					break;
483				}
484			}
485			return;
486		}
487	}
488}
489
490static void _mSDLHandleJoyButtonGBA(struct GBAThread* context, struct mSDLPlayer* sdlContext, const struct SDL_JoyButtonEvent* event) {
491	enum GBAKey key = 0;
492	key = mInputMapKey(sdlContext->bindings, SDL_BINDING_BUTTON, event->button);
493	if (key == GBA_KEY_NONE) {
494		return;
495	}
496
497	if (event->type == SDL_JOYBUTTONDOWN) {
498		context->activeKeys |= 1 << key;
499	} else {
500		context->activeKeys &= ~(1 << key);
501	}
502}
503
504static void _mSDLHandleJoyHatGBA(struct GBAThread* context, const struct SDL_JoyHatEvent* event) {
505	enum GBAKey key = 0;
506
507	if (event->value & SDL_HAT_UP) {
508		key |= 1 << GBA_KEY_UP;
509	}
510	if (event->value & SDL_HAT_LEFT) {
511		key |= 1 << GBA_KEY_LEFT;
512	}
513	if (event->value & SDL_HAT_DOWN) {
514		key |= 1 << GBA_KEY_DOWN;
515	}
516	if (event->value & SDL_HAT_RIGHT) {
517		key |= 1 << GBA_KEY_RIGHT;
518	}
519
520	context->activeKeys &= ~((1 << GBA_KEY_UP) | (1 << GBA_KEY_LEFT) | (1 << GBA_KEY_DOWN) | (1 << GBA_KEY_RIGHT));
521	context->activeKeys |= key;
522}
523
524static void _mSDLHandleJoyAxisGBA(struct GBAThread* context, struct mSDLPlayer* sdlContext, const struct SDL_JoyAxisEvent* event) {
525	int keys = context->activeKeys;
526
527	keys = mInputClearAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, keys);
528	enum GBAKey key = mInputMapAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, event->value);
529	if (key != -1) {
530		keys |= 1 << key;
531	}
532
533	context->activeKeys = keys;
534}
535
536static void _mSDLHandleKeypress(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const struct SDL_KeyboardEvent* event) {
537	int key = -1;
538	if (!event->keysym.mod) {
539#if !defined(BUILD_PANDORA) && SDL_VERSION_ATLEAST(2, 0, 0)
540		key = mInputMapKey(sdlContext->bindings, SDL_BINDING_KEY, event->keysym.scancode);
541#else
542		key = mInputMapKey(sdlContext->bindings, SDL_BINDING_KEY, event->keysym.sym);
543#endif
544	}
545	if (key != -1) {
546		if (event->type == SDL_KEYDOWN) {
547			context->core->addKeys(context->core, 1 << key);
548		} else {
549			context->core->clearKeys(context->core, 1 << key);
550		}
551		return;
552	}
553	if (event->keysym.sym == SDLK_TAB) {
554		context->sync.audioWait = event->type != SDL_KEYDOWN;
555		return;
556	}
557	if (event->type == SDL_KEYDOWN) {
558		switch (event->keysym.sym) {
559		case SDLK_F11:
560			// TODO: Put back debugger
561			return;
562#ifdef USE_PNG
563		case SDLK_F12:
564			// TODO: Put back screenshots
565			return;
566#endif
567		case SDLK_BACKSLASH:
568			mCoreThreadPause(context);
569			context->frameCallback = _pauseAfterFrame;
570			mCoreThreadUnpause(context);
571			return;
572		case SDLK_BACKQUOTE:
573			// TODO: Put back rewind
574			return;
575#ifdef BUILD_PANDORA
576		case SDLK_ESCAPE:
577			mCoreThreadEnd(context);
578			return;
579#endif
580		default:
581			if ((event->keysym.mod & GUI_MOD) && (event->keysym.mod & GUI_MOD) == event->keysym.mod) {
582				switch (event->keysym.sym) {
583#if SDL_VERSION_ATLEAST(2, 0, 0)
584				case SDLK_f:
585					SDL_SetWindowFullscreen(sdlContext->window, sdlContext->fullscreen ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP);
586					sdlContext->fullscreen = !sdlContext->fullscreen;
587					sdlContext->windowUpdated = 1;
588					break;
589#endif
590				case SDLK_p:
591					mCoreThreadTogglePause(context);
592					break;
593				case SDLK_n:
594					mCoreThreadPause(context);
595					context->frameCallback = _pauseAfterFrame;
596					mCoreThreadUnpause(context);
597					break;
598				case SDLK_r:
599					mCoreThreadReset(context);
600					break;
601				default:
602					break;
603				}
604			}
605			if (event->keysym.mod & KMOD_SHIFT) {
606				switch (event->keysym.sym) {
607				case SDLK_F1:
608				case SDLK_F2:
609				case SDLK_F3:
610				case SDLK_F4:
611				case SDLK_F5:
612				case SDLK_F6:
613				case SDLK_F7:
614				case SDLK_F8:
615				case SDLK_F9:
616					mCoreThreadInterrupt(context);
617					mCoreSaveState(context->core, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SCREENSHOT);
618					mCoreThreadContinue(context);
619					break;
620				default:
621					break;
622				}
623			} else {
624				switch (event->keysym.sym) {
625				case SDLK_F1:
626				case SDLK_F2:
627				case SDLK_F3:
628				case SDLK_F4:
629				case SDLK_F5:
630				case SDLK_F6:
631				case SDLK_F7:
632				case SDLK_F8:
633				case SDLK_F9:
634					mCoreThreadInterrupt(context);
635					mCoreLoadState(context->core, event->keysym.sym - SDLK_F1 + 1, SAVESTATE_SCREENSHOT);
636					mCoreThreadContinue(context);
637					break;
638				default:
639					break;
640				}
641			}
642			return;
643		}
644	}
645}
646
647static void _mSDLHandleJoyButton(struct mCore* core, struct mSDLPlayer* sdlContext, const struct SDL_JoyButtonEvent* event) {
648	int key = 0;
649	key = mInputMapKey(sdlContext->bindings, SDL_BINDING_BUTTON, event->button);
650	if (key == -1) {
651		return;
652	}
653
654	if (event->type == SDL_JOYBUTTONDOWN) {
655		core->addKeys(core, 1 << key);
656	} else {
657		core->clearKeys(core, 1 << key);
658	}
659}
660
661static void _mSDLHandleJoyAxis(struct mCore* core, struct mSDLPlayer* sdlContext, const struct SDL_JoyAxisEvent* event) {
662	int clearKeys = ~mInputClearAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, -1);
663	int newKeys = 0;
664	int key = mInputMapAxis(sdlContext->bindings, SDL_BINDING_BUTTON, event->axis, event->value);
665	if (key != -1) {
666		newKeys |= 1 << key;
667	}
668	clearKeys &= ~newKeys;
669	core->clearKeys(core, clearKeys);
670	core->addKeys(core, newKeys);
671
672}
673
674#if SDL_VERSION_ATLEAST(2, 0, 0)
675static void _mSDLHandleWindowEvent(struct mSDLPlayer* sdlContext, const struct SDL_WindowEvent* event) {
676	switch (event->event) {
677	case SDL_WINDOWEVENT_SIZE_CHANGED:
678		sdlContext->windowUpdated = 1;
679		break;
680	}
681}
682#endif
683
684void mSDLHandleEventGBA(struct GBAThread* context, struct mSDLPlayer* sdlContext, const union SDL_Event* event) {
685	switch (event->type) {
686	case SDL_QUIT:
687		GBAThreadEnd(context);
688		break;
689#if SDL_VERSION_ATLEAST(2, 0, 0)
690	case SDL_WINDOWEVENT:
691		_mSDLHandleWindowEvent(sdlContext, &event->window);
692		break;
693#endif
694	case SDL_KEYDOWN:
695	case SDL_KEYUP:
696		_mSDLHandleKeypressGBA(context, sdlContext, &event->key);
697		break;
698	case SDL_JOYBUTTONDOWN:
699	case SDL_JOYBUTTONUP:
700		_mSDLHandleJoyButtonGBA(context, sdlContext, &event->jbutton);
701		break;
702	case SDL_JOYHATMOTION:
703		_mSDLHandleJoyHatGBA(context, &event->jhat);
704		break;
705	case SDL_JOYAXISMOTION:
706		_mSDLHandleJoyAxisGBA(context, sdlContext, &event->jaxis);
707		break;
708	}
709}
710
711void mSDLHandleEvent(struct mCoreThread* context, struct mSDLPlayer* sdlContext, const union SDL_Event* event) {
712	switch (event->type) {
713	case SDL_QUIT:
714		mCoreThreadEnd(context);
715		break;
716#if SDL_VERSION_ATLEAST(2, 0, 0)
717	case SDL_WINDOWEVENT:
718		_mSDLHandleWindowEvent(sdlContext, &event->window);
719		break;
720#endif
721	case SDL_KEYDOWN:
722	case SDL_KEYUP:
723		_mSDLHandleKeypress(context, sdlContext, &event->key);
724		break;
725	case SDL_JOYBUTTONDOWN:
726	case SDL_JOYBUTTONUP:
727		_mSDLHandleJoyButton(context->core, sdlContext, &event->jbutton);
728		break;
729	case SDL_JOYHATMOTION:
730		// TODO
731		break;
732	case SDL_JOYAXISMOTION:
733		_mSDLHandleJoyAxis(context->core, sdlContext, &event->jaxis);
734		break;
735	}
736}
737
738#if SDL_VERSION_ATLEAST(2, 0, 0)
739static void _mSDLSetRumble(struct mRumble* rumble, int enable) {
740	struct mSDLRumble* sdlRumble = (struct mSDLRumble*) rumble;
741	if (!sdlRumble->p->joystick->haptic || !SDL_HapticRumbleSupported(sdlRumble->p->joystick->haptic)) {
742		return;
743	}
744	sdlRumble->level += enable;
745	if (CircleBufferSize(&sdlRumble->history) == RUMBLE_PWM) {
746		int8_t oldLevel;
747		CircleBufferRead8(&sdlRumble->history, &oldLevel);
748		sdlRumble->level -= oldLevel;
749	}
750	CircleBufferWrite8(&sdlRumble->history, enable);
751	if (sdlRumble->level) {
752		SDL_HapticRumblePlay(sdlRumble->p->joystick->haptic, sdlRumble->level / (float) RUMBLE_PWM, 20);
753	} else {
754		SDL_HapticRumbleStop(sdlRumble->p->joystick->haptic);
755	}
756}
757#endif
758
759static int32_t _readTilt(struct mSDLPlayer* player, int axis) {
760	if (!player->joystick) {
761		return 0;
762	}
763	return SDL_JoystickGetAxis(player->joystick->joystick, axis) * 0x3800;
764}
765
766static int32_t _mSDLReadTiltX(struct mRotationSource* source) {
767	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
768	return _readTilt(rotation->p, rotation->axisX);
769}
770
771static int32_t _mSDLReadTiltY(struct mRotationSource* source) {
772	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
773	return _readTilt(rotation->p, rotation->axisY);
774}
775
776static int32_t _mSDLReadGyroZ(struct mRotationSource* source) {
777	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
778	float z = rotation->zDelta;
779	return z * rotation->gyroSensitivity;
780}
781
782static void _mSDLRotationSample(struct mRotationSource* source) {
783	struct mSDLRotation* rotation = (struct mSDLRotation*) source;
784	SDL_JoystickUpdate();
785	if (!rotation->p->joystick) {
786		return;
787	}
788
789	int x = SDL_JoystickGetAxis(rotation->p->joystick->joystick, rotation->gyroX);
790	int y = SDL_JoystickGetAxis(rotation->p->joystick->joystick, rotation->gyroY);
791	union {
792		float f;
793		int32_t i;
794	} theta = { .f = atan2f(y, x) - atan2f(rotation->oldY, rotation->oldX) };
795	if (isnan(theta.f)) {
796		theta.f = 0.0f;
797	} else if (theta.f > M_PI) {
798		theta.f -= 2.0f * M_PI;
799	} else if (theta.f < -M_PI) {
800		theta.f += 2.0f * M_PI;
801	}
802	rotation->oldX = x;
803	rotation->oldY = y;
804
805	float oldZ = 0;
806	if (CircleBufferSize(&rotation->zHistory) == GYRO_STEPS * sizeof(float)) {
807		CircleBufferRead32(&rotation->zHistory, (int32_t*) &oldZ);
808	}
809	CircleBufferWrite32(&rotation->zHistory, theta.i);
810	rotation->zDelta += theta.f - oldZ;
811}
812
813#if SDL_VERSION_ATLEAST(2, 0, 0)
814void mSDLSuspendScreensaver(struct mSDLEvents* events) {
815	if (events->screensaverSuspendDepth == 0 && events->screensaverSuspendable) {
816		SDL_DisableScreenSaver();
817	}
818	++events->screensaverSuspendDepth;
819}
820
821void mSDLResumeScreensaver(struct mSDLEvents* events) {
822	--events->screensaverSuspendDepth;
823	if (events->screensaverSuspendDepth == 0 && events->screensaverSuspendable) {
824		SDL_EnableScreenSaver();
825	}
826}
827
828void mSDLSetScreensaverSuspendable(struct mSDLEvents* events, bool suspendable) {
829	bool wasSuspendable = events->screensaverSuspendable;
830	events->screensaverSuspendable = suspendable;
831	if (events->screensaverSuspendDepth > 0) {
832		if (suspendable && !wasSuspendable) {
833			SDL_DisableScreenSaver();
834		} else if (!suspendable && wasSuspendable) {
835			SDL_EnableScreenSaver();
836		}
837	} else {
838		SDL_EnableScreenSaver();
839	}
840}
841#endif