all repos — mgba @ ad1313fd43fa0c8e059a2d8eef0bbe332fbdbedf

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