all repos — mgba @ db8bb29c5a7b7efcd4d086ee383870a2565792e2

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