all repos — mgba @ 739df1ed74018bc6fe0b011867b3179c0efe34d3

mGBA Game Boy Advance Emulator

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

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