all repos — mgba @ 98ff2fb5348d0c4145b03ba380dd512949e78b52

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