all repos — mgba @ 34dc2ae6f51b2a19e8a23718b87d229dc0bbf007

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