all repos — mgba @ 2a4ecde790e92a389500aac625f372103d7cf0e5

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