all repos — mgba @ b3cf9ec162885dbdcf5aa6e4e5abbcd112d9ed5b

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