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