all repos — mgba @ b8fe87324f8987db99ede4b3332a9ea781726e85

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