all repos — mgba @ 51c405011ff299a1eebdcebf8d6bbfb9afb67108

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	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 title[13] = { '\0' };
522	GBAGetGameTitle(m_controller->thread()->gba, title);
523	if (m_frameList.isEmpty()) {
524		setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
525		return;
526	}
527	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
528	float fps = (m_frameList.count() - 1) * 10000.f / interval;
529	fps = round(fps) / 10.f;
530	setWindowTitle(tr(PROJECT_NAME " - %1 (%2 fps)").arg(title).arg(fps));
531}
532
533void Window::openStateWindow(LoadSave ls) {
534	if (m_stateWindow) {
535		return;
536	}
537	bool wasPaused = m_controller->isPaused();
538	m_stateWindow = new LoadSaveState(m_controller);
539	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
540	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
541	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
542		m_screenWidget->layout()->removeWidget(m_stateWindow);
543		m_stateWindow = nullptr;
544		setFocus();
545	});
546	if (!wasPaused) {
547		m_controller->setPaused(true);
548		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
549	}
550	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
551	m_stateWindow->setMode(ls);
552	attachWidget(m_stateWindow);
553}
554
555void Window::setupMenu(QMenuBar* menubar) {
556	menubar->clear();
557	QMenu* fileMenu = menubar->addMenu(tr("&File"));
558	m_shortcutController->addMenu(fileMenu);
559	installEventFilter(m_shortcutController);
560	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open), "loadROM");
561	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
562	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
563
564	m_mruMenu = fileMenu->addMenu(tr("Recent"));
565
566	fileMenu->addSeparator();
567
568	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
569	loadState->setShortcut(tr("F10"));
570	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
571	m_gameActions.append(loadState);
572	addControlledAction(fileMenu, loadState, "loadState");
573
574	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
575	saveState->setShortcut(tr("Shift+F10"));
576	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
577	m_gameActions.append(saveState);
578	addControlledAction(fileMenu, saveState, "saveState");
579
580	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
581	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
582	int i;
583	for (i = 1; i < 10; ++i) {
584		QAction* quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
585		quickLoad->setShortcut(tr("F%1").arg(i));
586		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
587		m_gameActions.append(quickLoad);
588		addAction(quickLoad);
589		quickLoadMenu->addAction(quickLoad);
590
591		QAction* quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
592		quickSave->setShortcut(tr("Shift+F%1").arg(i));
593		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
594		m_gameActions.append(quickSave);
595		addAction(quickSave);
596		quickSaveMenu->addAction(quickSave);
597	}
598
599	fileMenu->addSeparator();
600	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
601	connect(multiWindow, &QAction::triggered, [this]() {
602		std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
603		if (!multiplayer) {
604			multiplayer = std::make_shared<MultiplayerController>();
605			m_controller->setMultiplayerController(multiplayer);
606		}
607		Window* w2 = new Window(m_config, multiplayer->attached());
608		w2->setAttribute(Qt::WA_DeleteOnClose);
609		w2->loadConfig();
610		w2->controller()->setMultiplayerController(multiplayer);
611		w2->show();
612	});
613	addControlledAction(fileMenu, multiWindow, "multiWindow");
614
615#ifndef Q_OS_MAC
616	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
617#endif
618
619	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
620	m_shortcutController->addMenu(emulationMenu);
621	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
622	reset->setShortcut(tr("Ctrl+R"));
623	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
624	m_gameActions.append(reset);
625	addControlledAction(emulationMenu, reset, "reset");
626
627	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
628	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
629	m_gameActions.append(shutdown);
630	addControlledAction(emulationMenu, shutdown, "shutdown");
631	emulationMenu->addSeparator();
632
633	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
634	pause->setChecked(false);
635	pause->setCheckable(true);
636	pause->setShortcut(tr("Ctrl+P"));
637	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
638	connect(m_controller, &GameController::gamePaused, [this, pause]() {
639		pause->setChecked(true);
640
641		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
642		QPixmap pixmap;
643		pixmap.convertFromImage(currentImage.rgbSwapped());
644		m_screenWidget->setPixmap(pixmap);
645		m_screenWidget->setLockAspectRatio(3, 2);
646	});
647	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
648	m_gameActions.append(pause);
649	addControlledAction(emulationMenu, pause, "pause");
650
651	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
652	frameAdvance->setShortcut(tr("Ctrl+N"));
653	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
654	m_gameActions.append(frameAdvance);
655	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
656
657	emulationMenu->addSeparator();
658
659	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
660	turbo->setCheckable(true);
661	turbo->setChecked(false);
662	turbo->setShortcut(tr("Shift+Tab"));
663	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
664	addControlledAction(emulationMenu, turbo, "fastForward");
665
666	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
667	rewind->setShortcut(tr("`"));
668	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
669	m_gameActions.append(rewind);
670	addControlledAction(emulationMenu, rewind, "rewind");
671
672	ConfigOption* videoSync = m_config->addOption("videoSync");
673	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
674	videoSync->connect([this](const QVariant& value) {
675		m_controller->setVideoSync(value.toBool());
676	}, this);
677	m_config->updateOption("videoSync");
678
679	ConfigOption* audioSync = m_config->addOption("audioSync");
680	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
681	audioSync->connect([this](const QVariant& value) {
682		m_controller->setAudioSync(value.toBool());
683	}, this);
684	m_config->updateOption("audioSync");
685
686	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
687	m_shortcutController->addMenu(avMenu);
688	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
689	m_shortcutController->addMenu(frameMenu, avMenu);
690	for (int i = 1; i <= 6; ++i) {
691		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
692		connect(setSize, &QAction::triggered, [this, i]() {
693			showNormal();
694			resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
695		});
696		addControlledAction(frameMenu, setSize, tr("frame%1x").arg(QString::number(i)));
697	}
698	addControlledAction(frameMenu, frameMenu->addAction(tr("Fullscreen"), this, SLOT(toggleFullScreen()), QKeySequence("Ctrl+F")), "fullscreen");
699
700	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
701	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
702	lockAspectRatio->connect([this](const QVariant& value) {
703		m_display->lockAspectRatio(value.toBool());
704	}, this);
705	m_config->updateOption("lockAspectRatio");
706
707	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
708	resampleVideo->addBoolean(tr("Resample video"), avMenu);
709	resampleVideo->connect([this](const QVariant& value) {
710		m_display->filter(value.toBool());
711	}, this);
712	m_config->updateOption("resampleVideo");
713
714	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
715	ConfigOption* skip = m_config->addOption("frameskip");
716	skip->connect([this](const QVariant& value) {
717		m_controller->setFrameskip(value.toInt());
718	}, this);
719	for (int i = 0; i <= 10; ++i) {
720		skip->addValue(QString::number(i), i, skipMenu);
721	}
722	m_config->updateOption("frameskip");
723
724	avMenu->addSeparator();
725
726	QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
727	ConfigOption* buffers = m_config->addOption("audioBuffers");
728	buffers->connect([this](const QVariant& value) {
729		emit audioBufferSamplesChanged(value.toInt());
730	}, this);
731	buffers->addValue(tr("512"), 512, buffersMenu);
732	buffers->addValue(tr("768"), 768, buffersMenu);
733	buffers->addValue(tr("1024"), 1024, buffersMenu);
734	buffers->addValue(tr("2048"), 2048, buffersMenu);
735	buffers->addValue(tr("4096"), 4096, buffersMenu);
736	m_config->updateOption("audioBuffers");
737
738	avMenu->addSeparator();
739
740	QMenu* target = avMenu->addMenu("FPS target");
741	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
742	fpsTargetOption->connect([this](const QVariant& value) {
743		emit fpsTargetChanged(value.toInt());
744	}, this);
745	fpsTargetOption->addValue(tr("15"), 15, target);
746	fpsTargetOption->addValue(tr("30"), 30, target);
747	fpsTargetOption->addValue(tr("45"), 45, target);
748	fpsTargetOption->addValue(tr("60"), 60, target);
749	fpsTargetOption->addValue(tr("90"), 90, target);
750	fpsTargetOption->addValue(tr("120"), 120, target);
751	fpsTargetOption->addValue(tr("240"), 240, target);
752	m_config->updateOption("fpsTarget");
753
754#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
755	avMenu->addSeparator();
756#endif
757
758#ifdef USE_PNG
759	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
760	screenshot->setShortcut(tr("F12"));
761	connect(screenshot, SIGNAL(triggered()), m_display, SLOT(screenshot()));
762	m_gameActions.append(screenshot);
763	addControlledAction(avMenu, screenshot, "screenshot");
764#endif
765
766#ifdef USE_FFMPEG
767	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
768	recordOutput->setShortcut(tr("F11"));
769	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
770	addControlledAction(avMenu, recordOutput, "recordOutput");
771#endif
772
773#ifdef USE_MAGICK
774	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
775	recordGIF->setShortcut(tr("Shift+F11"));
776	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
777	addControlledAction(avMenu, recordGIF, "recordGIF");
778#endif
779
780	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
781	m_shortcutController->addMenu(toolsMenu);
782	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
783	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
784	addControlledAction(toolsMenu, viewLogs, "viewLogs");
785
786	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
787	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
788	addControlledAction(toolsMenu, overrides, "overrideWindow");
789
790	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
791	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
792	addControlledAction(toolsMenu, sensors, "sensorWindow");
793
794	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
795	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
796	addControlledAction(toolsMenu, cheats, "cheatsWindow");
797
798#ifdef USE_GDB_STUB
799	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
800	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
801	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
802#endif
803
804	QMenu* solarMenu = toolsMenu->addMenu(tr("Solar sensor"));
805	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
806	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
807	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
808
809	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
810	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
811	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
812
813	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
814	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
815	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
816
817	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
818	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
819	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
820
821	toolsMenu->addSeparator();
822	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())), "settings");
823	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())), "shortcuts");
824
825	QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
826	connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
827	addControlledAction(toolsMenu, keymap, "remapKeyboard");
828
829#ifdef BUILD_SDL
830	QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
831	connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
832	addControlledAction(toolsMenu, gamepad, "remapGamepad");
833#endif
834
835	ConfigOption* skipBios = m_config->addOption("skipBios");
836	skipBios->connect([this](const QVariant& value) {
837		m_controller->setSkipBIOS(value.toBool());
838	}, this);
839
840	ConfigOption* useBios = m_config->addOption("useBios");
841	useBios->connect([this](const QVariant& value) {
842		m_controller->setUseBIOS(value.toBool());
843	}, this);
844
845	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
846	rewindEnable->connect([this](const QVariant& value) {
847		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
848	}, this);
849
850	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
851	rewindBufferCapacity->connect([this](const QVariant& value) {
852		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
853	}, this);
854
855	ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
856	rewindBufferInterval->connect([this](const QVariant& value) {
857		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
858	}, this);
859
860	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
861	allowOpposingDirections->connect([this](const QVariant& value) {
862		m_inputController.setAllowOpposing(value.toBool());
863	}, this);
864
865	QMenu* other = new QMenu(tr("Other"), this);
866	m_shortcutController->addMenu(other);
867	m_shortcutController->addFunctions(other, [this]() {
868		m_controller->setTurbo(true, false);
869	}, [this]() {
870		m_controller->setTurbo(false, false);
871	}, QKeySequence(Qt::Key_Tab), tr("Fast Forward (held)"), "holdFastForward");
872
873	addControlledAction(other, other->addAction(tr("Exit fullscreen"), this, SLOT(exitFullScreen()), QKeySequence("Esc")), "exitFullScreen");
874
875	foreach (QAction* action, m_gameActions) {
876		action->setDisabled(true);
877	}
878}
879
880void Window::attachWidget(QWidget* widget) {
881	m_screenWidget->layout()->addWidget(widget);
882	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
883}
884
885void Window::detachWidget(QWidget* widget) {
886	m_screenWidget->layout()->removeWidget(widget);
887}
888
889void Window::appendMRU(const QString& fname) {
890	int index = m_mruFiles.indexOf(fname);
891	if (index >= 0) {
892		m_mruFiles.removeAt(index);
893	}
894	m_mruFiles.prepend(fname);
895	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
896		m_mruFiles.removeLast();
897	}
898	updateMRU();
899}
900
901void Window::updateMRU() {
902	if (!m_mruMenu) {
903		return;
904	}
905	m_mruMenu->clear();
906	int i = 0;
907	for (const QString& file : m_mruFiles) {
908		QAction* item = new QAction(file, m_mruMenu);
909		item->setShortcut(QString("Ctrl+%1").arg(i));
910		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
911		m_mruMenu->addAction(item);
912		++i;
913	}
914	m_config->setMRU(m_mruFiles);
915	m_config->write();
916	m_mruMenu->setEnabled(i > 0);
917}
918
919QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
920	m_shortcutController->addAction(menu, action, name);
921	menu->addAction(action);
922	action->setShortcutContext(Qt::WidgetShortcut);
923	addAction(action);
924	return action;
925}
926
927WindowBackground::WindowBackground(QWidget* parent)
928	: QLabel(parent)
929{
930	setLayout(new QStackedLayout());
931	layout()->setContentsMargins(0, 0, 0, 0);
932	setAlignment(Qt::AlignCenter);
933}
934
935void WindowBackground::setSizeHint(const QSize& hint) {
936	m_sizeHint = hint;
937}
938
939QSize WindowBackground::sizeHint() const {
940	return m_sizeHint;
941}
942
943void WindowBackground::setLockAspectRatio(int width, int height) {
944	m_aspectWidth = width;
945	m_aspectHeight = height;
946}
947
948void WindowBackground::paintEvent(QPaintEvent*) {
949	QPainter painter(this);
950	painter.setRenderHint(QPainter::SmoothPixmapTransform);
951	const QPixmap* logo = pixmap();
952	painter.fillRect(QRect(QPoint(), size()), Qt::black);
953	if (!logo) {
954		return;
955	}
956	QSize s = size();
957	QSize ds = s;
958	if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
959		ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
960	} else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
961		ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
962	}
963	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
964	QRect full(origin, ds);
965	painter.drawPixmap(full, *logo);
966}