all repos — mgba @ 532261af2c689bb1fc1c722c5a58950fbaae8488

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