all repos — mgba @ 42a2a5737b62b020cf577af4abb20ffa4419b8ea

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