all repos — mgba @ 003a21b13d8d563509de5d20966b7c03b14c626f

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 <QDesktopWidget>
   9#include <QKeyEvent>
  10#include <QKeySequence>
  11#include <QMenuBar>
  12#include <QMessageBox>
  13#include <QMimeData>
  14#include <QPainter>
  15#include <QStackedLayout>
  16
  17#include "AboutScreen.h"
  18#include "CheatsView.h"
  19#include "ConfigController.h"
  20#include "Display.h"
  21#include "GameController.h"
  22#include "GBAApp.h"
  23#include "GBAKeyEditor.h"
  24#include "GDBController.h"
  25#include "GDBWindow.h"
  26#include "GIFView.h"
  27#include "LoadSaveState.h"
  28#include "LogView.h"
  29#include "MultiplayerController.h"
  30#include "MemoryView.h"
  31#include "OverrideView.h"
  32#include "PaletteView.h"
  33#include "SensorView.h"
  34#include "SettingsView.h"
  35#include "ShortcutController.h"
  36#include "ShortcutView.h"
  37#include "VideoView.h"
  38
  39extern "C" {
  40#include "platform/commandline.h"
  41}
  42
  43using namespace QGBA;
  44
  45#if defined(__WIN32) || defined(__OpenBSD__)
  46// This is a macro everywhere except MinGW and OpenBSD, it seems
  47using std::isnan;
  48#endif
  49
  50Window::Window(ConfigController* config, int playerId, QWidget* parent)
  51	: QMainWindow(parent)
  52	, m_log(0)
  53	, m_logView(new LogView(&m_log))
  54	, m_stateWindow(nullptr)
  55	, m_screenWidget(new WindowBackground())
  56	, m_logo(":/res/mgba-1024.png")
  57	, m_config(config)
  58	, m_inputController(playerId, this)
  59#ifdef USE_FFMPEG
  60	, m_videoView(nullptr)
  61#endif
  62#ifdef USE_MAGICK
  63	, m_gifView(nullptr)
  64#endif
  65#ifdef USE_GDB_STUB
  66	, m_gdbController(nullptr)
  67#endif
  68	, m_mruMenu(nullptr)
  69	, m_shortcutController(new ShortcutController(this))
  70	, m_playerId(playerId)
  71{
  72	setFocusPolicy(Qt::StrongFocus);
  73	setAcceptDrops(true);
  74	setAttribute(Qt::WA_DeleteOnClose);
  75	m_controller = new GameController(this);
  76	m_controller->setInputController(&m_inputController);
  77	m_controller->setOverrides(m_config->overrides());
  78	updateTitle();
  79
  80	m_display = Display::create(this);
  81
  82	m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
  83	m_logo = m_logo; // Free memory left over in old pixmap
  84
  85	m_screenWidget->setMinimumSize(m_display->minimumSize());
  86	m_screenWidget->setSizePolicy(m_display->sizePolicy());
  87	m_screenWidget->setSizeHint(m_display->minimumSize() * 2);
  88	m_screenWidget->setPixmap(m_logo);
  89	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
  90	setCentralWidget(m_screenWidget);
  91
  92	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));
  93	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
  94	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_display, SLOT(stopDrawing()));
  95	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), this, SLOT(gameStopped()));
  96	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
  97	connect(m_controller, SIGNAL(stateLoaded(GBAThread*)), m_display, SLOT(forceDraw()));
  98	connect(m_controller, SIGNAL(rewound(GBAThread*)), m_display, SLOT(forceDraw()));
  99	connect(m_controller, &GameController::gamePaused, [this]() {
 100		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS,
 101		                    VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGBX8888);
 102		QPixmap pixmap;
 103		pixmap.convertFromImage(currentImage);
 104		m_screenWidget->setPixmap(pixmap);
 105		m_screenWidget->setLockAspectRatio(3, 2);
 106	});
 107	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), m_display, SLOT(pauseDrawing()));
 108#ifndef Q_OS_MAC
 109	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), menuBar(), SLOT(show()));
 110	connect(m_controller, &GameController::gameUnpaused, [this]() {
 111		if(isFullScreen()) {
 112			menuBar()->hide();
 113		}
 114	});
 115#endif
 116	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
 117	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), m_display, SLOT(unpauseDrawing()));
 118	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
 119	connect(m_controller, SIGNAL(postLog(int, const QString&)), &m_log, SLOT(postLog(int, const QString&)));
 120	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
 121	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), m_display, SLOT(framePosted(const uint32_t*)));
 122	connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
 123	connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
 124	connect(m_controller, SIGNAL(unimplementedBiosCall(int)), this, SLOT(unimplementedBiosCall(int)));
 125	connect(m_controller, SIGNAL(statusPosted(const QString&)), m_display, SLOT(showMessage(const QString&)));
 126	connect(&m_log, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
 127	connect(&m_log, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
 128	connect(&m_log, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
 129	connect(this, SIGNAL(startDrawing(GBAThread*)), m_display, SLOT(startDrawing(GBAThread*)), Qt::QueuedConnection);
 130	connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
 131	connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
 132	connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
 133	connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
 134	connect(this, SIGNAL(sampleRateChanged(unsigned)), m_controller, SLOT(setAudioSampleRate(unsigned)));
 135	connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
 136	connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));
 137	connect(m_display, &Display::hideCursor, [this]() {
 138		if (static_cast<QStackedLayout*>(m_screenWidget->layout())->currentWidget() == m_display) {
 139			m_screenWidget->setCursor(Qt::BlankCursor);
 140		}
 141	});
 142	connect(m_display, &Display::showCursor, [this]() {
 143		m_screenWidget->unsetCursor();
 144	});
 145	connect(&m_inputController, SIGNAL(profileLoaded(const QString&)), m_shortcutController, SLOT(loadProfile(const QString&)));
 146
 147	m_log.setLevels(GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL | GBA_LOG_STATUS);
 148	m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
 149
 150	m_shortcutController->setConfigController(m_config);
 151	setupMenu(menuBar());
 152}
 153
 154Window::~Window() {
 155	delete m_logView;
 156
 157#ifdef USE_FFMPEG
 158	delete m_videoView;
 159#endif
 160
 161#ifdef USE_MAGICK
 162	delete m_gifView;
 163#endif
 164}
 165
 166void Window::argumentsPassed(GBAArguments* args) {
 167	loadConfig();
 168
 169	if (args->patch) {
 170		m_controller->loadPatch(args->patch);
 171	}
 172
 173	if (args->fname) {
 174		m_controller->loadGame(args->fname, args->dirmode);
 175	}
 176}
 177
 178void Window::resizeFrame(int width, int height) {
 179	QSize newSize(width, height);
 180	m_screenWidget->setSizeHint(newSize);
 181	newSize -= m_screenWidget->size();
 182	newSize += size();
 183	resize(newSize);
 184}
 185
 186void Window::setConfig(ConfigController* config) {
 187	m_config = config;
 188}
 189
 190void Window::loadConfig() {
 191	const GBAOptions* opts = m_config->options();
 192
 193	m_log.setLevels(opts->logLevel);
 194
 195	m_controller->setOptions(opts);
 196	m_display->lockAspectRatio(opts->lockAspectRatio);
 197	m_display->filter(opts->resampleVideo);
 198
 199	if (opts->bios) {
 200		m_controller->loadBIOS(opts->bios);
 201	}
 202
 203	// TODO: Move these to ConfigController
 204	if (opts->fpsTarget) {
 205		emit fpsTargetChanged(opts->fpsTarget);
 206	}
 207
 208	if (opts->audioBuffers) {
 209		emit audioBufferSamplesChanged(opts->audioBuffers);
 210	}
 211
 212	if (opts->sampleRate) {
 213		emit sampleRateChanged(opts->sampleRate);
 214	}
 215
 216	if (opts->width && opts->height) {
 217		resizeFrame(opts->width, opts->height);
 218	}
 219
 220	if (opts->fullscreen) {
 221		enterFullScreen();
 222	}
 223
 224	m_inputController.setScreensaverSuspendable(opts->suspendScreensaver);
 225
 226	m_mruFiles = m_config->getMRU();
 227	updateMRU();
 228
 229	m_inputController.setConfiguration(m_config);
 230}
 231
 232void Window::saveConfig() {
 233	m_inputController.saveConfiguration();
 234	m_config->write();
 235}
 236
 237void Window::selectROM() {
 238	QStringList formats{
 239		"*.gba",
 240#ifdef USE_LIBZIP
 241		"*.zip",
 242#endif
 243#ifdef USE_LZMA
 244		"*.7z",
 245#endif
 246		"*.rom",
 247		"*.bin"};
 248	QString filter = tr("Game Boy Advance ROMs (%1)").arg(formats.join(QChar(' ')));
 249	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), filter);
 250	if (!filename.isEmpty()) {
 251		m_controller->loadGame(filename);
 252	}
 253}
 254
 255void Window::replaceROM() {
 256	QStringList formats{
 257		"*.gba",
 258#ifdef USE_LIBZIP
 259		"*.zip",
 260#endif
 261#ifdef USE_LZMA
 262		"*.7z",
 263#endif
 264		"*.rom",
 265		"*.bin"};
 266	QString filter = tr("Game Boy Advance ROMs (%1)").arg(formats.join(QChar(' ')));
 267	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), filter);
 268	if (!filename.isEmpty()) {
 269		m_controller->replaceGame(filename);
 270	}
 271}
 272
 273void Window::selectBIOS() {
 274	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select BIOS"));
 275	if (!filename.isEmpty()) {
 276		m_config->setOption("bios", filename);
 277		m_config->updateOption("bios");
 278		m_config->setOption("useBios", true);
 279		m_config->updateOption("useBios");
 280		m_controller->loadBIOS(filename);
 281	}
 282}
 283
 284void Window::selectPatch() {
 285	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select patch"), tr("Patches (*.ips *.ups *.bps)"));
 286	if (!filename.isEmpty()) {
 287		m_controller->loadPatch(filename);
 288	}
 289}
 290
 291void Window::openView(QWidget* widget) {
 292	connect(this, SIGNAL(shutdown()), widget, SLOT(close()));
 293	widget->setAttribute(Qt::WA_DeleteOnClose);
 294	widget->show();
 295}
 296
 297void Window::importSharkport() {
 298	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
 299	if (!filename.isEmpty()) {
 300		m_controller->importSharkport(filename);
 301	}
 302}
 303
 304void Window::exportSharkport() {
 305	QString filename = GBAApp::app()->getSaveFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
 306	if (!filename.isEmpty()) {
 307		m_controller->exportSharkport(filename);
 308	}
 309}
 310
 311void Window::openKeymapWindow() {
 312	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, InputController::KEYBOARD);
 313	openView(keyEditor);
 314}
 315
 316void Window::openSettingsWindow() {
 317	SettingsView* settingsWindow = new SettingsView(m_config);
 318	connect(settingsWindow, SIGNAL(biosLoaded(const QString&)), m_controller, SLOT(loadBIOS(const QString&)));
 319	connect(settingsWindow, SIGNAL(audioDriverChanged()), m_controller, SLOT(reloadAudioDriver()));
 320	connect(settingsWindow, SIGNAL(displayDriverChanged()), this, SLOT(mustRestart()));
 321	openView(settingsWindow);
 322}
 323
 324void Window::openShortcutWindow() {
 325#ifdef BUILD_SDL
 326	m_inputController.recalibrateAxes();
 327#endif
 328	ShortcutView* shortcutView = new ShortcutView();
 329	shortcutView->setController(m_shortcutController);
 330	shortcutView->setInputController(&m_inputController);
 331	openView(shortcutView);
 332}
 333
 334void Window::openOverrideWindow() {
 335	OverrideView* overrideWindow = new OverrideView(m_controller, m_config);
 336	openView(overrideWindow);
 337}
 338
 339void Window::openSensorWindow() {
 340	SensorView* sensorWindow = new SensorView(m_controller, &m_inputController);
 341	openView(sensorWindow);
 342}
 343
 344void Window::openCheatsWindow() {
 345	CheatsView* cheatsWindow = new CheatsView(m_controller);
 346	openView(cheatsWindow);
 347}
 348
 349void Window::openPaletteWindow() {
 350	PaletteView* paletteWindow = new PaletteView(m_controller);
 351	openView(paletteWindow);
 352}
 353
 354void Window::openMemoryWindow() {
 355	MemoryView* memoryWindow = new MemoryView(m_controller);
 356	openView(memoryWindow);
 357}
 358
 359void Window::openAboutScreen() {
 360	AboutScreen* about = new AboutScreen();
 361	openView(about);
 362}
 363
 364#ifdef BUILD_SDL
 365void Window::openGamepadWindow() {
 366	const char* profile = m_inputController.profileForType(SDL_BINDING_BUTTON);
 367	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, SDL_BINDING_BUTTON, profile);
 368	openView(keyEditor);
 369}
 370#endif
 371
 372#ifdef USE_FFMPEG
 373void Window::openVideoWindow() {
 374	if (!m_videoView) {
 375		m_videoView = new VideoView();
 376		connect(m_videoView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 377		connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 378		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(stopRecording()));
 379		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(close()));
 380		connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
 381	}
 382	m_videoView->show();
 383}
 384#endif
 385
 386#ifdef USE_MAGICK
 387void Window::openGIFWindow() {
 388	if (!m_gifView) {
 389		m_gifView = new GIFView();
 390		connect(m_gifView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 391		connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 392		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(stopRecording()));
 393		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(close()));
 394		connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
 395	}
 396	m_gifView->show();
 397}
 398#endif
 399
 400#ifdef USE_GDB_STUB
 401void Window::gdbOpen() {
 402	if (!m_gdbController) {
 403		m_gdbController = new GDBController(m_controller, this);
 404	}
 405	GDBWindow* window = new GDBWindow(m_gdbController);
 406	openView(window);
 407}
 408#endif
 409
 410void Window::keyPressEvent(QKeyEvent* event) {
 411	if (event->isAutoRepeat()) {
 412		QWidget::keyPressEvent(event);
 413		return;
 414	}
 415	GBAKey key = m_inputController.mapKeyboard(event->key());
 416	if (key == GBA_KEY_NONE) {
 417		QWidget::keyPressEvent(event);
 418		return;
 419	}
 420	m_controller->keyPressed(key);
 421	event->accept();
 422}
 423
 424void Window::keyReleaseEvent(QKeyEvent* event) {
 425	if (event->isAutoRepeat()) {
 426		QWidget::keyReleaseEvent(event);
 427		return;
 428	}
 429	GBAKey key = m_inputController.mapKeyboard(event->key());
 430	if (key == GBA_KEY_NONE) {
 431		QWidget::keyPressEvent(event);
 432		return;
 433	}
 434	m_controller->keyReleased(key);
 435	event->accept();
 436}
 437
 438void Window::resizeEvent(QResizeEvent* event) {
 439	if (!isFullScreen()) {
 440		m_config->setOption("height", m_screenWidget->height());
 441		m_config->setOption("width", m_screenWidget->width());
 442	}
 443
 444	int factor = 0;
 445	if (event->size().width() % VIDEO_HORIZONTAL_PIXELS == 0 && event->size().height() % VIDEO_VERTICAL_PIXELS == 0 &&
 446	    event->size().width() / VIDEO_HORIZONTAL_PIXELS == event->size().height() / VIDEO_VERTICAL_PIXELS) {
 447		factor = event->size().width() / VIDEO_HORIZONTAL_PIXELS;
 448	}
 449	for (QMap<int, QAction*>::iterator iter = m_frameSizes.begin(); iter != m_frameSizes.end(); ++iter) {
 450		bool enableSignals = iter.value()->blockSignals(true);
 451		if (iter.key() == factor) {
 452			iter.value()->setChecked(true);
 453		} else {
 454			iter.value()->setChecked(false);
 455		}
 456		iter.value()->blockSignals(enableSignals);
 457	}
 458
 459	m_config->setOption("fullscreen", isFullScreen());
 460}
 461
 462void Window::showEvent(QShowEvent* event) {
 463	resizeFrame(m_screenWidget->sizeHint().width(), m_screenWidget->sizeHint().height());
 464	QVariant windowPos = m_config->getQtOption("windowPos");
 465	if (!windowPos.isNull()) {
 466		move(windowPos.toPoint());
 467	} else {
 468		QRect rect = frameGeometry();
 469		rect.moveCenter(QApplication::desktop()->availableGeometry().center());
 470		move(rect.topLeft());
 471	}
 472}
 473
 474void Window::closeEvent(QCloseEvent* event) {
 475	emit shutdown();
 476	m_config->setQtOption("windowPos", pos());
 477	saveConfig();
 478	QMainWindow::closeEvent(event);
 479}
 480
 481void Window::focusInEvent(QFocusEvent*) {
 482	m_display->forceDraw();
 483}
 484
 485void Window::focusOutEvent(QFocusEvent*) {
 486	m_controller->setTurbo(false, false);
 487	m_controller->stopRewinding();
 488	m_controller->clearKeys();
 489}
 490
 491void Window::dragEnterEvent(QDragEnterEvent* event) {
 492	if (event->mimeData()->hasFormat("text/uri-list")) {
 493		event->acceptProposedAction();
 494	}
 495}
 496
 497void Window::dropEvent(QDropEvent* event) {
 498	QString uris = event->mimeData()->data("text/uri-list");
 499	uris = uris.trimmed();
 500	if (uris.contains("\n")) {
 501		// Only one file please
 502		return;
 503	}
 504	QUrl url(uris);
 505	if (!url.isLocalFile()) {
 506		// No remote loading
 507		return;
 508	}
 509	event->accept();
 510	m_controller->loadGame(url.path());
 511}
 512
 513void Window::mouseDoubleClickEvent(QMouseEvent* event) {
 514	if (event->button() != Qt::LeftButton) {
 515		return;
 516	}
 517	toggleFullScreen();
 518}
 519
 520void Window::enterFullScreen() {
 521	if (isFullScreen()) {
 522		return;
 523	}
 524	showFullScreen();
 525#ifndef Q_OS_MAC
 526	if (m_controller->isLoaded() && !m_controller->isPaused()) {
 527		menuBar()->hide();
 528	}
 529#endif
 530}
 531
 532void Window::exitFullScreen() {
 533	if (!isFullScreen()) {
 534		return;
 535	}
 536	m_screenWidget->unsetCursor();
 537	menuBar()->show();
 538	showNormal();
 539}
 540
 541void Window::toggleFullScreen() {
 542	if (isFullScreen()) {
 543		exitFullScreen();
 544	} else {
 545		enterFullScreen();
 546	}
 547}
 548
 549void Window::gameStarted(GBAThread* context) {
 550	char title[13] = { '\0' };
 551	MutexLock(&context->stateMutex);
 552	if (context->state < THREAD_EXITING) {
 553		emit startDrawing(context);
 554		GBAGetGameTitle(context->gba, title);
 555	} else {
 556		MutexUnlock(&context->stateMutex);
 557		return;
 558	}
 559	MutexUnlock(&context->stateMutex);
 560	foreach (QAction* action, m_gameActions) {
 561		action->setDisabled(false);
 562	}
 563	if (context->fname) {
 564		setWindowFilePath(context->fname);
 565		appendMRU(context->fname);
 566	}
 567	updateTitle();
 568	attachWidget(m_display);
 569
 570#ifndef Q_OS_MAC
 571	if (isFullScreen()) {
 572		menuBar()->hide();
 573	}
 574#endif
 575
 576	m_hitUnimplementedBiosCall = false;
 577	m_fpsTimer.start();
 578}
 579
 580void Window::gameStopped() {
 581	foreach (QAction* action, m_gameActions) {
 582		action->setDisabled(true);
 583	}
 584	setWindowFilePath(QString());
 585	updateTitle();
 586	detachWidget(m_display);
 587	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
 588	m_screenWidget->setPixmap(m_logo);
 589	m_screenWidget->unsetCursor();
 590
 591	m_fpsTimer.stop();
 592}
 593
 594void Window::gameCrashed(const QString& errorMessage) {
 595	QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
 596	                                     tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
 597	                                     QMessageBox::Ok, this, Qt::Sheet);
 598	crash->setAttribute(Qt::WA_DeleteOnClose);
 599	crash->show();
 600}
 601
 602void Window::gameFailed() {
 603	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
 604	                                    tr("Could not load game. Are you sure it's in the correct format?"),
 605	                                    QMessageBox::Ok, this, Qt::Sheet);
 606	fail->setAttribute(Qt::WA_DeleteOnClose);
 607	fail->show();
 608}
 609
 610void Window::unimplementedBiosCall(int call) {
 611	if (m_hitUnimplementedBiosCall) {
 612		return;
 613	}
 614	m_hitUnimplementedBiosCall = true;
 615
 616	QMessageBox* fail = new QMessageBox(
 617	    QMessageBox::Warning, tr("Unimplemented BIOS call"),
 618	    tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
 619	    QMessageBox::Ok, this, Qt::Sheet);
 620	fail->setAttribute(Qt::WA_DeleteOnClose);
 621	fail->show();
 622}
 623
 624void Window::tryMakePortable() {
 625	QMessageBox* confirm = new QMessageBox(QMessageBox::Question, tr("Really make portable?"),
 626	                                       tr("This will make the emulator load its configuration from the same directory as the executable. Do you want to continue?"),
 627	                                       QMessageBox::Yes | QMessageBox::Cancel, this, Qt::Sheet);
 628	confirm->setAttribute(Qt::WA_DeleteOnClose);
 629	connect(confirm->button(QMessageBox::Yes), SIGNAL(clicked()), m_config, SLOT(makePortable()));
 630	confirm->show();
 631}
 632
 633void Window::mustRestart() {
 634	QMessageBox* dialog = new QMessageBox(QMessageBox::Warning, tr("Restart needed"),
 635	                                      tr("Some changes will not take effect until the emulator is restarted."),
 636	                                      QMessageBox::Ok, this, Qt::Sheet);
 637	dialog->setAttribute(Qt::WA_DeleteOnClose);
 638	dialog->show();
 639}
 640
 641void Window::recordFrame() {
 642	m_frameList.append(QDateTime::currentDateTime());
 643	while (m_frameList.count() > FRAME_LIST_SIZE) {
 644		m_frameList.removeFirst();
 645	}
 646}
 647
 648void Window::showFPS() {
 649	if (m_frameList.isEmpty()) {
 650		updateTitle();
 651		return;
 652	}
 653	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
 654	float fps = (m_frameList.count() - 1) * 10000.f / interval;
 655	fps = round(fps) / 10.f;
 656	updateTitle(fps);
 657}
 658
 659void Window::updateTitle(float fps) {
 660	QString title;
 661
 662	m_controller->threadInterrupt();
 663	if (m_controller->isLoaded()) {
 664		char gameTitle[13] = { '\0' };
 665		GBAGetGameTitle(m_controller->thread()->gba, gameTitle);
 666
 667		title = (gameTitle);
 668	}
 669	MultiplayerController* multiplayer = m_controller->multiplayerController();
 670	if (multiplayer && multiplayer->attached() > 1) {
 671		title += tr(" -  Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
 672	}
 673	m_controller->threadContinue();
 674	if (title.isNull()) {
 675		setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
 676	} else if (isnan(fps)) {
 677		setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
 678	} else {
 679		setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
 680	}
 681}
 682
 683void Window::openStateWindow(LoadSave ls) {
 684	if (m_stateWindow) {
 685		return;
 686	}
 687	bool wasPaused = m_controller->isPaused();
 688	m_stateWindow = new LoadSaveState(m_controller);
 689	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
 690	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
 691	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
 692		detachWidget(m_stateWindow);
 693		m_stateWindow = nullptr;
 694		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
 695	});
 696	if (!wasPaused) {
 697		m_controller->setPaused(true);
 698		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
 699	}
 700	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
 701	m_stateWindow->setMode(ls);
 702	attachWidget(m_stateWindow);
 703}
 704
 705void Window::setupMenu(QMenuBar* menubar) {
 706	menubar->clear();
 707	QMenu* fileMenu = menubar->addMenu(tr("&File"));
 708	m_shortcutController->addMenu(fileMenu);
 709	installEventFilter(m_shortcutController);
 710	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open),
 711	                    "loadROM");
 712	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
 713	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
 714	addControlledAction(fileMenu, fileMenu->addAction(tr("Boot BIOS"), m_controller, SLOT(bootBIOS())), "bootBIOS");
 715
 716	addControlledAction(fileMenu, fileMenu->addAction(tr("Replace ROM..."), this, SLOT(replaceROM())), "replaceROM");
 717
 718	m_mruMenu = fileMenu->addMenu(tr("Recent"));
 719
 720	fileMenu->addSeparator();
 721
 722	addControlledAction(fileMenu, fileMenu->addAction(tr("Make portable"), this, SLOT(tryMakePortable())), "makePortable");
 723
 724	fileMenu->addSeparator();
 725
 726	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
 727	loadState->setShortcut(tr("F10"));
 728	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
 729	m_gameActions.append(loadState);
 730	addControlledAction(fileMenu, loadState, "loadState");
 731
 732	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
 733	saveState->setShortcut(tr("Shift+F10"));
 734	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
 735	m_gameActions.append(saveState);
 736	addControlledAction(fileMenu, saveState, "saveState");
 737
 738	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
 739	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
 740	m_shortcutController->addMenu(quickLoadMenu);
 741	m_shortcutController->addMenu(quickSaveMenu);
 742
 743	QAction* quickLoad = new QAction(tr("Load recent"), quickLoadMenu);
 744	connect(quickLoad, SIGNAL(triggered()), m_controller, SLOT(loadState()));
 745	m_gameActions.append(quickLoad);
 746	addControlledAction(quickLoadMenu, quickLoad, "quickLoad");
 747
 748	QAction* quickSave = new QAction(tr("Save recent"), quickSaveMenu);
 749	connect(quickSave, SIGNAL(triggered()), m_controller, SLOT(saveState()));
 750	m_gameActions.append(quickSave);
 751	addControlledAction(quickSaveMenu, quickSave, "quickSave");
 752
 753	quickLoadMenu->addSeparator();
 754	quickSaveMenu->addSeparator();
 755
 756	QAction* undoLoadState = new QAction(tr("Undo load state"), quickLoadMenu);
 757	undoLoadState->setShortcut(tr("F11"));
 758	connect(undoLoadState, SIGNAL(triggered()), m_controller, SLOT(loadBackupState()));
 759	m_gameActions.append(undoLoadState);
 760	addControlledAction(quickLoadMenu, undoLoadState, "undoLoadState");
 761
 762	QAction* undoSaveState = new QAction(tr("Undo save state"), quickSaveMenu);
 763	undoSaveState->setShortcut(tr("Shift+F11"));
 764	connect(undoSaveState, SIGNAL(triggered()), m_controller, SLOT(saveBackupState()));
 765	m_gameActions.append(undoSaveState);
 766	addControlledAction(quickSaveMenu, undoSaveState, "undoSaveState");
 767
 768	quickLoadMenu->addSeparator();
 769	quickSaveMenu->addSeparator();
 770
 771	int i;
 772	for (i = 1; i < 10; ++i) {
 773		quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
 774		quickLoad->setShortcut(tr("F%1").arg(i));
 775		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
 776		m_gameActions.append(quickLoad);
 777		addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
 778
 779		quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
 780		quickSave->setShortcut(tr("Shift+F%1").arg(i));
 781		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
 782		m_gameActions.append(quickSave);
 783		addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
 784	}
 785
 786	fileMenu->addSeparator();
 787	QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
 788	connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
 789	m_gameActions.append(importShark);
 790	addControlledAction(fileMenu, importShark, "importShark");
 791
 792	QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
 793	connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
 794	m_gameActions.append(exportShark);
 795	addControlledAction(fileMenu, exportShark, "exportShark");
 796
 797	fileMenu->addSeparator();
 798	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
 799	connect(multiWindow, &QAction::triggered, [this]() {
 800		GBAApp::app()->newWindow();
 801	});
 802	addControlledAction(fileMenu, multiWindow, "multiWindow");
 803
 804#ifndef Q_OS_MAC
 805	fileMenu->addSeparator();
 806#endif
 807
 808	QAction* about = new QAction(tr("About"), fileMenu);
 809	connect(about, SIGNAL(triggered()), this, SLOT(openAboutScreen()));
 810	fileMenu->addAction(about);
 811
 812#ifndef Q_OS_MAC
 813	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
 814#endif
 815
 816	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
 817	m_shortcutController->addMenu(emulationMenu);
 818	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
 819	reset->setShortcut(tr("Ctrl+R"));
 820	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
 821	m_gameActions.append(reset);
 822	addControlledAction(emulationMenu, reset, "reset");
 823
 824	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
 825	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
 826	m_gameActions.append(shutdown);
 827	addControlledAction(emulationMenu, shutdown, "shutdown");
 828
 829	QAction* yank = new QAction(tr("Yank game pak"), emulationMenu);
 830	connect(yank, SIGNAL(triggered()), m_controller, SLOT(yankPak()));
 831	m_gameActions.append(yank);
 832	addControlledAction(emulationMenu, yank, "yank");
 833	emulationMenu->addSeparator();
 834
 835	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
 836	pause->setChecked(false);
 837	pause->setCheckable(true);
 838	pause->setShortcut(tr("Ctrl+P"));
 839	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
 840	connect(m_controller, &GameController::gamePaused, [this, pause]() {
 841		pause->setChecked(true);
 842	});
 843	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
 844	m_gameActions.append(pause);
 845	addControlledAction(emulationMenu, pause, "pause");
 846
 847	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
 848	frameAdvance->setShortcut(tr("Ctrl+N"));
 849	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
 850	m_gameActions.append(frameAdvance);
 851	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
 852
 853	emulationMenu->addSeparator();
 854
 855	m_shortcutController->addFunctions(emulationMenu, [this]() {
 856		m_controller->setTurbo(true, false);
 857	}, [this]() {
 858		m_controller->setTurbo(false, false);
 859	}, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
 860
 861	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
 862	turbo->setCheckable(true);
 863	turbo->setChecked(false);
 864	turbo->setShortcut(tr("Shift+Tab"));
 865	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
 866	addControlledAction(emulationMenu, turbo, "fastForward");
 867
 868	QMenu* ffspeedMenu = emulationMenu->addMenu(tr("Fast forward speed"));
 869	ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
 870	ffspeed->connect([this](const QVariant& value) {
 871		m_controller->setTurboSpeed(value.toFloat());
 872	}, this);
 873	ffspeed->addValue(tr("Unbounded"), -1.0f, ffspeedMenu);
 874	ffspeed->setValue(QVariant(-1.0f));
 875	ffspeedMenu->addSeparator();
 876	for (i = 2; i < 11; ++i) {
 877		ffspeed->addValue(tr("%0x").arg(i), i, ffspeedMenu);
 878	}
 879	m_config->updateOption("fastForwardRatio");
 880
 881	m_shortcutController->addFunctions(emulationMenu, [this]() {
 882		m_controller->startRewinding();
 883	}, [this]() {
 884		m_controller->stopRewinding();
 885	}, QKeySequence("~"), tr("Rewind (held)"), "holdRewind");
 886
 887	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
 888	rewind->setShortcut(tr("`"));
 889	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
 890	m_gameActions.append(rewind);
 891	addControlledAction(emulationMenu, rewind, "rewind");
 892
 893	QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
 894	frameRewind->setShortcut(tr("Ctrl+B"));
 895	connect(frameRewind, &QAction::triggered, [this] () {
 896		m_controller->rewind(1);
 897	});
 898	m_gameActions.append(frameRewind);
 899	addControlledAction(emulationMenu, frameRewind, "frameRewind");
 900
 901	ConfigOption* videoSync = m_config->addOption("videoSync");
 902	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
 903	videoSync->connect([this](const QVariant& value) {
 904		m_controller->setVideoSync(value.toBool());
 905	}, this);
 906	m_config->updateOption("videoSync");
 907
 908	ConfigOption* audioSync = m_config->addOption("audioSync");
 909	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
 910	audioSync->connect([this](const QVariant& value) {
 911		m_controller->setAudioSync(value.toBool());
 912	}, this);
 913	m_config->updateOption("audioSync");
 914
 915	emulationMenu->addSeparator();
 916
 917	QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
 918	m_shortcutController->addMenu(solarMenu);
 919	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
 920	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
 921	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
 922
 923	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
 924	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
 925	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
 926
 927	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
 928	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
 929	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
 930
 931	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
 932	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
 933	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
 934
 935	solarMenu->addSeparator();
 936	for (int i = 0; i <= 10; ++i) {
 937		QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
 938		connect(setSolar, &QAction::triggered, [this, i]() {
 939			m_controller->setLuminanceLevel(i);
 940		});
 941		addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
 942	}
 943
 944	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
 945	m_shortcutController->addMenu(avMenu);
 946	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
 947	m_shortcutController->addMenu(frameMenu, avMenu);
 948	for (int i = 1; i <= 6; ++i) {
 949		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
 950		setSize->setCheckable(true);
 951		connect(setSize, &QAction::triggered, [this, i, setSize]() {
 952			showNormal();
 953			resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
 954			bool enableSignals = setSize->blockSignals(true);
 955			setSize->setChecked(true);
 956			setSize->blockSignals(enableSignals);
 957		});
 958		m_frameSizes[i] = setSize;
 959		addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
 960	}
 961	QKeySequence fullscreenKeys;
 962#ifdef Q_OS_WIN
 963	fullscreenKeys = QKeySequence("Alt+Return");
 964#else
 965	fullscreenKeys = QKeySequence("Ctrl+F");
 966#endif
 967	addControlledAction(frameMenu, frameMenu->addAction(tr("Toggle fullscreen"), this, SLOT(toggleFullScreen()), fullscreenKeys), "fullscreen");
 968
 969	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
 970	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
 971	lockAspectRatio->connect([this](const QVariant& value) {
 972		m_display->lockAspectRatio(value.toBool());
 973	}, this);
 974	m_config->updateOption("lockAspectRatio");
 975
 976	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
 977	resampleVideo->addBoolean(tr("Resample video"), avMenu);
 978	resampleVideo->connect([this](const QVariant& value) {
 979		m_display->filter(value.toBool());
 980	}, this);
 981	m_config->updateOption("resampleVideo");
 982
 983	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
 984	ConfigOption* skip = m_config->addOption("frameskip");
 985	skip->connect([this](const QVariant& value) {
 986		m_controller->setFrameskip(value.toInt());
 987	}, this);
 988	for (int i = 0; i <= 10; ++i) {
 989		skip->addValue(QString::number(i), i, skipMenu);
 990	}
 991	m_config->updateOption("frameskip");
 992
 993	avMenu->addSeparator();
 994
 995	QMenu* target = avMenu->addMenu(tr("FPS target"));
 996	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
 997	fpsTargetOption->connect([this](const QVariant& value) {
 998		emit fpsTargetChanged(value.toFloat());
 999	}, this);
1000	fpsTargetOption->addValue(tr("15"), 15, target);
1001	fpsTargetOption->addValue(tr("30"), 30, target);
1002	fpsTargetOption->addValue(tr("45"), 45, target);
1003	fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
1004	fpsTargetOption->addValue(tr("60"), 60, target);
1005	fpsTargetOption->addValue(tr("90"), 90, target);
1006	fpsTargetOption->addValue(tr("120"), 120, target);
1007	fpsTargetOption->addValue(tr("240"), 240, target);
1008	m_config->updateOption("fpsTarget");
1009
1010#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
1011	avMenu->addSeparator();
1012#endif
1013
1014#ifdef USE_PNG
1015	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
1016	screenshot->setShortcut(tr("F12"));
1017	connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
1018	m_gameActions.append(screenshot);
1019	addControlledAction(avMenu, screenshot, "screenshot");
1020#endif
1021
1022#ifdef USE_FFMPEG
1023	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
1024	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
1025	addControlledAction(avMenu, recordOutput, "recordOutput");
1026#endif
1027
1028#ifdef USE_MAGICK
1029	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
1030	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
1031	addControlledAction(avMenu, recordGIF, "recordGIF");
1032#endif
1033
1034	avMenu->addSeparator();
1035	QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
1036
1037	for (int i = 0; i < 4; ++i) {
1038		QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
1039		enableBg->setCheckable(true);
1040		enableBg->setChecked(true);
1041		connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->setVideoLayerEnabled(i, enable); });
1042		addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
1043	}
1044
1045	QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
1046	enableObj->setCheckable(true);
1047	enableObj->setChecked(true);
1048	connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->setVideoLayerEnabled(4, enable); });
1049	addControlledAction(videoLayers, enableObj, "enableOBJ");
1050
1051	QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
1052
1053	for (int i = 0; i < 4; ++i) {
1054		QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
1055		enableCh->setCheckable(true);
1056		enableCh->setChecked(true);
1057		connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(i, enable); });
1058		addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
1059	}
1060
1061	QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
1062	enableChA->setCheckable(true);
1063	enableChA->setChecked(true);
1064	connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(4, enable); });
1065	addControlledAction(audioChannels, enableChA, QString("enableChA"));
1066
1067	QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
1068	enableChB->setCheckable(true);
1069	enableChB->setChecked(true);
1070	connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(5, enable); });
1071	addControlledAction(audioChannels, enableChB, QString("enableChB"));
1072
1073	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
1074	m_shortcutController->addMenu(toolsMenu);
1075	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
1076	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
1077	addControlledAction(toolsMenu, viewLogs, "viewLogs");
1078
1079	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
1080	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
1081	addControlledAction(toolsMenu, overrides, "overrideWindow");
1082
1083	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
1084	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
1085	addControlledAction(toolsMenu, sensors, "sensorWindow");
1086
1087	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1088	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
1089	addControlledAction(toolsMenu, cheats, "cheatsWindow");
1090
1091#ifdef USE_GDB_STUB
1092	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1093	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
1094	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1095#endif
1096
1097	toolsMenu->addSeparator();
1098	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())),
1099	                    "settings");
1100	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())),
1101	                    "shortcuts");
1102
1103	QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
1104	connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
1105	addControlledAction(toolsMenu, keymap, "remapKeyboard");
1106
1107#ifdef BUILD_SDL
1108	QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
1109	connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
1110	addControlledAction(toolsMenu, gamepad, "remapGamepad");
1111#endif
1112
1113	toolsMenu->addSeparator();
1114
1115	QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1116	connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
1117	m_gameActions.append(paletteView);
1118	addControlledAction(toolsMenu, paletteView, "paletteWindow");
1119
1120	QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1121	connect(memoryView, SIGNAL(triggered()), this, SLOT(openMemoryWindow()));
1122	m_gameActions.append(memoryView);
1123	addControlledAction(toolsMenu, memoryView, "memoryView");
1124
1125	ConfigOption* skipBios = m_config->addOption("skipBios");
1126	skipBios->connect([this](const QVariant& value) {
1127		m_controller->setSkipBIOS(value.toBool());
1128	}, this);
1129
1130	ConfigOption* useBios = m_config->addOption("useBios");
1131	useBios->connect([this](const QVariant& value) {
1132		m_controller->setUseBIOS(value.toBool());
1133	}, this);
1134
1135	ConfigOption* buffers = m_config->addOption("audioBuffers");
1136	buffers->connect([this](const QVariant& value) {
1137		emit audioBufferSamplesChanged(value.toInt());
1138	}, this);
1139
1140	ConfigOption* sampleRate = m_config->addOption("sampleRate");
1141	sampleRate->connect([this](const QVariant& value) {
1142		emit sampleRateChanged(value.toUInt());
1143	}, this);
1144
1145	ConfigOption* volume = m_config->addOption("volume");
1146	volume->connect([this](const QVariant& value) {
1147		m_controller->setVolume(value.toInt());
1148	}, this);
1149
1150	ConfigOption* mute = m_config->addOption("mute");
1151	mute->connect([this](const QVariant& value) {
1152		m_controller->setMute(value.toBool());
1153	}, this);
1154
1155	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1156	rewindEnable->connect([this](const QVariant& value) {
1157		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
1158	}, this);
1159
1160	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1161	rewindBufferCapacity->connect([this](const QVariant& value) {
1162		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
1163	}, this);
1164
1165	ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
1166	rewindBufferInterval->connect([this](const QVariant& value) {
1167		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
1168	}, this);
1169
1170	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1171	allowOpposingDirections->connect([this](const QVariant& value) {
1172		m_inputController.setAllowOpposing(value.toBool());
1173	}, this);
1174
1175	QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1176	connect(exitFullScreen, SIGNAL(triggered()), this, SLOT(exitFullScreen()));
1177	exitFullScreen->setShortcut(QKeySequence("Esc"));
1178	addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1179
1180	foreach (QAction* action, m_gameActions) {
1181		action->setDisabled(true);
1182	}
1183}
1184
1185void Window::attachWidget(QWidget* widget) {
1186	m_screenWidget->layout()->addWidget(widget);
1187	m_screenWidget->unsetCursor();
1188	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1189}
1190
1191void Window::detachWidget(QWidget* widget) {
1192	m_screenWidget->layout()->removeWidget(widget);
1193}
1194
1195void Window::appendMRU(const QString& fname) {
1196	int index = m_mruFiles.indexOf(fname);
1197	if (index >= 0) {
1198		m_mruFiles.removeAt(index);
1199	}
1200	m_mruFiles.prepend(fname);
1201	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1202		m_mruFiles.removeLast();
1203	}
1204	updateMRU();
1205}
1206
1207void Window::updateMRU() {
1208	if (!m_mruMenu) {
1209		return;
1210	}
1211	m_mruMenu->clear();
1212	int i = 0;
1213	for (const QString& file : m_mruFiles) {
1214		QAction* item = new QAction(file, m_mruMenu);
1215		item->setShortcut(QString("Ctrl+%1").arg(i));
1216		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1217		m_mruMenu->addAction(item);
1218		++i;
1219	}
1220	m_config->setMRU(m_mruFiles);
1221	m_config->write();
1222	m_mruMenu->setEnabled(i > 0);
1223}
1224
1225QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1226	addHiddenAction(menu, action, name);
1227	menu->addAction(action);
1228	return action;
1229}
1230
1231QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1232	m_shortcutController->addAction(menu, action, name);
1233	action->setShortcutContext(Qt::WidgetShortcut);
1234	addAction(action);
1235	return action;
1236}
1237
1238WindowBackground::WindowBackground(QWidget* parent)
1239	: QLabel(parent)
1240{
1241	setLayout(new QStackedLayout());
1242	layout()->setContentsMargins(0, 0, 0, 0);
1243	setAlignment(Qt::AlignCenter);
1244}
1245
1246void WindowBackground::setSizeHint(const QSize& hint) {
1247	m_sizeHint = hint;
1248}
1249
1250QSize WindowBackground::sizeHint() const {
1251	return m_sizeHint;
1252}
1253
1254void WindowBackground::setLockAspectRatio(int width, int height) {
1255	m_aspectWidth = width;
1256	m_aspectHeight = height;
1257}
1258
1259void WindowBackground::paintEvent(QPaintEvent*) {
1260	const QPixmap* logo = pixmap();
1261	if (!logo) {
1262		return;
1263	}
1264	QPainter painter(this);
1265	painter.setRenderHint(QPainter::SmoothPixmapTransform);
1266	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1267	QSize s = size();
1268	QSize ds = s;
1269	if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
1270		ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
1271	} else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
1272		ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
1273	}
1274	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1275	QRect full(origin, ds);
1276	painter.drawPixmap(full, *logo);
1277}