all repos — mgba @ e9c82df5187212025d930d862beb523f373c74ed

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