all repos — mgba @ e9365cdda22f3c41b5b0f208cc248439e8b80676

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