all repos — mgba @ 31862db5a5ce03443b167053dee051664455543c

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