all repos — mgba @ 723b91dfe346c9f59ddd37e5e2074699b791907f

mGBA Game Boy Advance Emulator

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

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