all repos — mgba @ fb9df7270d1f5174fd9031b2647d9af9c62af7b9

mGBA Game Boy Advance Emulator

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

   1/* Copyright (c) 2013-2016 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#ifdef USE_SQLITE3
  19#include "ArchiveInspector.h"
  20#endif
  21#include "CheatsView.h"
  22#include "ConfigController.h"
  23#include "DebuggerConsole.h"
  24#include "DebuggerConsoleController.h"
  25#include "Display.h"
  26#include "GameController.h"
  27#include "GBAApp.h"
  28#include "GDBController.h"
  29#include "GDBWindow.h"
  30#include "GIFView.h"
  31#include "InputModel.h"
  32#include "IOViewer.h"
  33#include "LoadSaveState.h"
  34#include "LogView.h"
  35#include "MultiplayerController.h"
  36#include "MemoryView.h"
  37#include "OverrideView.h"
  38#include "ObjView.h"
  39#include "PaletteView.h"
  40#include "ROMInfo.h"
  41#include "SensorView.h"
  42#include "SettingsView.h"
  43#include "ShaderSelector.h"
  44#include "TileView.h"
  45#include "VideoView.h"
  46
  47#include <mgba/core/version.h>
  48#ifdef M_CORE_GB
  49#include <mgba/internal/gb/gb.h>
  50#include <mgba/internal/gb/input.h>
  51#include <mgba/internal/gb/video.h>
  52#endif
  53#ifdef M_CORE_GBA
  54#include <mgba/internal/gba/gba.h>
  55#include <mgba/internal/gba/input.h>
  56#include <mgba/internal/gba/video.h>
  57#endif
  58#include "feature/commandline.h"
  59#include "feature/sqlite3/no-intro.h"
  60#include <mgba-util/vfs.h>
  61
  62using namespace QGBA;
  63
  64Window::Window(ConfigController* config, int playerId, QWidget* parent)
  65	: QMainWindow(parent)
  66	, m_log(0)
  67	, m_logView(new LogView(&m_log))
  68	, m_stateWindow(nullptr)
  69	, m_screenWidget(new WindowBackground())
  70	, m_logo(":/res/mgba-1024.png")
  71	, m_config(config)
  72	, m_inputModel(new InputModel(this))
  73	, m_inputController(m_inputModel, playerId, this)
  74#ifdef USE_FFMPEG
  75	, m_videoView(nullptr)
  76#endif
  77#ifdef USE_MAGICK
  78	, m_gifView(nullptr)
  79#endif
  80#ifdef USE_GDB_STUB
  81	, m_gdbController(nullptr)
  82#endif
  83#ifdef USE_DEBUGGERS
  84	, m_console(nullptr)
  85#endif
  86	, m_mruMenu(nullptr)
  87	, m_fullscreenOnStart(false)
  88	, m_autoresume(false)
  89	, m_wasOpened(false)
  90{
  91	setFocusPolicy(Qt::StrongFocus);
  92	setAcceptDrops(true);
  93	setAttribute(Qt::WA_DeleteOnClose);
  94	m_controller = new GameController(this);
  95	m_controller->setInputController(&m_inputController);
  96	updateTitle();
  97
  98	m_display = Display::create(this);
  99	m_shaderView = new ShaderSelector(m_display, m_config);
 100
 101	m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
 102	m_logo = m_logo; // Free memory left over in old pixmap
 103
 104	m_screenWidget->setMinimumSize(m_display->minimumSize());
 105	m_screenWidget->setSizePolicy(m_display->sizePolicy());
 106	int i = 2;
 107	QVariant multiplier = m_config->getOption("scaleMultiplier");
 108	if (!multiplier.isNull()) {
 109		m_savedScale = multiplier.toInt();
 110		i = m_savedScale;
 111	}
 112#ifdef USE_SQLITE3
 113	m_libraryView = new LibraryView();
 114	ConfigOption* showLibrary = m_config->addOption("showLibrary");
 115	showLibrary->connect([this](const QVariant& value) {
 116		if (value.toBool()) {
 117			if (m_controller->isLoaded()) {
 118				m_screenWidget->layout()->addWidget(m_libraryView);
 119			} else {
 120				attachWidget(m_libraryView);
 121			}
 122		} else {
 123			detachWidget(m_libraryView);
 124		}
 125	}, this);
 126	m_config->updateOption("showLibrary");
 127
 128	connect(m_libraryView, &LibraryView::accepted, [this]() {
 129		VFile* output = m_libraryView->selectedVFile();
 130		QPair<QString, QString> path = m_libraryView->selectedPath();
 131		if (output) {
 132			m_controller->loadGame(output, path.first, path.second);
 133		}
 134	});
 135#elif defined(M_CORE_GBA)
 136	m_screenWidget->setSizeHint(QSize(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i));
 137#endif
 138	m_screenWidget->setPixmap(m_logo);
 139	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
 140	setCentralWidget(m_screenWidget);
 141
 142	connect(m_controller, SIGNAL(gameStarted(mCoreThread*, const QString&)), this, SLOT(gameStarted(mCoreThread*, const QString&)));
 143	connect(m_controller, SIGNAL(gameStarted(mCoreThread*, const QString&)), &m_inputController, SLOT(suspendScreensaver()));
 144	connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_display, SLOT(stopDrawing()));
 145	connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), this, SLOT(gameStopped()));
 146	connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), &m_inputController, SLOT(resumeScreensaver()));
 147	connect(m_controller, SIGNAL(stateLoaded(mCoreThread*)), m_display, SLOT(forceDraw()));
 148	connect(m_controller, SIGNAL(rewound(mCoreThread*)), m_display, SLOT(forceDraw()));
 149	connect(m_controller, &GameController::gamePaused, [this](mCoreThread* context) {
 150		unsigned width, height;
 151		context->core->desiredVideoDimensions(context->core, &width, &height);
 152		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), width, height,
 153		                    width * BYTES_PER_PIXEL, QImage::Format_RGBX8888);
 154		QPixmap pixmap;
 155		pixmap.convertFromImage(currentImage);
 156		m_screenWidget->setPixmap(pixmap);
 157		m_screenWidget->setLockAspectRatio(width, height);
 158	});
 159	connect(m_controller, SIGNAL(gamePaused(mCoreThread*)), m_display, SLOT(pauseDrawing()));
 160#ifndef Q_OS_MAC
 161	connect(m_controller, SIGNAL(gamePaused(mCoreThread*)), menuBar(), SLOT(show()));
 162	connect(m_controller, &GameController::gameUnpaused, [this]() {
 163		if(isFullScreen()) {
 164			menuBar()->hide();
 165		}
 166	});
 167#endif
 168	connect(m_controller, SIGNAL(gamePaused(mCoreThread*)), &m_inputController, SLOT(resumeScreensaver()));
 169	connect(m_controller, SIGNAL(gameUnpaused(mCoreThread*)), m_display, SLOT(unpauseDrawing()));
 170	connect(m_controller, SIGNAL(gameUnpaused(mCoreThread*)), &m_inputController, SLOT(suspendScreensaver()));
 171	connect(m_controller, SIGNAL(postLog(int, int, const QString&)), &m_log, SLOT(postLog(int, int, const QString&)));
 172	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
 173	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), m_display, SLOT(framePosted(const uint32_t*)));
 174	connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
 175	connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
 176	connect(m_controller, SIGNAL(unimplementedBiosCall(int)), this, SLOT(unimplementedBiosCall(int)));
 177	connect(m_controller, SIGNAL(statusPosted(const QString&)), m_display, SLOT(showMessage(const QString&)));
 178	connect(&m_log, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
 179	connect(&m_log, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
 180	connect(&m_log, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
 181	connect(this, SIGNAL(startDrawing(mCoreThread*)), m_display, SLOT(startDrawing(mCoreThread*)), Qt::QueuedConnection);
 182	connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
 183	connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
 184	connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
 185	connect(this, SIGNAL(shutdown()), m_shaderView, SLOT(hide()));
 186	connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
 187	connect(this, SIGNAL(sampleRateChanged(unsigned)), m_controller, SLOT(setAudioSampleRate(unsigned)));
 188	connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
 189	connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));
 190	connect(&m_focusCheck, SIGNAL(timeout()), this, SLOT(focusCheck()));
 191	connect(m_display, &Display::hideCursor, [this]() {
 192		if (static_cast<QStackedLayout*>(m_screenWidget->layout())->currentWidget() == m_display) {
 193			m_screenWidget->setCursor(Qt::BlankCursor);
 194		}
 195	});
 196	connect(m_display, &Display::showCursor, [this]() {
 197		m_screenWidget->unsetCursor();
 198	});
 199
 200	m_log.setLevels(mLOG_WARN | mLOG_ERROR | mLOG_FATAL);
 201	m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
 202	m_focusCheck.setInterval(200);
 203
 204	m_inputModel->setConfigController(m_config);
 205	setupMenu(menuBar());
 206
 207#ifdef M_CORE_GBA
 208	m_inputController.addPlatform(PLATFORM_GBA, tr("Game Boy Advance"), &GBAInputInfo);
 209#endif
 210#ifdef M_CORE_GB
 211	m_inputController.addPlatform(PLATFORM_GB, tr("Game Boy"), &GBInputInfo);
 212#endif
 213	m_inputController.setupCallback(m_controller);
 214}
 215
 216Window::~Window() {
 217	delete m_logView;
 218
 219#ifdef USE_FFMPEG
 220	delete m_videoView;
 221#endif
 222
 223#ifdef USE_MAGICK
 224	delete m_gifView;
 225#endif
 226
 227#ifdef USE_SQLITE3
 228	delete m_libraryView;
 229#endif
 230}
 231
 232void Window::argumentsPassed(mArguments* args) {
 233	loadConfig();
 234
 235	if (args->patch) {
 236		m_controller->loadPatch(args->patch);
 237	}
 238
 239	if (args->fname) {
 240		m_controller->loadGame(args->fname);
 241	}
 242
 243#ifdef USE_GDB_STUB
 244	if (args->debuggerType == DEBUGGER_GDB) {
 245		if (!m_gdbController) {
 246			m_gdbController = new GDBController(m_controller, this);
 247			m_gdbController->listen();
 248		}
 249	}
 250#endif
 251}
 252
 253void Window::resizeFrame(const QSize& size) {
 254	QSize newSize(size);
 255#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
 256	newSize /= m_screenWidget->devicePixelRatioF();
 257#endif
 258	m_screenWidget->setSizeHint(newSize);
 259	newSize -= m_screenWidget->size();
 260	newSize += this->size();
 261	resize(newSize);
 262}
 263
 264void Window::setConfig(ConfigController* config) {
 265	m_config = config;
 266}
 267
 268void Window::loadConfig() {
 269	const mCoreOptions* opts = m_config->options();
 270	reloadConfig();
 271
 272	// TODO: Move these to ConfigController
 273	if (opts->fpsTarget) {
 274		emit fpsTargetChanged(opts->fpsTarget);
 275	}
 276
 277	if (opts->audioBuffers) {
 278		emit audioBufferSamplesChanged(opts->audioBuffers);
 279	}
 280
 281	if (opts->sampleRate) {
 282		emit sampleRateChanged(opts->sampleRate);
 283	}
 284
 285	if (opts->width && opts->height) {
 286		resizeFrame(QSize(opts->width, opts->height));
 287	}
 288
 289	if (opts->fullscreen) {
 290		enterFullScreen();
 291	}
 292
 293	if (opts->shader) {
 294		struct VDir* shader = VDirOpen(opts->shader);
 295		if (shader) {
 296			m_display->setShaders(shader);
 297			m_shaderView->refreshShaders();
 298			shader->close(shader);
 299		}
 300	}
 301
 302	m_mruFiles = m_config->getMRU();
 303	updateMRU();
 304
 305	m_inputController.setConfiguration(m_config);
 306	m_controller->setUseBIOS(opts->useBios);
 307}
 308
 309void Window::reloadConfig() {
 310	const mCoreOptions* opts = m_config->options();
 311
 312	m_log.setLevels(opts->logLevel);
 313
 314	QString saveStateExtdata = m_config->getOption("saveStateExtdata");
 315	bool ok;
 316	int flags = saveStateExtdata.toInt(&ok);
 317	if (ok) {
 318		m_controller->setSaveStateExtdata(flags);
 319	}
 320
 321	QString loadStateExtdata = m_config->getOption("loadStateExtdata");
 322	flags = loadStateExtdata.toInt(&ok);
 323	if (ok) {
 324		m_controller->setLoadStateExtdata(flags);
 325	}
 326
 327	m_controller->setConfig(m_config->config());
 328	m_display->lockAspectRatio(opts->lockAspectRatio);
 329	m_display->filter(opts->resampleVideo);
 330
 331	m_inputController.setScreensaverSuspendable(opts->suspendScreensaver);
 332}
 333
 334void Window::saveConfig() {
 335	m_inputController.saveConfiguration();
 336	m_config->write();
 337}
 338
 339QString Window::getFilters() const {
 340	QStringList filters;
 341	QStringList formats;
 342
 343#ifdef M_CORE_GBA
 344	QStringList gbaFormats{
 345		"*.gba",
 346#if defined(USE_LIBZIP) || defined(USE_ZLIB)
 347		"*.zip",
 348#endif
 349#ifdef USE_LZMA
 350		"*.7z",
 351#endif
 352		"*.agb",
 353		"*.mb",
 354		"*.rom",
 355		"*.bin"};
 356	formats.append(gbaFormats);
 357	filters.append(tr("Game Boy Advance ROMs (%1)").arg(gbaFormats.join(QChar(' '))));
 358#endif
 359
 360#ifdef M_CORE_GB
 361	QStringList gbFormats{
 362		"*.gb",
 363		"*.gbc",
 364#if defined(USE_LIBZIP) || defined(USE_ZLIB)
 365		"*.zip",
 366#endif
 367#ifdef USE_LZMA
 368		"*.7z",
 369#endif
 370		"*.rom",
 371		"*.bin"};
 372	formats.append(gbFormats);
 373	filters.append(tr("Game Boy ROMs (%1)").arg(gbFormats.join(QChar(' '))));
 374#endif
 375
 376	formats.removeDuplicates();
 377	filters.prepend(tr("All ROMs (%1)").arg(formats.join(QChar(' '))));
 378	return filters.join(";;");
 379}
 380
 381QString Window::getFiltersArchive() const {
 382	QStringList filters;
 383
 384	QStringList formats{
 385#if defined(USE_LIBZIP) || defined(USE_ZLIB)
 386		"*.zip",
 387#endif
 388#ifdef USE_LZMA
 389		"*.7z",
 390#endif
 391	};
 392	filters.append(tr("Archives (%1)").arg(formats.join(QChar(' '))));
 393	return filters.join(";;");
 394}
 395
 396void Window::selectROM() {
 397	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFilters());
 398	if (!filename.isEmpty()) {
 399		m_controller->loadGame(filename);
 400	}
 401}
 402
 403#ifdef USE_SQLITE3
 404void Window::selectROMInArchive() {
 405	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFiltersArchive());
 406	if (filename.isEmpty()) {
 407		return;
 408	}
 409	ArchiveInspector* archiveInspector = new ArchiveInspector(filename);
 410	connect(archiveInspector, &QDialog::accepted, [this,  archiveInspector]() {
 411		VFile* output = archiveInspector->selectedVFile();
 412		QPair<QString, QString> path = archiveInspector->selectedPath();
 413		if (output) {
 414			m_controller->loadGame(output, path.second, path.first);
 415		}
 416		archiveInspector->close();
 417	});
 418	archiveInspector->setAttribute(Qt::WA_DeleteOnClose);
 419	archiveInspector->show();
 420}
 421
 422void Window::addDirToLibrary() {
 423	QString filename = GBAApp::app()->getOpenDirectoryName(this, tr("Select folder"));
 424	if (filename.isEmpty()) {
 425		return;
 426	}
 427	m_libraryView->addDirectory(filename);
 428}
 429#endif
 430
 431void Window::replaceROM() {
 432	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFilters());
 433	if (!filename.isEmpty()) {
 434		m_controller->replaceGame(filename);
 435	}
 436}
 437
 438void Window::selectSave(bool temporary) {
 439	QStringList formats{"*.sav"};
 440	QString filter = tr("Game Boy Advance save files (%1)").arg(formats.join(QChar(' ')));
 441	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save"), filter);
 442	if (!filename.isEmpty()) {
 443		m_controller->loadSave(filename, temporary);
 444	}
 445}
 446
 447void Window::multiplayerChanged() {
 448	int attached = 1;
 449	MultiplayerController* multiplayer = m_controller->multiplayerController();
 450	if (multiplayer) {
 451		attached = multiplayer->attached();
 452	}
 453	if (m_controller->isLoaded()) {
 454		for (QAction* action : m_nonMpActions) {
 455			action->setDisabled(attached > 1);
 456		}
 457	}
 458}
 459
 460void Window::selectPatch() {
 461	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select patch"), tr("Patches (*.ips *.ups *.bps)"));
 462	if (!filename.isEmpty()) {
 463		m_controller->loadPatch(filename);
 464	}
 465}
 466
 467void Window::openView(QWidget* widget) {
 468	connect(this, SIGNAL(shutdown()), widget, SLOT(close()));
 469	widget->setAttribute(Qt::WA_DeleteOnClose);
 470	widget->show();
 471}
 472
 473void Window::importSharkport() {
 474	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
 475	if (!filename.isEmpty()) {
 476		m_controller->importSharkport(filename);
 477	}
 478}
 479
 480void Window::exportSharkport() {
 481	QString filename = GBAApp::app()->getSaveFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
 482	if (!filename.isEmpty()) {
 483		m_controller->exportSharkport(filename);
 484	}
 485}
 486
 487void Window::openSettingsWindow() {
 488	SettingsView* settingsWindow = new SettingsView(m_config, &m_inputController, m_inputModel);
 489	connect(settingsWindow, SIGNAL(biosLoaded(int, const QString&)), m_controller, SLOT(loadBIOS(int, const QString&)));
 490	connect(settingsWindow, SIGNAL(audioDriverChanged()), m_controller, SLOT(reloadAudioDriver()));
 491	connect(settingsWindow, SIGNAL(displayDriverChanged()), this, SLOT(mustRestart()));
 492	connect(settingsWindow, SIGNAL(pathsChanged()), this, SLOT(reloadConfig()));
 493	openView(settingsWindow);
 494}
 495
 496void Window::openAboutScreen() {
 497	AboutScreen* about = new AboutScreen();
 498	openView(about);
 499}
 500
 501template <typename T, typename A>
 502std::function<void()> Window::openTView(A arg) {
 503	return [=]() {
 504		T* view = new T(m_controller, arg);
 505		openView(view);
 506	};
 507}
 508
 509template <typename T>
 510std::function<void()> Window::openTView() {
 511	return [=]() {
 512		T* view = new T(m_controller);
 513		openView(view);
 514	};
 515}
 516
 517#ifdef USE_FFMPEG
 518void Window::openVideoWindow() {
 519	if (!m_videoView) {
 520		m_videoView = new VideoView();
 521		connect(m_videoView, SIGNAL(recordingStarted(mAVStream*)), m_controller, SLOT(setAVStream(mAVStream*)));
 522		connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 523		connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_videoView, SLOT(stopRecording()));
 524		connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_videoView, SLOT(close()));
 525		connect(m_controller, &GameController::gameStarted, [this]() {
 526			m_videoView->setNativeResolution(m_controller->screenDimensions());
 527		});
 528		if (m_controller->isLoaded()) {
 529			m_videoView->setNativeResolution(m_controller->screenDimensions());
 530		}
 531		connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
 532	}
 533	m_videoView->show();
 534}
 535#endif
 536
 537#ifdef USE_MAGICK
 538void Window::openGIFWindow() {
 539	if (!m_gifView) {
 540		m_gifView = new GIFView();
 541		connect(m_gifView, SIGNAL(recordingStarted(mAVStream*)), m_controller, SLOT(setAVStream(mAVStream*)));
 542		connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 543		connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_gifView, SLOT(stopRecording()));
 544		connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_gifView, SLOT(close()));
 545		connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
 546	}
 547	m_gifView->show();
 548}
 549#endif
 550
 551#ifdef USE_GDB_STUB
 552void Window::gdbOpen() {
 553	if (!m_gdbController) {
 554		m_gdbController = new GDBController(m_controller, this);
 555	}
 556	GDBWindow* window = new GDBWindow(m_gdbController);
 557	openView(window);
 558}
 559#endif
 560
 561#ifdef USE_DEBUGGERS
 562void Window::consoleOpen() {
 563	if (!m_console) {
 564		m_console = new DebuggerConsoleController(m_controller, this);
 565	}
 566	DebuggerConsole* window = new DebuggerConsole(m_console);
 567	openView(window);
 568}
 569#endif
 570
 571void Window::resizeEvent(QResizeEvent* event) {
 572	if (!isFullScreen()) {
 573		m_config->setOption("height", m_screenWidget->height());
 574		m_config->setOption("width", m_screenWidget->width());
 575	}
 576
 577	int factor = 0;
 578	QSize size(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
 579	if (m_controller->isLoaded()) {
 580		size = m_controller->screenDimensions();
 581	}
 582	if (m_screenWidget->width() % size.width() == 0 && m_screenWidget->height() % size.height() == 0 &&
 583	    m_screenWidget->width() / size.width() == m_screenWidget->height() / size.height()) {
 584		factor = m_screenWidget->width() / size.width();
 585	} else {
 586		m_savedScale = 0;
 587	}
 588	for (QMap<int, QAction*>::iterator iter = m_frameSizes.begin(); iter != m_frameSizes.end(); ++iter) {
 589		bool enableSignals = iter.value()->blockSignals(true);
 590		iter.value()->setChecked(iter.key() == factor);
 591		iter.value()->blockSignals(enableSignals);
 592	}
 593
 594	m_config->setOption("fullscreen", isFullScreen());
 595}
 596
 597void Window::showEvent(QShowEvent* event) {
 598	if (m_wasOpened) {
 599		return;
 600	}
 601	m_wasOpened = true;
 602	resizeFrame(m_screenWidget->sizeHint());
 603	QVariant windowPos = m_config->getQtOption("windowPos");
 604	if (!windowPos.isNull()) {
 605		move(windowPos.toPoint());
 606	} else {
 607		QRect rect = frameGeometry();
 608		rect.moveCenter(QApplication::desktop()->availableGeometry().center());
 609		move(rect.topLeft());
 610	}
 611	if (m_fullscreenOnStart) {
 612		enterFullScreen();
 613		m_fullscreenOnStart = false;
 614	}
 615}
 616
 617void Window::closeEvent(QCloseEvent* event) {
 618	emit shutdown();
 619	m_config->setQtOption("windowPos", pos());
 620
 621	if (m_savedScale > 0) {
 622		m_config->setOption("height", VIDEO_VERTICAL_PIXELS * m_savedScale);
 623		m_config->setOption("width", VIDEO_HORIZONTAL_PIXELS * m_savedScale);
 624	}
 625	saveConfig();
 626	QMainWindow::closeEvent(event);
 627}
 628
 629void Window::focusInEvent(QFocusEvent*) {
 630	m_display->forceDraw();
 631}
 632
 633void Window::focusOutEvent(QFocusEvent*) {
 634	m_controller->setTurbo(false, false);
 635	m_controller->stopRewinding();
 636	m_controller->clearKeys();
 637}
 638
 639void Window::dragEnterEvent(QDragEnterEvent* event) {
 640	if (event->mimeData()->hasFormat("text/uri-list")) {
 641		event->acceptProposedAction();
 642	}
 643}
 644
 645void Window::dropEvent(QDropEvent* event) {
 646	QString uris = event->mimeData()->data("text/uri-list");
 647	uris = uris.trimmed();
 648	if (uris.contains("\n")) {
 649		// Only one file please
 650		return;
 651	}
 652	QUrl url(uris);
 653	if (!url.isLocalFile()) {
 654		// No remote loading
 655		return;
 656	}
 657	event->accept();
 658	m_controller->loadGame(url.toLocalFile());
 659}
 660
 661void Window::mouseDoubleClickEvent(QMouseEvent* event) {
 662	if (event->button() != Qt::LeftButton) {
 663		return;
 664	}
 665	toggleFullScreen();
 666}
 667
 668void Window::enterFullScreen() {
 669	if (!isVisible()) {
 670		m_fullscreenOnStart = true;
 671		return;
 672	}
 673	if (isFullScreen()) {
 674		return;
 675	}
 676	showFullScreen();
 677#ifndef Q_OS_MAC
 678	if (m_controller->isLoaded() && !m_controller->isPaused()) {
 679		menuBar()->hide();
 680	}
 681#endif
 682}
 683
 684void Window::exitFullScreen() {
 685	if (!isFullScreen()) {
 686		return;
 687	}
 688	m_screenWidget->unsetCursor();
 689	menuBar()->show();
 690	showNormal();
 691}
 692
 693void Window::toggleFullScreen() {
 694	if (isFullScreen()) {
 695		exitFullScreen();
 696	} else {
 697		enterFullScreen();
 698	}
 699}
 700
 701void Window::gameStarted(mCoreThread* context, const QString& fname) {
 702	MutexLock(&context->stateMutex);
 703	if (context->state < THREAD_EXITING) {
 704		emit startDrawing(context);
 705	} else {
 706		MutexUnlock(&context->stateMutex);
 707		return;
 708	}
 709	MutexUnlock(&context->stateMutex);
 710	foreach (QAction* action, m_gameActions) {
 711		action->setDisabled(false);
 712	}
 713#ifdef M_CORE_GBA
 714	foreach (QAction* action, m_gbaActions) {
 715		action->setDisabled(context->core->platform(context->core) != PLATFORM_GBA);
 716	}
 717#endif
 718	multiplayerChanged();
 719	if (!fname.isEmpty()) {
 720		setWindowFilePath(fname);
 721		appendMRU(fname);
 722	}
 723	updateTitle();
 724	unsigned width, height;
 725	context->core->desiredVideoDimensions(context->core, &width, &height);
 726	m_display->setMinimumSize(width, height);
 727	m_screenWidget->setMinimumSize(m_display->minimumSize());
 728	if (m_savedScale > 0) {
 729		resizeFrame(QSize(width, height) * m_savedScale);
 730	}
 731	attachWidget(m_display);
 732
 733#ifndef Q_OS_MAC
 734	if (isFullScreen()) {
 735		menuBar()->hide();
 736	}
 737#endif
 738
 739	m_inputController.setPlatform(m_controller->platform());
 740
 741	m_hitUnimplementedBiosCall = false;
 742	m_fpsTimer.start();
 743	m_focusCheck.start();
 744}
 745
 746void Window::gameStopped() {
 747#ifdef M_CORE_GBA
 748	foreach (QAction* action, m_gbaActions) {
 749		action->setDisabled(false);
 750	}
 751#endif
 752	foreach (QAction* action, m_gameActions) {
 753		action->setDisabled(true);
 754	}
 755	setWindowFilePath(QString());
 756	updateTitle();
 757	detachWidget(m_display);
 758	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
 759	m_screenWidget->setPixmap(m_logo);
 760	m_screenWidget->unsetCursor();
 761#ifdef M_CORE_GB
 762	m_display->setMinimumSize(GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
 763#elif defined(M_CORE_GBA)
 764	m_display->setMinimumSize(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
 765#endif
 766	m_screenWidget->setMinimumSize(m_display->minimumSize());
 767
 768	m_fpsTimer.stop();
 769	m_focusCheck.stop();
 770}
 771
 772void Window::gameCrashed(const QString& errorMessage) {
 773	QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
 774	                                     tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
 775	                                     QMessageBox::Ok, this, Qt::Sheet);
 776	crash->setAttribute(Qt::WA_DeleteOnClose);
 777	crash->show();
 778}
 779
 780void Window::gameFailed() {
 781	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
 782	                                    tr("Could not load game. Are you sure it's in the correct format?"),
 783	                                    QMessageBox::Ok, this, Qt::Sheet);
 784	fail->setAttribute(Qt::WA_DeleteOnClose);
 785	fail->show();
 786}
 787
 788void Window::unimplementedBiosCall(int call) {
 789	if (m_hitUnimplementedBiosCall) {
 790		return;
 791	}
 792	m_hitUnimplementedBiosCall = true;
 793
 794	QMessageBox* fail = new QMessageBox(
 795	    QMessageBox::Warning, tr("Unimplemented BIOS call"),
 796	    tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
 797	    QMessageBox::Ok, this, Qt::Sheet);
 798	fail->setAttribute(Qt::WA_DeleteOnClose);
 799	fail->show();
 800}
 801
 802void Window::tryMakePortable() {
 803	QMessageBox* confirm = new QMessageBox(QMessageBox::Question, tr("Really make portable?"),
 804	                                       tr("This will make the emulator load its configuration from the same directory as the executable. Do you want to continue?"),
 805	                                       QMessageBox::Yes | QMessageBox::Cancel, this, Qt::Sheet);
 806	confirm->setAttribute(Qt::WA_DeleteOnClose);
 807	connect(confirm->button(QMessageBox::Yes), SIGNAL(clicked()), m_config, SLOT(makePortable()));
 808	confirm->show();
 809}
 810
 811void Window::mustRestart() {
 812	QMessageBox* dialog = new QMessageBox(QMessageBox::Warning, tr("Restart needed"),
 813	                                      tr("Some changes will not take effect until the emulator is restarted."),
 814	                                      QMessageBox::Ok, this, Qt::Sheet);
 815	dialog->setAttribute(Qt::WA_DeleteOnClose);
 816	dialog->show();
 817}
 818
 819void Window::recordFrame() {
 820	m_frameList.append(QDateTime::currentDateTime());
 821	while (m_frameList.count() > FRAME_LIST_SIZE) {
 822		m_frameList.removeFirst();
 823	}
 824}
 825
 826void Window::showFPS() {
 827	if (m_frameList.isEmpty()) {
 828		updateTitle();
 829		return;
 830	}
 831	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
 832	float fps = (m_frameList.count() - 1) * 10000.f / interval;
 833	fps = round(fps) / 10.f;
 834	updateTitle(fps);
 835}
 836
 837void Window::updateTitle(float fps) {
 838	QString title;
 839
 840	m_controller->threadInterrupt();
 841	if (m_controller->isLoaded()) {
 842		const NoIntroDB* db = GBAApp::app()->gameDB();
 843		NoIntroGame game{};
 844		uint32_t crc32 = 0;
 845		m_controller->thread()->core->checksum(m_controller->thread()->core, &crc32, CHECKSUM_CRC32);
 846
 847		char gameTitle[17] = { '\0' };
 848		mCore* core = m_controller->thread()->core;
 849		core->getGameTitle(core, gameTitle);
 850		title = gameTitle;
 851
 852#ifdef USE_SQLITE3
 853		if (db && crc32 && NoIntroDBLookupGameByCRC(db, crc32, &game)) {
 854			title = QLatin1String(game.name);
 855		}
 856#endif
 857	}
 858	MultiplayerController* multiplayer = m_controller->multiplayerController();
 859	if (multiplayer && multiplayer->attached() > 1) {
 860		title += tr(" -  Player %1 of %2").arg(multiplayer->playerId(m_controller) + 1).arg(multiplayer->attached());
 861		for (QAction* action : m_nonMpActions) {
 862			action->setDisabled(true);
 863		}
 864	} else if (m_controller->isLoaded()) {
 865		for (QAction* action : m_nonMpActions) {
 866			action->setDisabled(false);
 867		}
 868	}
 869	m_controller->threadContinue();
 870	if (title.isNull()) {
 871		setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
 872	} else if (fps < 0) {
 873		setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
 874	} else {
 875		setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
 876	}
 877}
 878
 879void Window::openStateWindow(LoadSave ls) {
 880	if (m_stateWindow) {
 881		return;
 882	}
 883	MultiplayerController* multiplayer = m_controller->multiplayerController();
 884	if (multiplayer && multiplayer->attached() > 1) {
 885		return;
 886	}
 887	bool wasPaused = m_controller->isPaused();
 888	m_stateWindow = new LoadSaveState(m_controller);
 889	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
 890	connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_stateWindow, SLOT(close()));
 891	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
 892		detachWidget(m_stateWindow);
 893		m_stateWindow = nullptr;
 894		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
 895	});
 896	if (!wasPaused) {
 897		m_controller->setPaused(true);
 898		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
 899	}
 900	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
 901	m_stateWindow->setMode(ls);
 902	attachWidget(m_stateWindow);
 903}
 904
 905void Window::setupMenu(QMenuBar* menubar) {
 906	menubar->clear();
 907	QMenu* fileMenu = menubar->addMenu(tr("&File"));
 908	m_inputModel->addMenu(fileMenu);
 909	installEventFilter(&m_inputController);
 910	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open),
 911	                    "loadROM");
 912#ifdef USE_SQLITE3
 913	addControlledAction(fileMenu, fileMenu->addAction(tr("Load ROM in archive..."), this, SLOT(selectROMInArchive())),
 914	                    "loadROMInArchive");
 915	addControlledAction(fileMenu, fileMenu->addAction(tr("Add folder to library..."), this, SLOT(addDirToLibrary())),
 916	                    "addDirToLibrary");
 917#endif
 918
 919	QAction* loadTemporarySave = new QAction(tr("Load temporary save..."), fileMenu);
 920	connect(loadTemporarySave, &QAction::triggered, [this]() { this->selectSave(true); });
 921	m_gameActions.append(loadTemporarySave);
 922	addControlledAction(fileMenu, loadTemporarySave, "loadTemporarySave");
 923
 924	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
 925
 926	QAction* bootBIOS = new QAction(tr("Boot BIOS"), fileMenu);
 927	connect(bootBIOS, &QAction::triggered, [this]() {
 928		m_controller->loadBIOS(PLATFORM_GBA, m_config->getOption("gba.bios"));
 929		m_controller->bootBIOS();
 930	});
 931	addControlledAction(fileMenu, bootBIOS, "bootBIOS");
 932
 933	addControlledAction(fileMenu, fileMenu->addAction(tr("Replace ROM..."), this, SLOT(replaceROM())), "replaceROM");
 934
 935	QAction* romInfo = new QAction(tr("ROM &info..."), fileMenu);
 936	connect(romInfo, &QAction::triggered, openTView<ROMInfo>());
 937	m_gameActions.append(romInfo);
 938	addControlledAction(fileMenu, romInfo, "romInfo");
 939
 940	m_mruMenu = fileMenu->addMenu(tr("Recent"));
 941
 942	fileMenu->addSeparator();
 943
 944	addControlledAction(fileMenu, fileMenu->addAction(tr("Make portable"), this, SLOT(tryMakePortable())), "makePortable");
 945
 946	fileMenu->addSeparator();
 947
 948	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
 949	loadState->setShortcut(tr("F10"));
 950	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
 951	m_gameActions.append(loadState);
 952	m_nonMpActions.append(loadState);
 953	addControlledAction(fileMenu, loadState, "loadState");
 954
 955	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
 956	saveState->setShortcut(tr("Shift+F10"));
 957	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
 958	m_gameActions.append(saveState);
 959	m_nonMpActions.append(saveState);
 960	addControlledAction(fileMenu, saveState, "saveState");
 961
 962	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
 963	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
 964	m_inputModel->addMenu(quickLoadMenu);
 965	m_inputModel->addMenu(quickSaveMenu);
 966
 967	QAction* quickLoad = new QAction(tr("Load recent"), quickLoadMenu);
 968	connect(quickLoad, SIGNAL(triggered()), m_controller, SLOT(loadState()));
 969	m_gameActions.append(quickLoad);
 970	m_nonMpActions.append(quickLoad);
 971	addControlledAction(quickLoadMenu, quickLoad, "quickLoad");
 972
 973	QAction* quickSave = new QAction(tr("Save recent"), quickSaveMenu);
 974	connect(quickSave, SIGNAL(triggered()), m_controller, SLOT(saveState()));
 975	m_gameActions.append(quickSave);
 976	m_nonMpActions.append(quickSave);
 977	addControlledAction(quickSaveMenu, quickSave, "quickSave");
 978
 979	quickLoadMenu->addSeparator();
 980	quickSaveMenu->addSeparator();
 981
 982	QAction* undoLoadState = new QAction(tr("Undo load state"), quickLoadMenu);
 983	undoLoadState->setShortcut(tr("F11"));
 984	connect(undoLoadState, SIGNAL(triggered()), m_controller, SLOT(loadBackupState()));
 985	m_gameActions.append(undoLoadState);
 986	m_nonMpActions.append(undoLoadState);
 987	addControlledAction(quickLoadMenu, undoLoadState, "undoLoadState");
 988
 989	QAction* undoSaveState = new QAction(tr("Undo save state"), quickSaveMenu);
 990	undoSaveState->setShortcut(tr("Shift+F11"));
 991	connect(undoSaveState, SIGNAL(triggered()), m_controller, SLOT(saveBackupState()));
 992	m_gameActions.append(undoSaveState);
 993	m_nonMpActions.append(undoSaveState);
 994	addControlledAction(quickSaveMenu, undoSaveState, "undoSaveState");
 995
 996	quickLoadMenu->addSeparator();
 997	quickSaveMenu->addSeparator();
 998
 999	int i;
1000	for (i = 1; i < 10; ++i) {
1001		quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
1002		quickLoad->setShortcut(tr("F%1").arg(i));
1003		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
1004		m_gameActions.append(quickLoad);
1005		m_nonMpActions.append(quickLoad);
1006		addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
1007
1008		quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
1009		quickSave->setShortcut(tr("Shift+F%1").arg(i));
1010		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
1011		m_gameActions.append(quickSave);
1012		m_nonMpActions.append(quickSave);
1013		addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
1014	}
1015
1016#ifdef M_CORE_GBA
1017	fileMenu->addSeparator();
1018	QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
1019	connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
1020	m_gameActions.append(importShark);
1021	m_gbaActions.append(importShark);
1022	addControlledAction(fileMenu, importShark, "importShark");
1023
1024	QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
1025	connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
1026	m_gameActions.append(exportShark);
1027	m_gbaActions.append(exportShark);
1028	addControlledAction(fileMenu, exportShark, "exportShark");
1029#endif
1030
1031	fileMenu->addSeparator();
1032	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
1033	connect(multiWindow, &QAction::triggered, [this]() {
1034		GBAApp::app()->newWindow();
1035	});
1036	addControlledAction(fileMenu, multiWindow, "multiWindow");
1037
1038#ifndef Q_OS_MAC
1039	fileMenu->addSeparator();
1040#endif
1041
1042	QAction* about = new QAction(tr("About"), fileMenu);
1043	connect(about, SIGNAL(triggered()), this, SLOT(openAboutScreen()));
1044	fileMenu->addAction(about);
1045
1046#ifndef Q_OS_MAC
1047	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
1048#endif
1049
1050	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
1051	m_inputModel->addMenu(emulationMenu);
1052	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
1053	reset->setShortcut(tr("Ctrl+R"));
1054	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
1055	m_gameActions.append(reset);
1056	addControlledAction(emulationMenu, reset, "reset");
1057
1058	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
1059	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
1060	m_gameActions.append(shutdown);
1061	addControlledAction(emulationMenu, shutdown, "shutdown");
1062
1063#ifdef M_CORE_GBA
1064	QAction* yank = new QAction(tr("Yank game pak"), emulationMenu);
1065	connect(yank, SIGNAL(triggered()), m_controller, SLOT(yankPak()));
1066	m_gameActions.append(yank);
1067	m_gbaActions.append(yank);
1068	addControlledAction(emulationMenu, yank, "yank");
1069#endif
1070	emulationMenu->addSeparator();
1071
1072	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
1073	pause->setChecked(false);
1074	pause->setCheckable(true);
1075	pause->setShortcut(tr("Ctrl+P"));
1076	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
1077	connect(m_controller, &GameController::gamePaused, [this, pause]() {
1078		pause->setChecked(true);
1079	});
1080	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
1081	m_gameActions.append(pause);
1082	addControlledAction(emulationMenu, pause, "pause");
1083
1084	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
1085	frameAdvance->setShortcut(tr("Ctrl+N"));
1086	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
1087	m_gameActions.append(frameAdvance);
1088	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
1089
1090	emulationMenu->addSeparator();
1091
1092	m_inputModel->addFunctions(emulationMenu, [this]() {
1093		m_controller->setTurbo(true, false);
1094	}, [this]() {
1095		m_controller->setTurbo(false, false);
1096	}, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
1097
1098	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
1099	turbo->setCheckable(true);
1100	turbo->setChecked(false);
1101	turbo->setShortcut(tr("Shift+Tab"));
1102	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
1103	addControlledAction(emulationMenu, turbo, "fastForward");
1104
1105	QMenu* ffspeedMenu = emulationMenu->addMenu(tr("Fast forward speed"));
1106	ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
1107	ffspeed->connect([this](const QVariant& value) {
1108		m_controller->setTurboSpeed(value.toFloat());
1109	}, this);
1110	ffspeed->addValue(tr("Unbounded"), -1.0f, ffspeedMenu);
1111	ffspeed->setValue(QVariant(-1.0f));
1112	ffspeedMenu->addSeparator();
1113	for (i = 2; i < 11; ++i) {
1114		ffspeed->addValue(tr("%0x").arg(i), i, ffspeedMenu);
1115	}
1116	m_config->updateOption("fastForwardRatio");
1117
1118	m_inputModel->addFunctions(emulationMenu, [this]() {
1119		m_controller->startRewinding();
1120	}, [this]() {
1121		m_controller->stopRewinding();
1122	}, QKeySequence("`"), tr("Rewind (held)"), "holdRewind");
1123
1124	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
1125	rewind->setShortcut(tr("~"));
1126	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
1127	m_gameActions.append(rewind);
1128	m_nonMpActions.append(rewind);
1129	addControlledAction(emulationMenu, rewind, "rewind");
1130
1131	QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
1132	frameRewind->setShortcut(tr("Ctrl+B"));
1133	connect(frameRewind, &QAction::triggered, [this] () {
1134		m_controller->rewind(1);
1135	});
1136	m_gameActions.append(frameRewind);
1137	m_nonMpActions.append(frameRewind);
1138	addControlledAction(emulationMenu, frameRewind, "frameRewind");
1139
1140	ConfigOption* videoSync = m_config->addOption("videoSync");
1141	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
1142	videoSync->connect([this](const QVariant& value) {
1143		reloadConfig();
1144	}, this);
1145	m_config->updateOption("videoSync");
1146
1147	ConfigOption* audioSync = m_config->addOption("audioSync");
1148	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
1149	audioSync->connect([this](const QVariant& value) {
1150		reloadConfig();
1151	}, this);
1152	m_config->updateOption("audioSync");
1153
1154	emulationMenu->addSeparator();
1155
1156	QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
1157	m_inputModel->addMenu(solarMenu);
1158	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
1159	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
1160	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
1161
1162	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
1163	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
1164	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
1165
1166	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
1167	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
1168	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
1169
1170	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
1171	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
1172	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
1173
1174	solarMenu->addSeparator();
1175	for (int i = 0; i <= 10; ++i) {
1176		QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
1177		connect(setSolar, &QAction::triggered, [this, i]() {
1178			m_controller->setLuminanceLevel(i);
1179		});
1180		addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
1181	}
1182
1183	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
1184	m_inputModel->addMenu(avMenu);
1185	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
1186	m_inputModel->addMenu(frameMenu, avMenu);
1187	for (int i = 1; i <= 6; ++i) {
1188		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
1189		setSize->setCheckable(true);
1190		if (m_savedScale == i) {
1191			setSize->setChecked(true);
1192		}
1193		connect(setSize, &QAction::triggered, [this, i, setSize]() {
1194			showNormal();
1195			QSize size(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
1196			if (m_controller->isLoaded()) {
1197				size = m_controller->screenDimensions();
1198			}
1199			size *= i;
1200			m_savedScale = i;
1201			m_config->setOption("scaleMultiplier", i); // TODO: Port to other
1202			resizeFrame(size);
1203			bool enableSignals = setSize->blockSignals(true);
1204			setSize->setChecked(true);
1205			setSize->blockSignals(enableSignals);
1206		});
1207		m_frameSizes[i] = setSize;
1208		addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
1209	}
1210	QKeySequence fullscreenKeys;
1211#ifdef Q_OS_WIN
1212	fullscreenKeys = QKeySequence("Alt+Return");
1213#else
1214	fullscreenKeys = QKeySequence("Ctrl+F");
1215#endif
1216	addControlledAction(frameMenu, frameMenu->addAction(tr("Toggle fullscreen"), this, SLOT(toggleFullScreen()), fullscreenKeys), "fullscreen");
1217
1218	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1219	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
1220	lockAspectRatio->connect([this](const QVariant& value) {
1221		m_display->lockAspectRatio(value.toBool());
1222	}, this);
1223	m_config->updateOption("lockAspectRatio");
1224
1225	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1226	resampleVideo->addBoolean(tr("Bilinear filtering"), avMenu);
1227	resampleVideo->connect([this](const QVariant& value) {
1228		m_display->filter(value.toBool());
1229	}, this);
1230	m_config->updateOption("resampleVideo");
1231
1232	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
1233	ConfigOption* skip = m_config->addOption("frameskip");
1234	skip->connect([this](const QVariant& value) {
1235		reloadConfig();
1236	}, this);
1237	for (int i = 0; i <= 10; ++i) {
1238		skip->addValue(QString::number(i), i, skipMenu);
1239	}
1240	m_config->updateOption("frameskip");
1241
1242	QAction* shaderView = new QAction(tr("Shader options..."), avMenu);
1243	connect(shaderView, SIGNAL(triggered()), m_shaderView, SLOT(show()));
1244	if (!m_display->supportsShaders()) {
1245		shaderView->setEnabled(false);
1246	}
1247	addControlledAction(avMenu, shaderView, "shaderSelector");
1248
1249	avMenu->addSeparator();
1250
1251	ConfigOption* mute = m_config->addOption("mute");
1252	mute->addBoolean(tr("Mute"), avMenu);
1253	mute->connect([this](const QVariant& value) {
1254		reloadConfig();
1255	}, this);
1256	m_config->updateOption("mute");
1257
1258	QMenu* target = avMenu->addMenu(tr("FPS target"));
1259	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1260	fpsTargetOption->connect([this](const QVariant& value) {
1261		emit fpsTargetChanged(value.toFloat());
1262	}, this);
1263	fpsTargetOption->addValue(tr("15"), 15, target);
1264	fpsTargetOption->addValue(tr("30"), 30, target);
1265	fpsTargetOption->addValue(tr("45"), 45, target);
1266	fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
1267	fpsTargetOption->addValue(tr("60"), 60, target);
1268	fpsTargetOption->addValue(tr("90"), 90, target);
1269	fpsTargetOption->addValue(tr("120"), 120, target);
1270	fpsTargetOption->addValue(tr("240"), 240, target);
1271	m_config->updateOption("fpsTarget");
1272
1273#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
1274	avMenu->addSeparator();
1275#endif
1276
1277#ifdef USE_PNG
1278	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
1279	screenshot->setShortcut(tr("F12"));
1280	connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
1281	m_gameActions.append(screenshot);
1282	addControlledAction(avMenu, screenshot, "screenshot");
1283#endif
1284
1285#ifdef USE_FFMPEG
1286	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
1287	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
1288	addControlledAction(avMenu, recordOutput, "recordOutput");
1289	m_gameActions.append(recordOutput);
1290#endif
1291
1292#ifdef USE_MAGICK
1293	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
1294	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
1295	addControlledAction(avMenu, recordGIF, "recordGIF");
1296#endif
1297
1298	avMenu->addSeparator();
1299	QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
1300	m_inputModel->addMenu(videoLayers, avMenu);
1301
1302	for (int i = 0; i < 4; ++i) {
1303		QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
1304		enableBg->setCheckable(true);
1305		enableBg->setChecked(true);
1306		connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->setVideoLayerEnabled(i, enable); });
1307		addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
1308	}
1309
1310	QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
1311	enableObj->setCheckable(true);
1312	enableObj->setChecked(true);
1313	connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->setVideoLayerEnabled(4, enable); });
1314	addControlledAction(videoLayers, enableObj, "enableOBJ");
1315
1316	QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
1317	m_inputModel->addMenu(audioChannels, avMenu);
1318
1319	for (int i = 0; i < 4; ++i) {
1320		QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
1321		enableCh->setCheckable(true);
1322		enableCh->setChecked(true);
1323		connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(i, enable); });
1324		addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
1325	}
1326
1327	QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
1328	enableChA->setCheckable(true);
1329	enableChA->setChecked(true);
1330	connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(4, enable); });
1331	addControlledAction(audioChannels, enableChA, QString("enableChA"));
1332
1333	QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
1334	enableChB->setCheckable(true);
1335	enableChB->setChecked(true);
1336	connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(5, enable); });
1337	addControlledAction(audioChannels, enableChB, QString("enableChB"));
1338
1339	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
1340	m_inputModel->addMenu(toolsMenu);
1341	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
1342	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
1343	addControlledAction(toolsMenu, viewLogs, "viewLogs");
1344
1345	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
1346	connect(overrides, &QAction::triggered, openTView<OverrideView, ConfigController*>(m_config));
1347	addControlledAction(toolsMenu, overrides, "overrideWindow");
1348
1349	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
1350	connect(sensors, &QAction::triggered, openTView<SensorView, InputController*>(&m_inputController));
1351	addControlledAction(toolsMenu, sensors, "sensorWindow");
1352
1353	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1354	connect(cheats, &QAction::triggered, openTView<CheatsView>());
1355	m_gameActions.append(cheats);
1356	addControlledAction(toolsMenu, cheats, "cheatsWindow");
1357
1358	toolsMenu->addSeparator();
1359	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())),
1360	                    "settings");
1361
1362	toolsMenu->addSeparator();
1363
1364#ifdef USE_DEBUGGERS
1365	QAction* consoleWindow = new QAction(tr("Open debugger console..."), toolsMenu);
1366	connect(consoleWindow, SIGNAL(triggered()), this, SLOT(consoleOpen()));
1367	addControlledAction(toolsMenu, consoleWindow, "debuggerWindow");
1368#endif
1369
1370#ifdef USE_GDB_STUB
1371	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1372	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
1373	m_gbaActions.append(gdbWindow);
1374	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1375#endif
1376	toolsMenu->addSeparator();
1377
1378	QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1379	connect(paletteView, &QAction::triggered, openTView<PaletteView>());
1380	m_gameActions.append(paletteView);
1381	addControlledAction(toolsMenu, paletteView, "paletteWindow");
1382
1383	QAction* objView = new QAction(tr("View &sprites..."), toolsMenu);
1384	connect(objView, &QAction::triggered, openTView<ObjView>());
1385	m_gameActions.append(objView);
1386	addControlledAction(toolsMenu, objView, "spriteWindow");
1387
1388	QAction* tileView = new QAction(tr("View &tiles..."), toolsMenu);
1389	connect(tileView, &QAction::triggered, openTView<TileView>());
1390	m_gameActions.append(tileView);
1391	addControlledAction(toolsMenu, tileView, "tileWindow");
1392
1393	QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1394	connect(memoryView, &QAction::triggered, openTView<MemoryView>());
1395	m_gameActions.append(memoryView);
1396	addControlledAction(toolsMenu, memoryView, "memoryView");
1397
1398#ifdef M_CORE_GBA
1399	QAction* ioViewer = new QAction(tr("View &I/O registers..."), toolsMenu);
1400	connect(ioViewer, &QAction::triggered, openTView<IOViewer>());
1401	m_gameActions.append(ioViewer);
1402	m_gbaActions.append(ioViewer);
1403	addControlledAction(toolsMenu, ioViewer, "ioViewer");
1404#endif
1405
1406	ConfigOption* skipBios = m_config->addOption("skipBios");
1407	skipBios->connect([this](const QVariant& value) {
1408		reloadConfig();
1409	}, this);
1410
1411	ConfigOption* useBios = m_config->addOption("useBios");
1412	useBios->connect([this](const QVariant& value) {
1413		m_controller->setUseBIOS(value.toBool());
1414	}, this);
1415
1416	ConfigOption* buffers = m_config->addOption("audioBuffers");
1417	buffers->connect([this](const QVariant& value) {
1418		emit audioBufferSamplesChanged(value.toInt());
1419	}, this);
1420
1421	ConfigOption* sampleRate = m_config->addOption("sampleRate");
1422	sampleRate->connect([this](const QVariant& value) {
1423		emit sampleRateChanged(value.toUInt());
1424	}, this);
1425
1426	ConfigOption* volume = m_config->addOption("volume");
1427	volume->connect([this](const QVariant& value) {
1428		reloadConfig();
1429	}, this);
1430
1431	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1432	rewindEnable->connect([this](const QVariant& value) {
1433		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindSave").toInt());
1434	}, this);
1435
1436	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1437	rewindBufferCapacity->connect([this](const QVariant& value) {
1438		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindSave").toInt());
1439	}, this);
1440
1441	ConfigOption* rewindSave = m_config->addOption("rewindSave");
1442	rewindBufferCapacity->connect([this](const QVariant& value) {
1443		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toBool());
1444	}, this);
1445
1446	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1447	allowOpposingDirections->connect([this](const QVariant& value) {
1448		m_inputController.setAllowOpposing(value.toBool());
1449	}, this);
1450
1451	ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1452	saveStateExtdata->connect([this](const QVariant& value) {
1453		m_controller->setSaveStateExtdata(value.toInt());
1454	}, this);
1455
1456	ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1457	loadStateExtdata->connect([this](const QVariant& value) {
1458		m_controller->setLoadStateExtdata(value.toInt());
1459	}, this);
1460
1461	QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1462	connect(exitFullScreen, SIGNAL(triggered()), this, SLOT(exitFullScreen()));
1463	exitFullScreen->setShortcut(QKeySequence("Esc"));
1464	addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1465
1466	foreach (QAction* action, m_gameActions) {
1467		action->setDisabled(true);
1468	}
1469}
1470
1471void Window::attachWidget(QWidget* widget) {
1472	m_screenWidget->layout()->addWidget(widget);
1473	m_screenWidget->unsetCursor();
1474	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1475}
1476
1477void Window::detachWidget(QWidget* widget) {
1478	m_screenWidget->layout()->removeWidget(widget);
1479}
1480
1481void Window::appendMRU(const QString& fname) {
1482	int index = m_mruFiles.indexOf(fname);
1483	if (index >= 0) {
1484		m_mruFiles.removeAt(index);
1485	}
1486	m_mruFiles.prepend(fname);
1487	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1488		m_mruFiles.removeLast();
1489	}
1490	updateMRU();
1491}
1492
1493void Window::updateMRU() {
1494	if (!m_mruMenu) {
1495		return;
1496	}
1497	for (QAction* action : m_mruMenu->actions()) {
1498		delete action;
1499	}
1500	m_mruMenu->clear();
1501	int i = 0;
1502	for (const QString& file : m_mruFiles) {
1503		QAction* item = new QAction(file, m_mruMenu);
1504		item->setShortcut(QString("Ctrl+%1").arg(i));
1505		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1506		m_mruMenu->addAction(item);
1507		++i;
1508	}
1509	m_config->setMRU(m_mruFiles);
1510	m_config->write();
1511	m_mruMenu->setEnabled(i > 0);
1512}
1513
1514QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1515	addHiddenAction(menu, action, name);
1516	menu->addAction(action);
1517	return action;
1518}
1519
1520QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1521	m_inputModel->addAction(menu, action, name);
1522	action->setShortcutContext(Qt::WidgetShortcut);
1523	addAction(action);
1524	return action;
1525}
1526
1527void Window::focusCheck() {
1528	if (!m_config->getOption("pauseOnFocusLost").toInt()) {
1529		return;
1530	}
1531	if (QGuiApplication::focusWindow() && m_autoresume) {
1532		m_controller->setPaused(false);
1533		m_autoresume = false;
1534	} else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1535		m_autoresume = true;
1536		m_controller->setPaused(true);
1537	}
1538}
1539
1540WindowBackground::WindowBackground(QWidget* parent)
1541	: QLabel(parent)
1542{
1543	setLayout(new QStackedLayout());
1544	layout()->setContentsMargins(0, 0, 0, 0);
1545	setAlignment(Qt::AlignCenter);
1546}
1547
1548void WindowBackground::setSizeHint(const QSize& hint) {
1549	m_sizeHint = hint;
1550}
1551
1552QSize WindowBackground::sizeHint() const {
1553	return m_sizeHint;
1554}
1555
1556void WindowBackground::setLockAspectRatio(int width, int height) {
1557	m_aspectWidth = width;
1558	m_aspectHeight = height;
1559}
1560
1561void WindowBackground::paintEvent(QPaintEvent*) {
1562	const QPixmap* logo = pixmap();
1563	if (!logo) {
1564		return;
1565	}
1566	QPainter painter(this);
1567	painter.setRenderHint(QPainter::SmoothPixmapTransform);
1568	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1569	QSize s = size();
1570	QSize ds = s;
1571	if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
1572		ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
1573	} else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
1574		ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
1575	}
1576	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1577	QRect full(origin, ds);
1578	painter.drawPixmap(full, *logo);
1579}