all repos — mgba @ 24ff4e8a015c797d304b36be15df08868b811c63

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