all repos — mgba @ 253ca1d1b806962487fcf892d5d03442f512f27d

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