all repos — mgba @ d3ebcda24b2515111d1a75c9717ef87c91b31558

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