all repos — mgba @ f039234055a00181becf186ebceee71bfbbdc597

mGBA Game Boy Advance Emulator

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

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