all repos — mgba @ 4b957cb66d51cec6dd99d2c753a20d00529cfd5b

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::exitFullScreen() {
378	if (!isFullScreen()) {
379		return;
380	}
381	showNormal();
382	menuBar()->show();
383}
384
385void Window::toggleFullScreen() {
386	if (isFullScreen()) {
387		showNormal();
388		menuBar()->show();
389	} else {
390		showFullScreen();
391#ifndef Q_OS_MAC
392		if (m_controller->isLoaded() && !m_controller->isPaused()) {
393			menuBar()->hide();
394		}
395#endif
396	}
397}
398
399void Window::gameStarted(GBAThread* context) {
400	char title[13] = { '\0' };
401	MutexLock(&context->stateMutex);
402	if (context->state < THREAD_EXITING) {
403		emit startDrawing(m_controller->drawContext(), context);
404		GBAGetGameTitle(context->gba, title);
405	} else {
406		MutexUnlock(&context->stateMutex);
407		return;
408	}
409	MutexUnlock(&context->stateMutex);
410	foreach (QAction* action, m_gameActions) {
411		action->setDisabled(false);
412	}
413	appendMRU(context->fname);
414	setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
415	attachWidget(m_display);
416
417#ifndef Q_OS_MAC
418	if(isFullScreen()) {
419		menuBar()->hide();
420	}
421#endif
422
423	m_hitUnimplementedBiosCall = false;
424	m_fpsTimer.start();
425}
426
427void Window::gameStopped() {
428	foreach (QAction* action, m_gameActions) {
429		action->setDisabled(true);
430	}
431	setWindowTitle(tr(PROJECT_NAME));
432	detachWidget(m_display);
433	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
434	m_screenWidget->setPixmap(m_logo);
435
436	m_fpsTimer.stop();
437}
438
439void Window::gameCrashed(const QString& errorMessage) {
440	QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
441		tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
442		QMessageBox::Ok, this,  Qt::Sheet);
443	crash->setAttribute(Qt::WA_DeleteOnClose);
444	crash->show();
445}
446
447void Window::gameFailed() {
448	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
449		tr("Could not load game. Are you sure it's in the correct format?"),
450		QMessageBox::Ok, this,  Qt::Sheet);
451	fail->setAttribute(Qt::WA_DeleteOnClose);
452	fail->show();
453}
454
455void Window::unimplementedBiosCall(int call) {
456	if (m_hitUnimplementedBiosCall) {
457		return;
458	}
459	m_hitUnimplementedBiosCall = true;
460
461	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Unimplemented BIOS call"),
462		tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
463		QMessageBox::Ok, this,  Qt::Sheet);
464	fail->setAttribute(Qt::WA_DeleteOnClose);
465	fail->show();
466}
467
468void Window::recordFrame() {
469	m_frameList.append(QDateTime::currentDateTime());
470	while (m_frameList.count() > FRAME_LIST_SIZE) {
471		m_frameList.removeFirst();
472	}
473}
474
475void Window::showFPS() {
476	char title[13] = { '\0' };
477	GBAGetGameTitle(m_controller->thread()->gba, title);
478	if (m_frameList.isEmpty()) {
479		setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
480		return;
481	}
482	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
483	float fps = (m_frameList.count() - 1) * 10000.f / interval;
484	fps = round(fps) / 10.f;
485	setWindowTitle(tr(PROJECT_NAME " - %1 (%2 fps)").arg(title).arg(fps));
486}
487
488void Window::openStateWindow(LoadSave ls) {
489	if (m_stateWindow) {
490		return;
491	}
492	bool wasPaused = m_controller->isPaused();
493	m_stateWindow = new LoadSaveState(m_controller);
494	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
495	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
496	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
497		m_screenWidget->layout()->removeWidget(m_stateWindow);
498		m_stateWindow = nullptr;
499		setFocus();
500	});
501	if (!wasPaused) {
502		m_controller->setPaused(true);
503		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
504	}
505	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
506	m_stateWindow->setMode(ls);
507	attachWidget(m_stateWindow);
508}
509
510void Window::setupMenu(QMenuBar* menubar) {
511	menubar->clear();
512	QMenu* fileMenu = menubar->addMenu(tr("&File"));
513	m_shortcutController->addMenu(fileMenu);
514	installEventFilter(m_shortcutController);
515	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open), "loadROM");
516	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
517	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
518
519	m_mruMenu = fileMenu->addMenu(tr("Recent"));
520
521	fileMenu->addSeparator();
522
523	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
524	loadState->setShortcut(tr("F10"));
525	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
526	m_gameActions.append(loadState);
527	addControlledAction(fileMenu, loadState, "loadState");
528
529	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
530	saveState->setShortcut(tr("Shift+F10"));
531	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
532	m_gameActions.append(saveState);
533	addControlledAction(fileMenu, saveState, "saveState");
534
535	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
536	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
537	int i;
538	for (i = 1; i < 10; ++i) {
539		QAction* quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
540		quickLoad->setShortcut(tr("F%1").arg(i));
541		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
542		m_gameActions.append(quickLoad);
543		addAction(quickLoad);
544		quickLoadMenu->addAction(quickLoad);
545
546		QAction* quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
547		quickSave->setShortcut(tr("Shift+F%1").arg(i));
548		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
549		m_gameActions.append(quickSave);
550		addAction(quickSave);
551		quickSaveMenu->addAction(quickSave);
552	}
553
554	fileMenu->addSeparator();
555	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
556	connect(multiWindow, &QAction::triggered, [this]() {
557		std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
558		if (!multiplayer) {
559			multiplayer = std::make_shared<MultiplayerController>();
560			m_controller->setMultiplayerController(multiplayer);
561		}
562		Window* w2 = new Window(m_config, multiplayer->attached());
563		w2->setAttribute(Qt::WA_DeleteOnClose);
564		w2->loadConfig();
565		w2->controller()->setMultiplayerController(multiplayer);
566		w2->show();
567	});
568	addControlledAction(fileMenu, multiWindow, "multiWindow");
569
570#ifndef Q_OS_MAC
571	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
572#endif
573
574	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
575	m_shortcutController->addMenu(emulationMenu);
576	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
577	reset->setShortcut(tr("Ctrl+R"));
578	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
579	m_gameActions.append(reset);
580	addControlledAction(emulationMenu, reset, "reset");
581
582	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
583	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
584	m_gameActions.append(shutdown);
585	addControlledAction(emulationMenu, shutdown, "shutdown");
586	emulationMenu->addSeparator();
587
588	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
589	pause->setChecked(false);
590	pause->setCheckable(true);
591	pause->setShortcut(tr("Ctrl+P"));
592	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
593	connect(m_controller, &GameController::gamePaused, [this, pause]() {
594		pause->setChecked(true);
595
596		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
597		QPixmap pixmap;
598		pixmap.convertFromImage(currentImage.rgbSwapped());
599		m_screenWidget->setPixmap(pixmap);
600		m_screenWidget->setLockAspectRatio(3, 2);
601	});
602	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
603	m_gameActions.append(pause);
604	addControlledAction(emulationMenu, pause, "pause");
605
606	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
607	frameAdvance->setShortcut(tr("Ctrl+N"));
608	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
609	m_gameActions.append(frameAdvance);
610	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
611
612	emulationMenu->addSeparator();
613
614	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
615	turbo->setCheckable(true);
616	turbo->setChecked(false);
617	turbo->setShortcut(tr("Shift+Tab"));
618	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
619	addControlledAction(emulationMenu, turbo, "fastForward");
620
621	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
622	rewind->setShortcut(tr("`"));
623	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
624	m_gameActions.append(rewind);
625	addControlledAction(emulationMenu, rewind, "rewind");
626
627	ConfigOption* videoSync = m_config->addOption("videoSync");
628	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
629	videoSync->connect([this](const QVariant& value) {
630		m_controller->setVideoSync(value.toBool());
631	}, this);
632	m_config->updateOption("videoSync");
633
634	ConfigOption* audioSync = m_config->addOption("audioSync");
635	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
636	audioSync->connect([this](const QVariant& value) {
637		m_controller->setAudioSync(value.toBool());
638	}, this);
639	m_config->updateOption("audioSync");
640
641	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
642	m_shortcutController->addMenu(avMenu);
643	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
644	m_shortcutController->addMenu(frameMenu, avMenu);
645	for (int i = 1; i <= 6; ++i) {
646		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
647		connect(setSize, &QAction::triggered, [this, i]() {
648			showNormal();
649			resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
650		});
651		addControlledAction(frameMenu, setSize, tr("frame%1x").arg(QString::number(i)));
652	}
653	addControlledAction(frameMenu, frameMenu->addAction(tr("Fullscreen"), this, SLOT(toggleFullScreen()), QKeySequence("Ctrl+F")), "fullscreen");
654
655	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
656	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
657	lockAspectRatio->connect([this](const QVariant& value) {
658		m_display->lockAspectRatio(value.toBool());
659	}, this);
660	m_config->updateOption("lockAspectRatio");
661
662	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
663	resampleVideo->addBoolean(tr("Resample video"), avMenu);
664	resampleVideo->connect([this](const QVariant& value) {
665		m_display->filter(value.toBool());
666	}, this);
667	m_config->updateOption("resampleVideo");
668
669	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
670	ConfigOption* skip = m_config->addOption("frameskip");
671	skip->connect([this](const QVariant& value) {
672		m_controller->setFrameskip(value.toInt());
673	}, this);
674	for (int i = 0; i <= 10; ++i) {
675		skip->addValue(QString::number(i), i, skipMenu);
676	}
677	m_config->updateOption("frameskip");
678
679	avMenu->addSeparator();
680
681	QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
682	ConfigOption* buffers = m_config->addOption("audioBuffers");
683	buffers->connect([this](const QVariant& value) {
684		emit audioBufferSamplesChanged(value.toInt());
685	}, this);
686	buffers->addValue(tr("512"), 512, buffersMenu);
687	buffers->addValue(tr("768"), 768, buffersMenu);
688	buffers->addValue(tr("1024"), 1024, buffersMenu);
689	buffers->addValue(tr("2048"), 2048, buffersMenu);
690	buffers->addValue(tr("4096"), 4096, buffersMenu);
691	m_config->updateOption("audioBuffers");
692
693	avMenu->addSeparator();
694
695	QMenu* target = avMenu->addMenu("FPS target");
696	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
697	fpsTargetOption->connect([this](const QVariant& value) {
698		emit fpsTargetChanged(value.toInt());
699	}, this);
700	fpsTargetOption->addValue(tr("15"), 15, target);
701	fpsTargetOption->addValue(tr("30"), 30, target);
702	fpsTargetOption->addValue(tr("45"), 45, target);
703	fpsTargetOption->addValue(tr("60"), 60, target);
704	fpsTargetOption->addValue(tr("90"), 90, target);
705	fpsTargetOption->addValue(tr("120"), 120, target);
706	fpsTargetOption->addValue(tr("240"), 240, target);
707	m_config->updateOption("fpsTarget");
708
709#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
710	avMenu->addSeparator();
711#endif
712
713#ifdef USE_PNG
714	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
715	screenshot->setShortcut(tr("F12"));
716	connect(screenshot, SIGNAL(triggered()), m_display, SLOT(screenshot()));
717	m_gameActions.append(screenshot);
718	addControlledAction(avMenu, screenshot, "screenshot");
719#endif
720
721#ifdef USE_FFMPEG
722	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
723	recordOutput->setShortcut(tr("F11"));
724	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
725	addControlledAction(avMenu, recordOutput, "recordOutput");
726#endif
727
728#ifdef USE_MAGICK
729	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
730	recordGIF->setShortcut(tr("Shift+F11"));
731	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
732	addControlledAction(avMenu, recordGIF, "recordGIF");
733#endif
734
735	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
736	m_shortcutController->addMenu(toolsMenu);
737	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
738	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
739	addControlledAction(toolsMenu, viewLogs, "viewLogs");
740
741	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
742	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
743	addControlledAction(toolsMenu, overrides, "overrideWindow");
744
745	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
746	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
747	addControlledAction(toolsMenu, sensors, "sensorWindow");
748
749	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
750	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
751	addControlledAction(toolsMenu, cheats, "cheatsWindow");
752
753#ifdef USE_GDB_STUB
754	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
755	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
756	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
757#endif
758
759	QMenu* solarMenu = toolsMenu->addMenu(tr("Solar sensor"));
760	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
761	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
762	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
763
764	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
765	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
766	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
767
768	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
769	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
770	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
771
772	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
773	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
774	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
775
776	toolsMenu->addSeparator();
777	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())), "settings");
778	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())), "shortcuts");
779
780	QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
781	connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
782	addControlledAction(toolsMenu, keymap, "remapKeyboard");
783
784#ifdef BUILD_SDL
785	QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
786	connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
787	addControlledAction(toolsMenu, gamepad, "remapGamepad");
788#endif
789
790	ConfigOption* skipBios = m_config->addOption("skipBios");
791	skipBios->connect([this](const QVariant& value) {
792		m_controller->setSkipBIOS(value.toBool());
793	}, this);
794
795	ConfigOption* useBios = m_config->addOption("useBios");
796	useBios->connect([this](const QVariant& value) {
797		m_controller->setUseBIOS(value.toBool());
798	}, this);
799
800	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
801	rewindEnable->connect([this](const QVariant& value) {
802		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
803	}, this);
804
805	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
806	rewindBufferCapacity->connect([this](const QVariant& value) {
807		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
808	}, this);
809
810	ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
811	rewindBufferInterval->connect([this](const QVariant& value) {
812		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
813	}, this);
814
815	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
816	allowOpposingDirections->connect([this](const QVariant& value) {
817		m_inputController.setAllowOpposing(value.toBool());
818	}, this);
819
820	QMenu* other = new QMenu(tr("Other"), this);
821	m_shortcutController->addMenu(other);
822	m_shortcutController->addFunctions(other, [this]() {
823		m_controller->setTurbo(true, false);
824	}, [this]() {
825		m_controller->setTurbo(false, false);
826	}, QKeySequence(Qt::Key_Tab), tr("Fast Forward (held)"), "holdFastForward");
827
828	addControlledAction(other, other->addAction(tr("Exit fullscreen"), this, SLOT(exitFullScreen()), QKeySequence("Esc")), "exitFullscreen");
829
830	foreach (QAction* action, m_gameActions) {
831		action->setDisabled(true);
832	}
833}
834
835void Window::attachWidget(QWidget* widget) {
836	m_screenWidget->layout()->addWidget(widget);
837	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
838}
839
840void Window::detachWidget(QWidget* widget) {
841	m_screenWidget->layout()->removeWidget(widget);
842}
843
844void Window::appendMRU(const QString& fname) {
845	int index = m_mruFiles.indexOf(fname);
846	if (index >= 0) {
847		m_mruFiles.removeAt(index);
848	}
849	m_mruFiles.prepend(fname);
850	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
851		m_mruFiles.removeLast();
852	}
853	updateMRU();
854}
855
856void Window::updateMRU() {
857	if (!m_mruMenu) {
858		return;
859	}
860	m_mruMenu->clear();
861	int i = 0;
862	for (const QString& file : m_mruFiles) {
863		QAction* item = new QAction(file, m_mruMenu);
864		item->setShortcut(QString("Ctrl+%1").arg(i));
865		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
866		m_mruMenu->addAction(item);
867		++i;
868	}
869	m_config->setMRU(m_mruFiles);
870	m_config->write();
871	m_mruMenu->setEnabled(i > 0);
872}
873
874QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
875	m_shortcutController->addAction(menu, action, name);
876	menu->addAction(action);
877	addAction(action);
878	return action;
879}
880
881WindowBackground::WindowBackground(QWidget* parent)
882	: QLabel(parent)
883{
884	setLayout(new QStackedLayout());
885	layout()->setContentsMargins(0, 0, 0, 0);
886	setAlignment(Qt::AlignCenter);
887}
888
889void WindowBackground::setSizeHint(const QSize& hint) {
890	m_sizeHint = hint;
891}
892
893QSize WindowBackground::sizeHint() const {
894	return m_sizeHint;
895}
896
897void WindowBackground::setLockAspectRatio(int width, int height) {
898	m_aspectWidth = width;
899	m_aspectHeight = height;
900}
901
902void WindowBackground::paintEvent(QPaintEvent*) {
903	QPainter painter(this);
904	painter.setRenderHint(QPainter::SmoothPixmapTransform);
905	const QPixmap* logo = pixmap();
906	painter.fillRect(QRect(QPoint(), size()), Qt::black);
907	if (!logo) {
908		return;
909	}
910	QSize s = size();
911	QSize ds = s;
912	if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
913		ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
914	} else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
915		ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
916	}
917	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
918	QRect full(origin, ds);
919	painter.drawPixmap(full, *logo);
920}