all repos — mgba @ 609a9c5aa0c52de980bb55c09fd24eb85fb064e5

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