all repos — mgba @ 74c4cbe33e5bc67ef2b0eb1cb6bd518270735e63

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