all repos — mgba @ d0e1a5d5d2383a3e1a423fdcccc333b7c7302cca

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