all repos — mgba @ cf8e84a1f88c812eab399dfac6e8cd43dcd2fedd

mGBA Game Boy Advance Emulator

src/platform/qt/Window.cpp (view raw)

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