all repos — mgba @ e1a8befcbb4cd4f7b5f5239563f4a3e1d49dfd5f

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