all repos — mgba @ 64b396aff9fd048bc5b3c9bc158d2c22b67faf13

mGBA Game Boy Advance Emulator

src/platform/qt/Window.cpp (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 "Window.h"
  7
  8#include <QFileDialog>
  9#include <QFileInfo>
 10#include <QKeyEvent>
 11#include <QKeySequence>
 12#include <QMenuBar>
 13#include <QMessageBox>
 14#include <QMimeData>
 15#include <QStackedLayout>
 16
 17#include "CheatsView.h"
 18#include "ConfigController.h"
 19#include "GameController.h"
 20#include "GBAKeyEditor.h"
 21#include "GDBController.h"
 22#include "GDBWindow.h"
 23#include "GIFView.h"
 24#include "LoadSaveState.h"
 25#include "LogView.h"
 26#include "MultiplayerController.h"
 27#include "OverrideView.h"
 28#include "SensorView.h"
 29#include "SettingsView.h"
 30#include "ShortcutController.h"
 31#include "ShortcutView.h"
 32#include "VideoView.h"
 33
 34extern "C" {
 35#include "platform/commandline.h"
 36}
 37
 38using namespace QGBA;
 39
 40Window::Window(ConfigController* config, int playerId, QWidget* parent)
 41	: QMainWindow(parent)
 42	, m_logView(new LogView())
 43	, m_stateWindow(nullptr)
 44	, m_screenWidget(new WindowBackground())
 45	, m_logo(":/res/mgba-1024.png")
 46	, m_config(config)
 47	, m_inputController(playerId)
 48#ifdef USE_FFMPEG
 49	, m_videoView(nullptr)
 50#endif
 51#ifdef USE_MAGICK
 52	, m_gifView(nullptr)
 53#endif
 54#ifdef USE_GDB_STUB
 55	, m_gdbController(nullptr)
 56#endif
 57	, m_mruMenu(nullptr)
 58	, m_shortcutController(new ShortcutController(this))
 59	, m_playerId(playerId)
 60{
 61	setWindowTitle(PROJECT_NAME);
 62	setFocusPolicy(Qt::StrongFocus);
 63	setAcceptDrops(true);
 64	m_controller = new GameController(this);
 65	m_controller->setInputController(&m_inputController);
 66	m_controller->setOverrides(m_config->overrides());
 67
 68	QGLFormat format(QGLFormat(QGL::Rgba | QGL::DoubleBuffer));
 69	format.setSwapInterval(1);
 70	m_display = new Display(format);
 71
 72	m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
 73	m_logo = m_logo; // Free memory left over in old pixmap
 74
 75	m_screenWidget->setMinimumSize(m_display->minimumSize());
 76	m_screenWidget->setSizePolicy(m_display->sizePolicy());
 77	m_screenWidget->setSizeHint(m_display->minimumSize() * 2);
 78	m_screenWidget->setPixmap(m_logo);
 79	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
 80	setCentralWidget(m_screenWidget);
 81
 82	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));
 83	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_display, SLOT(stopDrawing()));
 84	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), this, SLOT(gameStopped()));
 85	connect(m_controller, SIGNAL(stateLoaded(GBAThread*)), m_display, SLOT(forceDraw()));
 86	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), m_display, SLOT(pauseDrawing()));
 87#ifndef Q_OS_MAC
 88	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), menuBar(), SLOT(show()));
 89	connect(m_controller, &GameController::gameUnpaused, [this]() {
 90		if(isFullScreen()) {
 91			menuBar()->hide();
 92		}
 93	});
 94#endif
 95	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), m_display, SLOT(unpauseDrawing()));
 96	connect(m_controller, SIGNAL(postLog(int, const QString&)), m_logView, SLOT(postLog(int, const QString&)));
 97	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
 98	connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
 99	connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
