all repos — mgba @ 7cad9ab33a3ac07060bc971c3a2f9e86d15424ff

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