all repos — mgba @ e131831238851145d6e52370fdef664eff9967b7

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