all repos — mgba @ 5b7e39e45f03f0d30857d91158a293ff742506e6

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