all repos — mgba @ 2def7289f3cb02c3a3edc51e26ce3f634033e264

mGBA Game Boy Advance Emulator

src/feature/gui/gui-runner.c (view raw)

  1/* Copyright (c) 2013-2016 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 "gui-runner.h"
  7
  8#include <mgba/core/core.h>
  9#include <mgba/core/serialize.h>
 10#include "feature/gui/gui-config.h"
 11#include <mgba/internal/gba/gba.h>
 12#include <mgba/internal/gba/input.h>
 13#include <mgba/gba/interface.h>
 14#include <mgba-util/gui/file-select.h>
 15#include <mgba-util/gui/font.h>
 16#include <mgba-util/gui/menu.h>
 17#include <mgba-util/memory.h>
 18#include <mgba-util/png-io.h>
 19#include <mgba-util/vfs.h>
 20
 21#include <sys/time.h>
 22
 23mLOG_DECLARE_CATEGORY(GUI_RUNNER);
 24mLOG_DEFINE_CATEGORY(GUI_RUNNER, "GUI Runner", "gui.runner");
 25
 26#define AUTOSAVE_GRANULARITY 600
 27#define FPS_GRANULARITY 120
 28#define FPS_BUFFER_SIZE 3
 29
 30enum {
 31	RUNNER_CONTINUE = 1,
 32	RUNNER_EXIT,
 33	RUNNER_SAVE_STATE,
 34	RUNNER_LOAD_STATE,
 35	RUNNER_SCREENSHOT,
 36	RUNNER_CONFIG,
 37	RUNNER_RESET,
 38	RUNNER_COMMAND_MASK = 0xFFFF
 39};
 40
 41#define RUNNER_STATE(X) ((X) << 16)
 42
 43static const struct mInputPlatformInfo _mGUIKeyInfo = {
 44	.platformName = "gui",
 45	.keyId = (const char*[GUI_INPUT_MAX]) {
 46		"Select",
 47		"Back",
 48		"Cancel",
 49		"Up",
 50		"Down",
 51		"Left",
 52		"Right",
 53		[mGUI_INPUT_INCREASE_BRIGHTNESS] = "Increase solar brightness",
 54		[mGUI_INPUT_DECREASE_BRIGHTNESS] = "Decrease solar brightness",
 55		[mGUI_INPUT_SCREEN_MODE] = "Screen mode",
 56		[mGUI_INPUT_SCREENSHOT] = "Take screenshot",
 57		[mGUI_INPUT_FAST_FORWARD_HELD] = "Fast forward (held)",
 58		[mGUI_INPUT_FAST_FORWARD_TOGGLE] = "Fast forward (toggle)",
 59		[mGUI_INPUT_MUTE_TOGGLE] = "Mute (toggle)",
 60	},
 61	.nKeys = GUI_INPUT_MAX
 62};
 63
 64static void _log(struct mLogger*, int category, enum mLogLevel level, const char* format, va_list args);
 65
 66static struct mGUILogger {
 67	struct mLogger d;
 68	struct VFile* vf;
 69	int logLevel;
 70} logger = {
 71	.d = {
 72		.log = _log
 73	},
 74	.vf = NULL,
 75	.logLevel = 0
 76};
 77
 78static bool _testExtensions(const char* name) {
 79	char ext[PATH_MAX] = {};
 80	separatePath(name, NULL, NULL, ext);
 81
 82	if (!strncmp(ext, "sav", PATH_MAX)) {
 83		return false;
 84	}
 85	if (!strncmp(ext, "png", PATH_MAX)) {
 86		return false;
 87	}
 88	if (!strncmp(ext, "ini", PATH_MAX)) {
 89		return false;
 90	}
 91	if (!strncmp(ext, "ss", 2)) {
 92		return false;
 93	}
 94
 95	return true;
 96}
 97
 98static void _drawBackground(struct GUIBackground* background, void* context) {
 99	UNUSED(context);
100	struct mGUIBackground* gbaBackground = (struct mGUIBackground*) background;
101	if (gbaBackground->p->drawFrame) {
102		gbaBackground->p->drawFrame(gbaBackground->p, true);
103	}
104}
105
106static void _drawState(struct GUIBackground* background, void* id) {
107	struct mGUIBackground* gbaBackground = (struct mGUIBackground*) background;
108	int stateId = ((int) id) >> 16;
109	if (gbaBackground->p->drawScreenshot) {
110		unsigned w, h;
111		gbaBackground->p->core->desiredVideoDimensions(gbaBackground->p->core, &w, &h);
112		if (gbaBackground->screenshot && gbaBackground->screenshotId == (int) id) {
113			gbaBackground->p->drawScreenshot(gbaBackground->p, gbaBackground->screenshot, w, h, true);
114			return;
115		}
116		struct VFile* vf = mCoreGetState(gbaBackground->p->core, stateId, false);
117		color_t* pixels = gbaBackground->screenshot;
118		if (!pixels) {
119			pixels = anonymousMemoryMap(w * h * 4);
120			gbaBackground->screenshot = pixels;
121		}
122		bool success = false;
123		if (vf && isPNG(vf) && pixels) {
124			png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
125			png_infop info = png_create_info_struct(png);
126			png_infop end = png_create_info_struct(png);
127			if (png && info && end) {
128				success = PNGReadHeader(png, info);
129				success = success && PNGReadPixels(png, info, pixels, w, h, w);
130				success = success && PNGReadFooter(png, end);
131			}
132			PNGReadClose(png, info, end);
133		}
134		if (vf) {
135			vf->close(vf);
136		}
137		if (success) {
138			gbaBackground->p->drawScreenshot(gbaBackground->p, pixels, w, h, true);
139			gbaBackground->screenshotId = (int) id;
140		} else if (gbaBackground->p->drawFrame) {
141			gbaBackground->p->drawFrame(gbaBackground->p, true);
142		}
143	}
144}
145
146static void _updateLux(struct GBALuminanceSource* lux) {
147	UNUSED(lux);
148}
149
150static uint8_t _readLux(struct GBALuminanceSource* lux) {
151	struct mGUIRunnerLux* runnerLux = (struct mGUIRunnerLux*) lux;
152	int value = 0x16;
153	if (runnerLux->luxLevel > 0) {
154		value += GBA_LUX_LEVELS[runnerLux->luxLevel - 1];
155	}
156	return 0xFF - value;
157}
158
159static void _tryAutosave(struct mGUIRunner* runner) {
160	int autosave = false;
161	mCoreConfigGetIntValue(&runner->config, "autosave", &autosave);
162	if (!autosave) {
163		return;
164	}
165
166#ifdef DISABLE_THREADING
167	mCoreSaveState(runner->core, 0, SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
168#else
169	if (!runner->autosave.buffer) {
170		runner->autosave.buffer = VFileMemChunk(NULL, 0);
171	}
172	MutexLock(&runner->autosave.mutex);
173	runner->autosave.core = runner->core;
174	mCoreSaveStateNamed(runner->core, runner->autosave.buffer, SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
175	ConditionWake(&runner->autosave.cond);
176	MutexUnlock(&runner->autosave.mutex);
177#endif
178}
179
180void mGUIInit(struct mGUIRunner* runner, const char* port) {
181	GUIInit(&runner->params);
182	runner->port = port;
183	runner->core = NULL;
184	runner->luminanceSource.d.readLuminance = _readLux;
185	runner->luminanceSource.d.sample = _updateLux;
186	runner->luminanceSource.luxLevel = 0;
187	runner->background.d.draw = _drawBackground;
188	runner->background.p = runner;
189	runner->fps = 0;
190	runner->lastFpsCheck = 0;
191	runner->totalDelta = 0;
192	CircleBufferInit(&runner->fpsBuffer, FPS_BUFFER_SIZE * sizeof(uint32_t));
193
194	mInputMapInit(&runner->params.keyMap, &_mGUIKeyInfo);
195	mCoreConfigInit(&runner->config, runner->port);
196	// TODO: Do we need to load more defaults?
197	mCoreConfigSetDefaultIntValue(&runner->config, "volume", 0x100);
198	mCoreConfigSetDefaultValue(&runner->config, "idleOptimization", "detect");
199	mCoreConfigSetDefaultIntValue(&runner->config, "autoload", true);
200#ifdef DISABLE_THREADING
201	mCoreConfigSetDefaultIntValue(&runner->config, "autosave", false);
202#else
203	mCoreConfigSetDefaultIntValue(&runner->config, "autosave", true);
204#endif
205	mCoreConfigSetDefaultIntValue(&runner->config, "showOSD", true);
206	mCoreConfigLoad(&runner->config);
207	mCoreConfigGetIntValue(&runner->config, "logLevel", &logger.logLevel);
208
209	char path[PATH_MAX];
210	mCoreConfigDirectory(path, PATH_MAX);
211	strncat(path, PATH_SEP "log", PATH_MAX - strlen(path));
212	logger.vf = VFileOpen(path, O_CREAT | O_WRONLY | O_APPEND);
213	mLogSetDefaultLogger(&logger.d);
214
215	const char* lastPath = mCoreConfigGetValue(&runner->config, "lastDirectory");
216	if (lastPath) {
217		struct VDir* dir = VDirOpen(lastPath);
218		if (dir) {
219			dir->close(dir);
220			strncpy(runner->params.currentPath, lastPath, PATH_MAX - 1);
221			runner->params.currentPath[PATH_MAX - 1] = '\0';
222		}
223	}
224
225#ifndef DISABLE_THREADING
226	if (!runner->autosave.running) {
227		runner->autosave.running = true;
228		runner->autosave.core = NULL;
229		MutexInit(&runner->autosave.mutex);
230		ConditionInit(&runner->autosave.cond);
231		ThreadCreate(&runner->autosave.thread, mGUIAutosaveThread, &runner->autosave);
232	}
233#endif
234}
235
236void mGUIDeinit(struct mGUIRunner* runner) {
237#ifndef DISABLE_THREADING
238	MutexLock(&runner->autosave.mutex);
239	runner->autosave.running = false;
240	ConditionWake(&runner->autosave.cond);
241	MutexUnlock(&runner->autosave.mutex);
242
243	ThreadJoin(&runner->autosave.thread);
244
245	ConditionDeinit(&runner->autosave.cond);
246	MutexDeinit(&runner->autosave.mutex);
247
248	if (runner->autosave.buffer) {
249		runner->autosave.buffer->close(runner->autosave.buffer);
250	}
251#endif
252
253	if (runner->teardown) {
254		runner->teardown(runner);
255	}
256	CircleBufferDeinit(&runner->fpsBuffer);
257	mInputMapDeinit(&runner->params.keyMap);
258	mCoreConfigDeinit(&runner->config);
259	if (logger.vf) {
260		logger.vf->close(logger.vf);
261		logger.vf = NULL;
262	}
263}
264
265static void _log(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
266	struct mGUILogger* guiLogger = (struct mGUILogger*) logger;
267	if (!guiLogger->vf) {
268		return;
269	}
270	if (!(guiLogger->logLevel & level)) {
271		return;
272	}
273
274	char log[256] = {0};
275	vsnprintf(log, sizeof(log) - 1, format, args);
276	char log2[256] = {0};
277	size_t len = snprintf(log2, sizeof(log2) - 1, "%s: %s\n", mLogCategoryName(category), log);
278	if (len >= sizeof(log2)) {
279		len = sizeof(log2) - 1;
280	}
281	if (guiLogger->vf->write(guiLogger->vf, log2, len) < 0) {
282		char path[PATH_MAX];
283		mCoreConfigDirectory(path, PATH_MAX);
284		strncat(path, PATH_SEP "log", PATH_MAX - strlen(path));
285		guiLogger->vf->close(guiLogger->vf);
286		guiLogger->vf = VFileOpen(path, O_CREAT | O_WRONLY | O_APPEND);
287		if (guiLogger->vf->write(guiLogger->vf, log2, len) < 0) {
288			guiLogger->vf->close(guiLogger->vf);
289			guiLogger->vf = NULL;
290		}
291	}
292#ifdef GEKKO
293	puts(log2);
294#endif
295}
296
297static void _updateLoading(size_t read, size_t size, void* context) {
298	struct mGUIRunner* runner = context;
299	if (read & 0x3FFFF) {
300		return;
301	}
302
303	runner->params.drawStart();
304	if (runner->params.guiPrepare) {
305		runner->params.guiPrepare();
306	}
307	GUIFontPrintf(runner->params.font, runner->params.width / 2, (GUIFontHeight(runner->params.font) + runner->params.height) / 2, GUI_ALIGN_HCENTER, 0xFFFFFFFF, "Loading...%i%%", 100 * read / size);
308	if (runner->params.guiFinish) {
309		runner->params.guiFinish();
310	}
311	runner->params.drawEnd();
312}
313
314void mGUIRun(struct mGUIRunner* runner, const char* path) {
315	struct mGUIBackground drawState = {
316		.d = {
317			.draw = _drawState
318		},
319		.p = runner,
320		.screenshot = 0,
321		.screenshotId = 0
322	};
323	struct GUIMenu pauseMenu = {
324		.title = "Game Paused",
325		.index = 0,
326		.background = &runner->background.d
327	};
328	struct GUIMenu stateSaveMenu = {
329		.title = "Save state",
330		.index = 0,
331		.background = &drawState.d
332	};
333	struct GUIMenu stateLoadMenu = {
334		.title = "Load state",
335		.index = 0,
336		.background = &drawState.d
337	};
338	GUIMenuItemListInit(&pauseMenu.items, 0);
339	GUIMenuItemListInit(&stateSaveMenu.items, 9);
340	GUIMenuItemListInit(&stateLoadMenu.items, 9);
341	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Unpause", .data = (void*) RUNNER_CONTINUE };
342	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Save state", .submenu = &stateSaveMenu };
343	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Load state", .submenu = &stateLoadMenu };
344
345	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(1)) };
346	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(2)) };
347	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(3)) };
348	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(4)) };
349	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(5)) };
350	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(6)) };
351	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(7)) };
352	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(8)) };
353	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(9)) };
354
355	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "Autosave", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(0)) };
356	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(1)) };
357	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(2)) };
358	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(3)) };
359	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(4)) };
360	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(5)) };
361	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(6)) };
362	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(7)) };
363	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(8)) };
364	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(9)) };
365
366	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Take screenshot", .data = (void*) RUNNER_SCREENSHOT };
367	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Configure", .data = (void*) RUNNER_CONFIG };
368	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Reset game", .data = (void*) RUNNER_RESET };
369	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Exit game", .data = (void*) RUNNER_EXIT };
370
371	runner->params.drawStart();
372	if (runner->params.guiPrepare) {
373		runner->params.guiPrepare();
374	}
375	GUIFontPrint(runner->params.font, runner->params.width / 2, (GUIFontHeight(runner->params.font) + runner->params.height) / 2, GUI_ALIGN_HCENTER, 0xFFFFFFFF, "Loading...");
376	if (runner->params.guiFinish) {
377		runner->params.guiFinish();
378	}
379	runner->params.drawEnd();
380
381	bool found = false;
382	mLOG(GUI_RUNNER, INFO, "Attempting to load %s", path);
383	runner->core = mCoreFind(path);
384	if (runner->core) {
385		mLOG(GUI_RUNNER, INFO, "Found core");
386		runner->core->init(runner->core);
387		mCoreInitConfig(runner->core, runner->port);
388		mInputMapInit(&runner->core->inputMap, &GBAInputInfo);
389
390		found = mCorePreloadFileCB(runner->core, path, _updateLoading, runner);
391		if (!found) {
392			mLOG(GUI_RUNNER, WARN, "Failed to load %s!", path);
393			mCoreConfigDeinit(&runner->core->config);
394			runner->core->deinit(runner->core);
395		}
396	}
397
398	if (!found) {
399		mLOG(GUI_RUNNER, WARN, "Failed to find core for %s!", path);
400		GUIShowMessageBox(&runner->params, GUI_MESSAGE_BOX_OK, 240, "Load failed!");
401		return;
402	}
403	if (runner->core->platform(runner->core) == PLATFORM_GBA) {
404		runner->core->setPeripheral(runner->core, mPERIPH_GBA_LUMINANCE, &runner->luminanceSource.d);
405	}
406	mLOG(GUI_RUNNER, DEBUG, "Loading config...");
407	mCoreLoadForeignConfig(runner->core, &runner->config);
408
409	mLOG(GUI_RUNNER, DEBUG, "Loading save...");
410	mCoreAutoloadSave(runner->core);
411	mCoreAutoloadCheats(runner->core);
412	if (runner->setup) {
413		mLOG(GUI_RUNNER, DEBUG, "Setting up runner...");
414		runner->setup(runner);
415	}
416	if (runner->config.port && runner->keySources) {
417		mLOG(GUI_RUNNER, DEBUG, "Loading key sources for %s...", runner->config.port);
418		size_t i;
419		for (i = 0; runner->keySources[i].id; ++i) {
420			mInputMapLoad(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
421		}
422	}
423	mLOG(GUI_RUNNER, DEBUG, "Reseting...");
424	runner->core->reset(runner->core);
425	mLOG(GUI_RUNNER, DEBUG, "Reset!");
426
427
428	int autoload = false;
429	mCoreConfigGetIntValue(&runner->config, "autoload", &autoload);
430	if (autoload) {
431		mCoreLoadState(runner->core, 0, SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
432	}
433
434	int showOSD = true;
435	mCoreConfigGetIntValue(&runner->config, "showOSD", &showOSD);
436
437	int drawFps = false;
438	mCoreConfigGetIntValue(&runner->config, "fpsCounter", &drawFps);
439
440	bool running = true;
441
442#ifndef DISABLE_THREADING
443	MutexLock(&runner->autosave.mutex);
444	runner->autosave.core = runner->core;
445	MutexUnlock(&runner->autosave.mutex);
446#endif
447
448	if (runner->gameLoaded) {
449		runner->gameLoaded(runner);
450	}
451	mLOG(GUI_RUNNER, INFO, "Game starting");
452	while (running) {
453		CircleBufferClear(&runner->fpsBuffer);
454		runner->totalDelta = 0;
455		runner->fps = 0;
456		struct timeval tv;
457		gettimeofday(&tv, 0);
458		runner->lastFpsCheck = 1000000LL * tv.tv_sec + tv.tv_usec;
459
460		int frame = 0;
461		bool fastForward = false;
462		while (running) {
463			if (runner->running) {
464				running = runner->running(runner);
465				if (!running) {
466					break;
467				}
468			}
469			uint32_t guiKeys;
470			uint32_t heldKeys;
471			GUIPollInput(&runner->params, &guiKeys, &heldKeys);
472			if (guiKeys & (1 << GUI_INPUT_CANCEL)) {
473				break;
474			}
475			if (guiKeys & (1 << mGUI_INPUT_INCREASE_BRIGHTNESS)) {
476				if (runner->luminanceSource.luxLevel < 10) {
477					++runner->luminanceSource.luxLevel;
478				}
479			}
480			if (guiKeys & (1 << mGUI_INPUT_DECREASE_BRIGHTNESS)) {
481				if (runner->luminanceSource.luxLevel > 0) {
482					--runner->luminanceSource.luxLevel;
483				}
484			}
485			if (guiKeys & (1 << mGUI_INPUT_SCREEN_MODE) && runner->incrementScreenMode) {
486				runner->incrementScreenMode(runner);
487			}
488			if (guiKeys & (1 << mGUI_INPUT_SCREENSHOT)) {
489				mCoreTakeScreenshot(runner->core);
490			}
491			if (runner->setFrameLimiter) {
492				if (guiKeys & (1 << mGUI_INPUT_FAST_FORWARD_TOGGLE)) {
493					fastForward = !fastForward;
494				}
495				if (fastForward || (heldKeys & (1 << mGUI_INPUT_FAST_FORWARD_HELD))) {
496					runner->setFrameLimiter(runner, false);
497				} else {
498					runner->setFrameLimiter(runner, true);
499				}
500			}
501			if (guiKeys & (1 << mGUI_INPUT_MUTE_TOGGLE)) {
502				int mute = !runner->core->opts.mute;
503				mCoreConfigSetUIntValue(&runner->config, "mute", mute);
504				runner->core->reloadConfigOption(runner->core, "mute", &runner->config);
505			}
506			uint16_t keys = runner->pollGameInput(runner);
507			if (runner->prepareForFrame) {
508				runner->prepareForFrame(runner);
509			}
510			runner->core->setKeys(runner->core, keys);
511			runner->core->runFrame(runner->core);
512			if (runner->drawFrame) {
513				runner->params.drawStart();
514				runner->drawFrame(runner, false);
515				if (showOSD || drawFps) {
516					if (runner->params.guiPrepare) {
517						runner->params.guiPrepare();
518					}
519					if (drawFps) {
520						GUIFontPrintf(runner->params.font, 0, GUIFontHeight(runner->params.font), GUI_ALIGN_LEFT, 0x7FFFFFFF, "%.2f fps", runner->fps);
521					}
522					if (showOSD) {
523						unsigned origin = runner->params.width - GUIFontHeight(runner->params.font) / 2;
524						unsigned w;
525						if (fastForward || (heldKeys & (1 << mGUI_INPUT_FAST_FORWARD_HELD))) {
526							GUIFontDrawIcon(runner->params.font, origin, GUIFontHeight(runner->params.font) / 2, GUI_ALIGN_RIGHT, 0, 0x7FFFFFFF, GUI_ICON_STATUS_FAST_FORWARD);
527							GUIFontIconMetrics(runner->params.font, GUI_ICON_STATUS_FAST_FORWARD, &w, NULL);
528							origin -= w + GUIFontHeight(runner->params.font) / 2;
529						}
530						if (runner->core->opts.mute) {
531							GUIFontDrawIcon(runner->params.font, origin, GUIFontHeight(runner->params.font) / 2, GUI_ALIGN_RIGHT, 0, 0x7FFFFFFF, GUI_ICON_STATUS_MUTE);
532							GUIFontIconMetrics(runner->params.font, GUI_ICON_STATUS_MUTE, &w, NULL);
533							origin -= w + GUIFontHeight(runner->params.font) / 2;
534						}
535					}
536					if (runner->params.guiFinish) {
537						runner->params.guiFinish();
538					}
539				}
540				runner->params.drawEnd();
541
542				if (runner->core->frameCounter(runner->core) % FPS_GRANULARITY == 0) {
543					if (drawFps) {
544						struct timeval tv;
545						gettimeofday(&tv, 0);
546						uint64_t t = 1000000LL * tv.tv_sec + tv.tv_usec;
547						uint64_t delta = t - runner->lastFpsCheck;
548						runner->lastFpsCheck = t;
549						if (delta > 0x7FFFFFFFLL) {
550							CircleBufferClear(&runner->fpsBuffer);
551							runner->fps = 0;
552						}
553						if (CircleBufferSize(&runner->fpsBuffer) == CircleBufferCapacity(&runner->fpsBuffer)) {
554							int32_t last;
555							CircleBufferRead32(&runner->fpsBuffer, &last);
556							runner->totalDelta -= last;
557						}
558						CircleBufferWrite32(&runner->fpsBuffer, delta);
559						runner->totalDelta += delta;
560						runner->fps = (CircleBufferSize(&runner->fpsBuffer) * FPS_GRANULARITY * 1000000.0f) / (runner->totalDelta * sizeof(uint32_t));
561					}
562				}
563				if (frame == AUTOSAVE_GRANULARITY) {
564					frame = 0;
565					_tryAutosave(runner);
566				}
567				++frame;
568			}
569		}
570		if (!running) {
571			break;
572		}
573
574		if (runner->paused) {
575			runner->paused(runner);
576		}
577		if (runner->setFrameLimiter) {
578			runner->setFrameLimiter(runner, true);
579		}
580
581		GUIInvalidateKeys(&runner->params);
582		uint32_t keys = 0xFFFFFFFF; // Huge hack to avoid an extra variable!
583		struct GUIMenuItem* item;
584		enum GUIMenuExitReason reason = GUIShowMenu(&runner->params, &pauseMenu, &item);
585		if (reason == GUI_MENU_EXIT_ACCEPT) {
586			switch (((int) item->data) & RUNNER_COMMAND_MASK) {
587			case RUNNER_EXIT:
588				running = false;
589				keys = 0;
590				break;
591			case RUNNER_RESET:
592				runner->core->reset(runner->core);
593				break;
594			case RUNNER_SAVE_STATE:
595				mCoreSaveState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
596				break;
597			case RUNNER_LOAD_STATE:
598				mCoreLoadState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
599				break;
600			case RUNNER_SCREENSHOT:
601				mCoreTakeScreenshot(runner->core);
602				break;
603			case RUNNER_CONFIG:
604				mGUIShowConfig(runner, runner->configExtra, runner->nConfigExtra);
605				break;
606			case RUNNER_CONTINUE:
607				break;
608			}
609		}
610		int frames = 0;
611		GUIPollInput(&runner->params, 0, &keys);
612		while (keys && frames < 30) {
613			++frames;
614			runner->params.drawStart();
615			runner->drawFrame(runner, true);
616			runner->params.drawEnd();
617#ifdef _3DS
618			// XXX: Why does this fix #1294?
619			usleep(1000);
620#endif
621			GUIPollInput(&runner->params, 0, &keys);
622		}
623		if (runner->unpaused) {
624			runner->unpaused(runner);
625		}
626		mCoreConfigGetIntValue(&runner->config, "fpsCounter", &drawFps);
627		mCoreConfigGetIntValue(&runner->config, "showOSD", &showOSD);
628	}
629	mLOG(GUI_RUNNER, DEBUG, "Shutting down...");
630	if (runner->gameUnloaded) {
631		runner->gameUnloaded(runner);
632	}
633#ifndef DISABLE_THREADING
634	MutexLock(&runner->autosave.mutex);
635	runner->autosave.core = NULL;
636	MutexUnlock(&runner->autosave.mutex);
637#endif
638
639	int autosave = false;
640	mCoreConfigGetIntValue(&runner->config, "autosave", &autosave);
641	if (autosave) {
642		mCoreSaveState(runner->core, 0, SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
643	}
644
645	mLOG(GUI_RUNNER, DEBUG, "Unloading game...");
646	runner->core->unloadROM(runner->core);
647	drawState.screenshotId = 0;
648	if (drawState.screenshot) {
649		unsigned w, h;
650		runner->core->desiredVideoDimensions(runner->core, &w, &h);
651		mappedMemoryFree(drawState.screenshot, w * h * 4);
652	}
653
654	if (runner->config.port) {
655		mLOG(GUI_RUNNER, DEBUG, "Saving key sources...");
656		if (runner->keySources) {
657			size_t i;
658			for (i = 0; runner->keySources[i].id; ++i) {
659				mInputMapSave(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
660				mInputMapSave(&runner->params.keyMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
661			}
662		}
663		mCoreConfigSave(&runner->config);
664	}
665	mInputMapDeinit(&runner->core->inputMap);
666	mLOG(GUI_RUNNER, DEBUG, "Deinitializing core...");
667	mCoreConfigDeinit(&runner->core->config);
668	runner->core->deinit(runner->core);
669	runner->core = NULL;
670
671	GUIMenuItemListDeinit(&pauseMenu.items);
672	GUIMenuItemListDeinit(&stateSaveMenu.items);
673	GUIMenuItemListDeinit(&stateLoadMenu.items);
674	mLOG(GUI_RUNNER, INFO, "Game stopped!");
675}
676
677void mGUIRunloop(struct mGUIRunner* runner) {
678	if (runner->keySources) {
679		mLOG(GUI_RUNNER, DEBUG, "Loading key sources for %s...", runner->config.port);
680		size_t i;
681		for (i = 0; runner->keySources[i].id; ++i) {
682			mInputMapLoad(&runner->params.keyMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
683		}
684	}
685	while (!runner->running || runner->running(runner)) {
686		char path[PATH_MAX];
687		const char* preselect = mCoreConfigGetValue(&runner->config, "lastGame");
688		if (preselect) {
689			preselect = strrchr(preselect, '/');
690		}
691		if (preselect) {
692			++preselect;
693		}
694		if (!GUISelectFile(&runner->params, path, sizeof(path), _testExtensions, NULL, preselect)) {
695			break;
696		}
697		mCoreConfigSetValue(&runner->config, "lastDirectory", runner->params.currentPath);
698		mCoreConfigSetValue(&runner->config, "lastGame", path);
699		mCoreConfigSave(&runner->config);
700		mGUIRun(runner, path);
701	}
702}
703
704#ifndef DISABLE_THREADING
705THREAD_ENTRY mGUIAutosaveThread(void* context) {
706	struct mGUIAutosaveContext* autosave = context;
707	MutexLock(&autosave->mutex);
708	while (autosave->running) {
709		ConditionWait(&autosave->cond, &autosave->mutex);
710		if (autosave->running && autosave->core) {
711			struct VFile* vf = mCoreGetState(autosave->core, 0, true);
712			void* mem = autosave->buffer->map(autosave->buffer, autosave->buffer->size(autosave->buffer), MAP_READ);
713			vf->write(vf, mem, autosave->buffer->size(autosave->buffer));
714			autosave->buffer->unmap(autosave->buffer, mem, autosave->buffer->size(autosave->buffer));
715			vf->close(vf);
716		}
717	}
718	MutexUnlock(&autosave->mutex);
719}
720#endif