all repos — mgba @ b6ddf8fd0081a9dc9b5b491f4ef573faf0779cad

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