100	connect(m_logView, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
101	connect(m_logView, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
102	connect(m_logView, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
103	connect(this, SIGNAL(startDrawing(const uint32_t*, GBAThread*)), m_display, SLOT(startDrawing(const uint32_t*, GBAThread*)), Qt::QueuedConnection);
104	connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
105	connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
106	connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
107	connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
108	connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
109	connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));
110
111	m_logView->setLevels(GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL);
112	m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
113
114	m_shortcutController->setConfigController(m_config);
115	setupMenu(menuBar());
116}
117
118Window::~Window() {
119	delete m_logView;
120
121#ifdef USE_FFMPEG
122	delete m_videoView;
123#endif
124
125#ifdef USE_MAGICK
126	delete m_gifView;
127#endif
128}
129
130void Window::argumentsPassed(GBAArguments* args) {
131	loadConfig();
132
133	if (args->patch) {
134		m_controller->loadPatch(args->patch);
135	}
136
137	if (args->fname) {
138		m_controller->loadGame(args->fname, args->dirmode);
139	}
140}
141
142void Window::resizeFrame(int width, int height) {
143	QSize newSize(width, height);
144	newSize -= m_screenWidget->size();
145	newSize += size();
146	resize(newSize);
147}
148
149void Window::setConfig(ConfigController* config) {
150	m_config = config;
151}
152
153void Window::loadConfig() {
154	const GBAOptions* opts = m_config->options();
155
156	m_logView->setLevels(opts->logLevel);
157
158	m_controller->setOptions(opts);
159	m_display->lockAspectRatio(opts->lockAspectRatio);
160	m_display->filter(opts->resampleVideo);
161
162	if (opts->bios) {
163		m_controller->loadBIOS(opts->bios);
164	}
165
166	if (opts->fpsTarget) {
167		emit fpsTargetChanged(opts->fpsTarget);
168	}
169
170	if (opts->audioBuffers) {
171		emit audioBufferSamplesChanged(opts->audioBuffers);
172	}
173
174	if (opts->width && opts->height) {
175		resizeFrame(opts->width, opts->height);
176	}
177
178	m_mruFiles = m_config->getMRU();
179	updateMRU();
180
181	m_inputController.setConfiguration(m_config);
182}
183
184void Window::saveConfig() {
185	m_config->write();
186}
187
188void Window::selectROM() {
189	QString filename = QFileDialog::getOpenFileName(this, tr("Select ROM"), m_config->getQtOption("lastDirectory").toString(), tr("Game Boy Advance ROMs (*.gba *.zip *.rom *.bin)"));
190	if (!filename.isEmpty()) {
191		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
192		m_controller->loadGame(filename);
193	}
194}
195
196void Window::selectBIOS() {
197	QString filename = QFileDialog::getOpenFileName(this, tr("Select BIOS"), m_config->getQtOption("lastDirectory").toString());
198	if (!filename.isEmpty()) {
199		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
200		m_config->setOption("bios", filename);
201		m_config->updateOption("bios");
202		m_config->setOption("useBios", true);
203		m_config->updateOption("useBios");
204		m_controller->loadBIOS(filename);
205	}
206}
207
208void Window::selectPatch() {
209	QString filename = QFileDialog::getOpenFileName(this, tr("Select patch"), m_config->getQtOption("lastDirectory").toString(), tr("Patches (*.ips *.ups *.bps)"));
210	if (!filename.isEmpty()) {
211		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
212		m_controller->loadPatch(filename);
213	}
214}
215
216void Window::openKeymapWindow() {
217	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, InputController::KEYBOARD);
218	connect(this, SIGNAL(shutdown()), keyEditor, SLOT(close()));
219	keyEditor->setAttribute(Qt::WA_DeleteOnClose);
220	keyEditor->show();
221}
222
223void Window::openSettingsWindow() {
224	SettingsView* settingsWindow = new SettingsView(m_config);
225	connect(this, SIGNAL(shutdown()), settingsWindow, SLOT(close()));
226	connect(settingsWindow, SIGNAL(biosLoaded(const QString&)), m_controller, SLOT(loadBIOS(const QString&)));
227	connect(settingsWindow, SIGNAL(audioDriverChanged()), m_controller, SLOT(reloadAudioDriver()));
228	settingsWindow->setAttribute(Qt::WA_DeleteOnClose);
229	settingsWindow->show();
230}
231
232void Window::openShortcutWindow() {
233	ShortcutView* shortcutView = new ShortcutView();
234	shortcutView->setController(m_shortcutController);
235	connect(this, SIGNAL(shutdown()), shortcutView, SLOT(close()));
236	shortcutView->setAttribute(Qt::WA_DeleteOnClose);
237	shortcutView->show();
238}
239
240void Window::openOverrideWindow() {
241	OverrideView* overrideWindow = new OverrideView(m_controller, m_config);
242	connect(this, SIGNAL(shutdown()), overrideWindow, SLOT(close()));
243	overrideWindow->setAttribute(Qt::WA_DeleteOnClose);
244	overrideWindow->show();
245}
246
247void Window::openSensorWindow() {
248	SensorView* sensorWindow = new SensorView(m_controller);
249	connect(this, SIGNAL(shutdown()), sensorWindow, SLOT(close()));
250	sensorWindow->setAttribute(Qt::WA_DeleteOnClose);
251	sensorWindow->show();
252}
253
254void Window::openCheatsWindow() {
255	CheatsView* cheatsWindow = new CheatsView(m_controller);
256	connect(this, SIGNAL(shutdown()), cheatsWindow, SLOT(close()));
257	cheatsWindow->setAttribute(Qt::WA_DeleteOnClose);
258	cheatsWindow->show();
259}
260
261#ifdef BUILD_SDL
262void Window::openGamepadWindow() {
263	const char* profile = m_inputController.profileForType(SDL_BINDING_BUTTON);
264	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, SDL_BINDING_BUTTON, profile);
265	connect(this, SIGNAL(shutdown()), keyEditor, SLOT(close()));
266	keyEditor->setAttribute(Qt::WA_DeleteOnClose);
267	keyEditor->show();
268}
269#endif
270
271#ifdef USE_FFMPEG
272void Window::openVideoWindow() {
273	if (!m_videoView) {
274		m_videoView = new VideoView();
275		connect(m_videoView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
276		connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
277		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(stopRecording()));
278		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(close()));
279		connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
280	}
281	m_videoView->show();
282}
283#endif
284
285#ifdef USE_MAGICK
286void Window::openGIFWindow() {
287	if (!m_gifView) {
288		m_gifView = new GIFView();
289		connect(m_gifView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
290		connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
291		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(stopRecording()));
292		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(close()));
293		connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
294	}
295	m_gifView->show();
296}
297#endif
298
299#ifdef USE_GDB_STUB
300void Window::gdbOpen() {
301	if (!m_gdbController) {
302		m_gdbController = new GDBController(m_controller, this);
303	}
304	GDBWindow* window = new GDBWindow(m_gdbController);
305	connect(this, SIGNAL(shutdown()), window, SLOT(close()));
306	window->setAttribute(Qt::WA_DeleteOnClose);
307	window->show();
308}
309#endif
310
311void Window::keyPressEvent(QKeyEvent* event) {
312	if (event->isAutoRepeat()) {
313		QWidget::keyPressEvent(event);
314		return;
315	}
316	GBAKey key = m_inputController.mapKeyboard(event->key());
317	if (key == GBA_KEY_NONE) {
318		QWidget::keyPressEvent(event);
319		return;
320	}
321	m_controller->keyPressed(key);
322	event->accept();
323}
324
325void Window::keyReleaseEvent(QKeyEvent* event) {
326	if (event->isAutoRepeat()) {
327		QWidget::keyReleaseEvent(event);
328		return;
329	}
330	GBAKey key = m_inputController.mapKeyboard(event->key());
331	if (key == GBA_KEY_NONE) {
332		QWidget::keyPressEvent(event);
333		return;
334	}
335	m_controller->keyReleased(key);
336	event->accept();
337}
338
339void Window::resizeEvent(QResizeEvent*) {
340	m_config->setOption("height", m_screenWidget->height());
341	m_config->setOption("width", m_screenWidget->width());
342}
343
344void Window::closeEvent(QCloseEvent* event) {
345	emit shutdown();
346	QMainWindow::closeEvent(event);
347}
348
349void Window::focusOutEvent(QFocusEvent*) {
350	m_controller->setTurbo(false, false);
351	m_controller->clearKeys();
352}
353
354void Window::dragEnterEvent(QDragEnterEvent* event) {
355	if (event->mimeData()->hasFormat("text/uri-list")) {
356		event->acceptProposedAction();
357	}
358}
359
360void Window::dropEvent(QDropEvent* event) {
361	QString uris = event->mimeData()->data("text/uri-list");
362	uris = uris.trimmed();
363	if (uris.contains("\n")) {
364		// Only one file please
365		return;
366	}
367	QUrl url(uris);
368	if (!url.isLocalFile()) {
369		// No remote loading
370		return;
371	}
372	event->accept();
373	m_controller->loadGame(url.path());
374}
375
376void Window::toggleFullScreen() {
377	if (isFullScreen()) {
378		showNormal();
379		menuBar()->show();
380	} else {
381		showFullScreen();
382#ifndef Q_OS_MAC
383		if (m_controller->isLoaded() && !m_controller->isPaused()) {
384			menuBar()->hide();
385		}
386#endif
387	}
388}
389
390void Window::gameStarted(GBAThread* context) {
391	char title[13] = { '\0' };
392	MutexLock(&context->stateMutex);
393	if (context->state < THREAD_EXITING) {
394		emit startDrawing(m_controller->drawContext(), context);
395		GBAGetGameTitle(context->gba, title);
396	} else {
397		MutexUnlock(&context->stateMutex);
398		return;
399	}
400	MutexUnlock(&context->stateMutex);
401	foreach (QAction* action, m_gameActions) {
402		action->setDisabled(false);
403	}
404	appendMRU(context->fname);
405	setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
406	attachWidget(m_display);
407
408#ifndef Q_OS_MAC
409	if(isFullScreen()) {
410		menuBar()->hide();
411	}
412#endif
413
414	m_fpsTimer.start();
415}
416
417void Window::gameStopped() {
418	foreach (QAction* action, m_gameActions) {
419		action->setDisabled(true);
420	}
421	setWindowTitle(tr(PROJECT_NAME));
422	detachWidget(m_display);
423	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
424	m_screenWidget->setPixmap(m_logo);
425
426	m_fpsTimer.stop();
427}
428
429void Window::gameCrashed(const QString& errorMessage) {
430	QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
431		tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
432		QMessageBox::Ok, this,  Qt::Sheet);
433	crash->setAttribute(Qt::WA_DeleteOnClose);
434	crash->show();
435}
436
437void Window::gameFailed() {
438	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
439		tr("Could not load game. Are you sure it's in the correct format?"),
440		QMessageBox::Ok, this,  Qt::Sheet);
441	fail->setAttribute(Qt::WA_DeleteOnClose);
442	fail->show();
443}
444
445void Window::recordFrame() {
446	m_frameList.append(QDateTime::currentDateTime());
447	while (m_frameList.count() > FRAME_LIST_SIZE) {
448		m_frameList.removeFirst();
449	}
450}
451
452void Window::showFPS() {
453	char title[13] = { '\0' };
454	GBAGetGameTitle(m_controller->thread()->gba, title);
455	if (m_frameList.isEmpty()) {
456		setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
457		return;
458	}
459	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
460	float fps = (m_frameList.count() - 1) * 10000.f / interval;
461	fps = round(fps) / 10.f;
462	setWindowTitle(tr(PROJECT_NAME " - %1 (%2 fps)").arg(title).arg(fps));
463}
464
465void Window::openStateWindow(LoadSave ls) {
466	if (m_stateWindow) {
467		return;
468	}
469	bool wasPaused = m_controller->isPaused();
470	m_stateWindow = new LoadSaveState(m_controller);
471	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
472	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
473	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
474		m_screenWidget->layout()->removeWidget(m_stateWindow);
475		m_stateWindow = nullptr;
476		setFocus();
477	});
478	if (!wasPaused) {
479		m_controller->setPaused(true);
480		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
481	}
482	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
483	m_stateWindow->setMode(ls);
484	attachWidget(m_stateWindow);
485}
486
487void Window::setupMenu(QMenuBar* menubar) {
488	menubar->clear();
489	QMenu* fileMenu = menubar->addMenu(tr("&File"));
490	m_shortcutController->addMenu(fileMenu);
491	installEventFilter(m_shortcutController);
492	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open), "loadROM");
493	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
494	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
495
496	m_mruMenu = fileMenu->addMenu(tr("Recent"));
497
498	fileMenu->addSeparator();
499
500	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
501	loadState->setShortcut(tr("F10"));
502	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
503	m_gameActions.append(loadState);
504	addControlledAction(fileMenu, loadState, "loadState");
505
506	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
507	saveState->setShortcut(tr("Shift+F10"));
508	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
509	m_gameActions.append(saveState);
510	addControlledAction(fileMenu, saveState, "saveState");
511
512	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
513	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
514	int i;
515	for (i = 1; i < 10; ++i) {
516		QAction* quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
517		quickLoad->setShortcut(tr("F%1").arg(i));
518		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
519		m_gameActions.append(quickLoad);
520		addAction(quickLoad);
521		quickLoadMenu->addAction(quickLoad);
522
523		QAction* quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
524		quickSave->setShortcut(tr("Shift+F%1").arg(i));
525		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
526		m_gameActions.append(quickSave);
527		addAction(quickSave);
528		quickSaveMenu->addAction(quickSave);
529	}
530
531	fileMenu->addSeparator();
532	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
533	connect(multiWindow, &QAction::triggered, [this]() {
534		std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
535		if (!multiplayer) {
536			multiplayer = std::make_shared<MultiplayerController>();
537			m_controller->setMultiplayerController(multiplayer);
538		}
539		Window* w2 = new Window(m_config, multiplayer->attached());
540		w2->setAttribute(Qt::WA_DeleteOnClose);
541		w2->loadConfig();
542		w2->controller()->setMultiplayerController(multiplayer);
543		w2->show();
544	});
545	addControlledAction(fileMenu, multiWindow, "multiWindow");
546
547#ifndef Q_OS_MAC
548	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
549#endif
550
551	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
552	m_shortcutController->addMenu(emulationMenu);
553	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
554	reset->setShortcut(tr("Ctrl+R"));
555	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
556	m_gameActions.append(reset);
557	addControlledAction(emulationMenu, reset, "reset");
558
559	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
560	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
561	m_gameActions.append(shutdown);
562	addControlledAction(emulationMenu, shutdown, "shutdown");
563	emulationMenu->addSeparator();
564
565	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
566	pause->setChecked(false);
567	pause->setCheckable(true);
568	pause->setShortcut(tr("Ctrl+P"));
569	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
570	connect(m_controller, &GameController::gamePaused, [this, pause]() {
571		pause->setChecked(true);
572
573		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
574		QPixmap pixmap;
575		pixmap.convertFromImage(currentImage.rgbSwapped());
576		m_screenWidget->setPixmap(pixmap);
577		m_screenWidget->setLockAspectRatio(3, 2);
578	});
579	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
580	m_gameActions.append(pause);
581	addControlledAction(emulationMenu, pause, "pause");
582
583	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
584	frameAdvance->setShortcut(tr("Ctrl+N"));
585	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
586	m_gameActions.append(frameAdvance);
587	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
588
589	emulationMenu->addSeparator();
590
591	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
592	turbo->setCheckable(true);
593	turbo->setChecked(false);
594	turbo->setShortcut(tr("Shift+Tab"));
595	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
596	addControlledAction(emulationMenu, turbo, "fastForward");
597
598	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
599	rewind->setShortcut(tr("`"));
600	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
601	m_gameActions.append(rewind);
602	addControlledAction(emulationMenu, rewind, "rewind");
603
604	ConfigOption* videoSync = m_config->addOption("videoSync");
605	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
606	videoSync->connect([this](const QVariant& value) {
607		m_controller->setVideoSync(value.toBool());
608	}, this);
609	m_config->updateOption("videoSync");
610
611	ConfigOption* audioSync = m_config->addOption("audioSync");
612	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
613	audioSync->connect([this](const QVariant& value) {
614		m_controller->setAudioSync(value.toBool());
615	}, this);
616	m_config->updateOption("audioSync");
617
618	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
619	m_shortcutController->addMenu(avMenu);
620	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
621	m_shortcutController->addMenu(frameMenu, avMenu);
622	for (int i = 1; i <= 6; ++i) {
623		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
624		connect(setSize, &QAction::triggered, [this, i]() {
625			showNormal();
626			resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
627		});
628		addControlledAction(frameMenu, setSize, tr("frame%1x").arg(QString::number(i)));
629	}
630	addControlledAction(frameMenu, frameMenu->addAction(tr("Fullscreen"), this, SLOT(toggleFullScreen()), QKeySequence("Ctrl+F")), "fullscreen");
631
632	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
633	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
634	lockAspectRatio->connect([this](const QVariant& value) {
635		m_display->lockAspectRatio(value.toBool());
636	}, this);
637	m_config->updateOption("lockAspectRatio");
638
639	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
640	resampleVideo->addBoolean(tr("Resample video"), avMenu);
641	resampleVideo->connect([this](const QVariant& value) {
642		m_display->filter(value.toBool());
643	}, this);
644	m_config->updateOption("resampleVideo");
645
646	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
647	ConfigOption* skip = m_config->addOption("frameskip");
648	skip->connect([this](const QVariant& value) {
649		m_controller->setFrameskip(value.toInt());
650	}, this);
651	for (int i = 0; i <= 10; ++i) {
652		skip->addValue(QString::number(i), i, skipMenu);
653	}
654	m_config->updateOption("frameskip");
655
656	avMenu->addSeparator();
657
658	QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
659	ConfigOption* buffers = m_config->addOption("audioBuffers");
660	buffers->connect([this](const QVariant& value) {
661		emit audioBufferSamplesChanged(value.toInt());
662	}, this);
663	buffers->addValue(tr("512"), 512, buffersMenu);
664	buffers->addValue(tr("768"), 768, buffersMenu);
665	buffers->addValue(tr("1024"), 1024, buffersMenu);
666	buffers->addValue(tr("2048"), 2048, buffersMenu);
667	buffers->addValue(tr("4096"), 4096, buffersMenu);
668	m_config->updateOption("audioBuffers");
669
670	avMenu->addSeparator();
671
672	QMenu* target = avMenu->addMenu("FPS target");
673	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
674	fpsTargetOption->connect([this](const QVariant& value) {
675		emit fpsTargetChanged(value.toInt());
676	}, this);
677	fpsTargetOption->addValue(tr("15"), 15, target);
678	fpsTargetOption->addValue(tr("30"), 30, target);
679	fpsTargetOption->addValue(tr("45"), 45, target);
680	fpsTargetOption->addValue(tr("60"), 60, target);
681	fpsTargetOption->addValue(tr("90"), 90, target);
682	fpsTargetOption->addValue(tr("120"), 120, target);
683	fpsTargetOption->addValue(tr("240"), 240, target);
684	m_config->updateOption("fpsTarget");
685
686#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
687	avMenu->addSeparator();
688#endif
689
690#ifdef USE_PNG
691	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
692	screenshot->setShortcut(tr("F12"));
693	connect(screenshot, SIGNAL(triggered()), m_display, SLOT(screenshot()));
694	m_gameActions.append(screenshot);
695	addControlledAction(avMenu, screenshot, "screenshot");
696#endif
697
698#ifdef USE_FFMPEG
699	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
700	recordOutput->setShortcut(tr("F11"));
701	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
702	addControlledAction(avMenu, recordOutput, "recordOutput");
703#endif
704
705#ifdef USE_MAGICK
706	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
707	recordGIF->setShortcut(tr("Shift+F11"));
708	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
709	addControlledAction(avMenu, recordGIF, "recordGIF");
710#endif
711
712	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
713	m_shortcutController->addMenu(toolsMenu);
714	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
715	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
716	addControlledAction(toolsMenu, viewLogs, "viewLogs");
717
718	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
719	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
720	addControlledAction(toolsMenu, overrides, "overrideWindow");
721
722	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
723	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
724	addControlledAction(toolsMenu, sensors, "sensorWindow");
725
726	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
727	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
728	addControlledAction(toolsMenu, cheats, "cheatsWindow");
729
730#ifdef USE_GDB_STUB
731	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
732	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
733	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
734#endif
735
736	QMenu* solarMenu = toolsMenu->addMenu(tr("Solar sensor"));
737	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
738	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
739	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
740
741	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
742	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
743	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
744
745	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
746	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
747	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
748
749	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
750	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
751	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
752
753	toolsMenu->addSeparator();
754	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())), "settings");
755	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())), "shortcuts");
756
757	QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
758	connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
759	addControlledAction(toolsMenu, keymap, "remapKeyboard");
760
761#ifdef BUILD_SDL
762	QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
763	connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
764	addControlledAction(toolsMenu, gamepad, "remapGamepad");
765#endif
766
767	ConfigOption* skipBios = m_config->addOption("skipBios");
768	skipBios->connect([this](const QVariant& value) {
769		m_controller->setSkipBIOS(value.toBool());
770	}, this);
771
772	ConfigOption* useBios = m_config->addOption("useBios");
773	useBios->connect([this](const QVariant& value) { m_controller->setUseBIOS(value.toBool()); });
774
775	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
776	rewindEnable->connect([this](const QVariant& value) {
777		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
778	}, this);
779
780	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
781	rewindBufferCapacity->connect([this](const QVariant& value) {
782		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
783	}, this);
784
785	ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
786	rewindBufferInterval->connect([this](const QVariant& value) {
787		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
788	}, this);
789
790	QMenu* other = new QMenu(tr("Other"), this);
791	m_shortcutController->addMenu(other);
792	m_shortcutController->addFunctions(other, [this]() {
793		m_controller->setTurbo(true, false);
794	}, [this]() {
795		m_controller->setTurbo(false, false);
796	}, QKeySequence(Qt::Key_Tab), tr("Fast Forward (held)"), "holdFastForward");
797
798	foreach (QAction* action, m_gameActions) {
799		action->setDisabled(true);
800	}
801}
802
803void Window::attachWidget(QWidget* widget) {
804	m_screenWidget->layout()->addWidget(widget);
805	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
806}
807
808void Window::detachWidget(QWidget* widget) {
809	m_screenWidget->layout()->removeWidget(widget);
810}
811
812void Window::appendMRU(const QString& fname) {
813	int index = m_mruFiles.indexOf(fname);
814	if (index >= 0) {
815		m_mruFiles.removeAt(index);
816	}
817	m_mruFiles.prepend(fname);
818	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
819		m_mruFiles.removeLast();
820	}
821	updateMRU();
822}
823
824void Window::updateMRU() {
825	if (!m_mruMenu) {
826		return;
827	}
828	m_mruMenu->clear();
829	int i = 0;
830	for (const QString& file : m_mruFiles) {
831		QAction* item = new QAction(file, m_mruMenu);
832		item->setShortcut(QString("Ctrl+%1").arg(i));
833		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
834		m_mruMenu->addAction(item);
835		++i;
836	}
837	m_config->setMRU(m_mruFiles);
838	m_config->write();
839	m_mruMenu->setEnabled(i > 0);
840}
841
842QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
843	m_shortcutController->addAction(menu, action, name);
844	menu->addAction(action);
845	addAction(action);
846	return action;
847}
848
849WindowBackground::WindowBackground(QWidget* parent)
850	: QLabel(parent)
851{
852	setLayout(new QStackedLayout());
853	layout()->setContentsMargins(0, 0, 0, 0);
854	setAlignment(Qt::AlignCenter);
855}
856
857void WindowBackground::setSizeHint(const QSize& hint) {
858	m_sizeHint = hint;
859}
860
861QSize WindowBackground::sizeHint() const {
862	return m_sizeHint;
863}
864
865void WindowBackground::setLockAspectRatio(int width, int height) {
866	m_aspectWidth = width;
867	m_aspectHeight = height;
868}
869
870void WindowBackground::paintEvent(QPaintEvent*) {
871	QPainter painter(this);
872	painter.setRenderHint(QPainter::SmoothPixmapTransform);
873	const QPixmap* logo = pixmap();
874	painter.fillRect(QRect(QPoint(), size()), Qt::black);
875	if (!logo) {
876		return;
877	}
878	QSize s = size();
879	QSize ds = s;
880	if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
881		ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
882	} else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
883		ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
884	}
885	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
886	QRect full(origin, ds);
887	painter.drawPixmap(full, *logo);
888}