all repos — mgba @ 12ef93d784c377fa8cf137abaae6a19a2541381d

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