all repos — mgba @ 232880bb0074eac3308ece3b006cb01902bbe035

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