all repos — mgba @ 536dc8f7ab9ec2512b90505a30eb14a4c0a6b4f6

mGBA Game Boy Advance Emulator

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

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