all repos — mgba @ cab9f3343b64865761243cf3014cbcb4d6771c56

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