all repos — mgba @ 963758c348585650fd22c9e1647c2ccec4aea568

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