all repos — mgba @ bcb1617a6996445faad0f5dede50bbd4d8d6f0b5

mGBA Game Boy Advance Emulator

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

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