all repos — mgba @ 9c5852e89ea26959c7a1872c7cee8d02e11d2317

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