all repos — mgba @ 6d2e81d2461d5486eeb0d019580fc9dc2067cc92

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