all repos — mgba @ c14da05d8dca225010677643c32fea5c0ac8517a

mGBA Game Boy Advance Emulator

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

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