1 /* Copyright (c) 2013-2017 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 <QKeyEvent>
9 #include <QKeySequence>
10 #include <QMenuBar>
11 #include <QMessageBox>
12 #include <QMimeData>
13 #include <QPainter>
14 #include <QScreen>
15 #include <QStackedLayout>
16 #include <QWindow>
17 
18 #ifdef USE_SQLITE3
19 #include "ArchiveInspector.h"
20 #include "library/LibraryController.h"
21 #endif
22 
23 #include "AboutScreen.h"
24 #include "AudioProcessor.h"
25 #include "BattleChipView.h"
26 #include "CheatsView.h"
27 #include "ConfigController.h"
28 #include "CoreController.h"
29 #include "DebuggerConsole.h"
30 #include "DebuggerConsoleController.h"
31 #include "Display.h"
32 #include "DolphinConnector.h"
33 #include "CoreController.h"
34 #include "FrameView.h"
35 #include "GBAApp.h"
36 #include "GDBController.h"
37 #include "GDBWindow.h"
38 #include "GIFView.h"
39 #include "IOViewer.h"
40 #include "LoadSaveState.h"
41 #include "LogView.h"
42 #include "MapView.h"
43 #include "MemorySearch.h"
44 #include "MemoryView.h"
45 #include "MultiplayerController.h"
46 #include "OverrideView.h"
47 #include "ObjView.h"
48 #include "PaletteView.h"
49 #include "PlacementControl.h"
50 #include "PrinterView.h"
51 #include "ReportView.h"
52 #include "ROMInfo.h"
53 #include "SaveConverter.h"
54 #include "SensorView.h"
55 #include "ShaderSelector.h"
56 #include "ShortcutController.h"
57 #include "TileView.h"
58 #include "VideoProxy.h"
59 #include "VideoView.h"
60 #include "utils.h"
61 
62 #ifdef USE_DISCORD_RPC
63 #include "DiscordCoordinator.h"
64 #endif
65 
66 #include <mgba/core/version.h>
67 #include <mgba/core/cheats.h>
68 #ifdef M_CORE_GB
69 #include <mgba/internal/gb/gb.h>
70 #include <mgba/internal/gb/video.h>
71 #endif
72 #ifdef M_CORE_GBA
73 #include <mgba/gba/interface.h>
74 #include <mgba/internal/gba/gba.h>
75 #endif
76 #include <mgba/feature/commandline.h>
77 #include <mgba-util/vfs.h>
78 
79 using namespace QGBA;
80 
Window(CoreManager * manager,ConfigController * config,int playerId,QWidget * parent)81 Window::Window(CoreManager* manager, ConfigController* config, int playerId, QWidget* parent)
82 	: QMainWindow(parent)
83 	, m_manager(manager)
84 	, m_logView(new LogView(&m_log, this))
85 	, m_screenWidget(new WindowBackground())
86 	, m_config(config)
87 	, m_inputController(playerId, this)
88 	, m_shortcutController(new ShortcutController(this))
89 {
90 	setFocusPolicy(Qt::StrongFocus);
91 	setAcceptDrops(true);
92 	setAttribute(Qt::WA_DeleteOnClose);
93 	updateTitle();
94 
95 	m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
96 	m_logo = m_logo; // Free memory left over in old pixmap
97 
98 #if defined(M_CORE_GBA)
99 	float i = 2;
100 #elif defined(M_CORE_GB)
101 	float i = 3;
102 #endif
103 	QVariant multiplier = m_config->getOption("scaleMultiplier");
104 	if (!multiplier.isNull()) {
105 		m_savedScale = multiplier.toInt();
106 		i = m_savedScale;
107 	}
108 #ifdef USE_SQLITE3
109 	m_libraryView = new LibraryController(nullptr, ConfigController::configDir() + "/library.sqlite3", m_config);
110 	ConfigOption* showLibrary = m_config->addOption("showLibrary");
111 	showLibrary->connect([this](const QVariant& value) {
112 		if (value.toBool()) {
113 			if (m_controller) {
114 				m_screenWidget->layout()->addWidget(m_libraryView);
115 			} else {
116 				attachWidget(m_libraryView);
117 			}
118 		} else {
119 			detachWidget(m_libraryView);
120 		}
121 	}, this);
122 	m_config->updateOption("showLibrary");
123 	ConfigOption* libraryStyle = m_config->addOption("libraryStyle");
124 	libraryStyle->connect([this](const QVariant& value) {
125 		m_libraryView->setViewStyle(static_cast<LibraryStyle>(value.toInt()));
126 	}, this);
127 	m_config->updateOption("libraryStyle");
128 
129 	connect(m_libraryView, &LibraryController::startGame, [this]() {
130 		VFile* output = m_libraryView->selectedVFile();
131 		if (output) {
132 			QPair<QString, QString> path = m_libraryView->selectedPath();
133 			setController(m_manager->loadGame(output, path.second, path.first), path.first + "/" + path.second);
134 		}
135 	});
136 #endif
137 #if defined(M_CORE_GBA)
138 	resizeFrame(QSize(GBA_VIDEO_HORIZONTAL_PIXELS * i, GBA_VIDEO_VERTICAL_PIXELS * i));
139 #elif defined(M_CORE_GB)
140 	resizeFrame(QSize(GB_VIDEO_HORIZONTAL_PIXELS * i, GB_VIDEO_VERTICAL_PIXELS * i));
141 #endif
142 	setLogo();
143 	setCentralWidget(m_screenWidget);
144 
145 	connect(this, &Window::shutdown, m_logView, &QWidget::hide);
146 	connect(&m_fpsTimer, &QTimer::timeout, this, &Window::showFPS);
147 	connect(&m_focusCheck, &QTimer::timeout, this, &Window::focusCheck);
148 	connect(&m_inputController, &InputController::profileLoaded, m_shortcutController, &ShortcutController::loadProfile);
149 
150 	m_log.setLevels(mLOG_WARN | mLOG_ERROR | mLOG_FATAL);
151 	m_log.load(m_config);
152 	m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
153 	m_focusCheck.setInterval(200);
154 	m_mustRestart.setInterval(MUST_RESTART_TIMEOUT);
155 	m_mustRestart.setSingleShot(true);
156 
157 	m_shortcutController->setConfigController(m_config);
158 	m_shortcutController->setActionMapper(&m_actions);
159 	setupMenu(menuBar());
160 }
161 
~Window()162 Window::~Window() {
163 	delete m_logView;
164 
165 #ifdef USE_SQLITE3
166 	delete m_libraryView;
167 #endif
168 }
169 
argumentsPassed(mArguments * args)170 void Window::argumentsPassed(mArguments* args) {
171 	loadConfig();
172 
173 	if (args->patch) {
174 		m_pendingPatch = args->patch;
175 	}
176 
177 	if (args->savestate) {
178 		m_pendingState = args->savestate;
179 	}
180 
181 #ifdef USE_GDB_STUB
182 	if (args->debuggerType == DEBUGGER_GDB) {
183 		if (!m_gdbController) {
184 			m_gdbController = new GDBController(this);
185 			if (m_controller) {
186 				m_gdbController->setController(m_controller);
187 			}
188 			m_gdbController->attach();
189 			m_gdbController->listen();
190 		}
191 	}
192 #endif
193 
194 	if (args->fname) {
195 		setController(m_manager->loadGame(args->fname), args->fname);
196 	}
197 }
198 
resizeFrame(const QSize & size)199 void Window::resizeFrame(const QSize& size) {
200 	QSize newSize(size);
201 	if (windowHandle()) {
202 		QRect geom = windowHandle()->screen()->availableGeometry();
203 		if (newSize.width() > geom.width()) {
204 			newSize.setWidth(geom.width());
205 		}
206 		if (newSize.height() > geom.height()) {
207 			newSize.setHeight(geom.height());
208 		}
209 	}
210 	m_screenWidget->setSizeHint(newSize);
211 	newSize -= m_screenWidget->size();
212 	newSize += this->size();
213 	if (!isFullScreen()) {
214 		resize(newSize);
215 	}
216 }
217 
setConfig(ConfigController * config)218 void Window::setConfig(ConfigController* config) {
219 	m_config = config;
220 }
221 
loadConfig()222 void Window::loadConfig() {
223 	const mCoreOptions* opts = m_config->options();
224 	reloadConfig();
225 
226 	if (opts->width && opts->height) {
227 		resizeFrame(QSize(opts->width, opts->height));
228 	}
229 
230 	if (opts->fullscreen) {
231 		enterFullScreen();
232 	}
233 
234 	m_mruFiles = m_config->getMRU();
235 	updateMRU();
236 
237 	m_inputController.setConfiguration(m_config);
238 }
239 
reloadConfig()240 void Window::reloadConfig() {
241 	const mCoreOptions* opts = m_config->options();
242 
243 	m_log.setLevels(opts->logLevel);
244 
245 	if (m_controller) {
246 		m_controller->loadConfig(m_config);
247 		if (m_audioProcessor) {
248 			m_audioProcessor->setBufferSamples(opts->audioBuffers);
249 			m_audioProcessor->requestSampleRate(opts->sampleRate);
250 		}
251 		m_display->resizeContext();
252 	}
253 
254 	m_inputController.setScreensaverSuspendable(opts->suspendScreensaver);
255 }
256 
saveConfig()257 void Window::saveConfig() {
258 	m_inputController.saveConfiguration();
259 	m_config->write();
260 }
261 
getFilters() const262 QString Window::getFilters() const {
263 	QStringList filters;
264 	QStringList formats;
265 
266 #ifdef M_CORE_GBA
267 	QStringList gbaFormats{
268 		"*.gba",
269 #if defined(USE_LIBZIP) || defined(USE_MINIZIP)
270 		"*.zip",
271 #endif
272 #ifdef USE_LZMA
273 		"*.7z",
274 #endif
275 #ifdef USE_ELF
276 		"*.elf",
277 #endif
278 		"*.agb",
279 		"*.mb",
280 		"*.rom",
281 		"*.bin"};
282 	formats.append(gbaFormats);
283 	filters.append(tr("Game Boy Advance ROMs (%1)").arg(gbaFormats.join(QChar(' '))));
284 #endif
285 
286 #ifdef M_CORE_GB
287 	QStringList gbFormats{
288 		"*.gb",
289 		"*.gbc",
290 		"*.sgb",
291 #if defined(USE_LIBZIP) || defined(USE_MINIZIP)
292 		"*.zip",
293 #endif
294 #ifdef USE_LZMA
295 		"*.7z",
296 #endif
297 		"*.rom",
298 		"*.bin"};
299 	formats.append(gbFormats);
300 	filters.append(tr("Game Boy ROMs (%1)").arg(gbFormats.join(QChar(' '))));
301 #endif
302 
303 	formats.removeDuplicates();
304 	filters.prepend(tr("All ROMs (%1)").arg(formats.join(QChar(' '))));
305 	filters.append(tr("%1 Video Logs (*.mvl)").arg(projectName));
306 	return filters.join(";;");
307 }
308 
getFiltersArchive() const309 QString Window::getFiltersArchive() const {
310 	QStringList filters;
311 
312 	QStringList formats{
313 #if defined(USE_LIBZIP) || defined(USE_MINIZIP)
314 		"*.zip",
315 #endif
316 #ifdef USE_LZMA
317 		"*.7z",
318 #endif
319 	};
320 	filters.append(tr("Archives (%1)").arg(formats.join(QChar(' '))));
321 	return filters.join(";;");
322 }
323 
selectROM()324 void Window::selectROM() {
325 	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFilters());
326 	if (!filename.isEmpty()) {
327 		setController(m_manager->loadGame(filename), filename);
328 	}
329 }
330 
bootBIOS()331 void Window::bootBIOS() {
332 	setController(m_manager->loadBIOS(mPLATFORM_GBA, m_config->getOption("gba.bios")), QString());
333 }
334 
335 #ifdef USE_SQLITE3
selectROMInArchive()336 void Window::selectROMInArchive() {
337 	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFiltersArchive());
338 	if (filename.isEmpty()) {
339 		return;
340 	}
341 	ArchiveInspector* archiveInspector = new ArchiveInspector(filename);
342 	connect(archiveInspector, &QDialog::accepted, [this,  archiveInspector]() {
343 		VFile* output = archiveInspector->selectedVFile();
344 		QPair<QString, QString> path = archiveInspector->selectedPath();
345 		if (output) {
346 			setController(m_manager->loadGame(output, path.second, path.first), path.first + "/" + path.second);
347 		}
348 		archiveInspector->close();
349 	});
350 	archiveInspector->setAttribute(Qt::WA_DeleteOnClose);
351 	archiveInspector->show();
352 }
353 
addDirToLibrary()354 void Window::addDirToLibrary() {
355 	QString filename = GBAApp::app()->getOpenDirectoryName(this, tr("Select folder"));
356 	if (filename.isEmpty()) {
357 		return;
358 	}
359 	m_libraryView->addDirectory(filename);
360 }
361 #endif
362 
replaceROM()363 void Window::replaceROM() {
364 	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFilters());
365 	if (!filename.isEmpty()) {
366 		m_controller->replaceGame(filename);
367 	}
368 }
369 
selectSave(bool temporary)370 void Window::selectSave(bool temporary) {
371 	QStringList formats{"*.sav"};
372 	QString filter = tr("Save games (%1)").arg(formats.join(QChar(' ')));
373 	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save game"), filter);
374 	if (!filename.isEmpty()) {
375 		m_controller->loadSave(filename, temporary);
376 	}
377 }
378 
selectState(bool load)379 void Window::selectState(bool load) {
380 	QStringList formats{"*.ss0", "*.ss1", "*.ss2", "*.ss3", "*.ss4", "*.ss5", "*.ss6", "*.ss7", "*.ss8", "*.ss9"};
381 	QString filter = tr("mGBA save state files (%1)").arg(formats.join(QChar(' ')));
382 	if (load) {
383 		QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save state"), filter);
384 		if (!filename.isEmpty()) {
385 			m_controller->loadState(filename);
386 		}
387 	} else {
388 		QString filename = GBAApp::app()->getSaveFileName(this, tr("Select save state"), filter);
389 		if (!filename.isEmpty()) {
390 			m_controller->saveState(filename);
391 		}
392 	}
393 }
394 
multiplayerChanged()395 void Window::multiplayerChanged() {
396 	if (!m_controller) {
397 		return;
398 	}
399 	int attached = 1;
400 	MultiplayerController* multiplayer = m_controller->multiplayerController();
401 	if (multiplayer) {
402 		attached = multiplayer->attached();
403 	}
404 	for (Action* action : m_nonMpActions) {
405 		action->setEnabled(attached < 2);
406 	}
407 }
408 
selectPatch()409 void Window::selectPatch() {
410 	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select patch"), tr("Patches (*.ips *.ups *.bps)"));
411 	if (!filename.isEmpty()) {
412 		if (m_controller) {
413 			m_controller->loadPatch(filename);
414 		} else {
415 			m_pendingPatch = filename;
416 		}
417 	}
418 }
419 
scanCard()420 void Window::scanCard() {
421 	QStringList filenames = GBAApp::app()->getOpenFileNames(this, tr("Select e-Reader dotcode"), tr("e-Reader card (*.raw *.bin *.bmp)"));
422 	for (QString& filename : filenames) {
423 		m_controller->scanCard(filename);
424 	}
425 }
426 
openView(QWidget * widget)427 void Window::openView(QWidget* widget) {
428 	connect(this, &Window::shutdown, widget, &QWidget::close);
429 	widget->setAttribute(Qt::WA_DeleteOnClose);
430 	widget->show();
431 }
432 
loadCamImage()433 void Window::loadCamImage() {
434 	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select image"), tr("Image file (*.png *.gif *.jpg *.jpeg);;All files (*)"));
435 	if (!filename.isEmpty()) {
436 		m_inputController.loadCamImage(filename);
437 	}
438 }
439 
importSharkport()440 void Window::importSharkport() {
441 	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
442 	if (!filename.isEmpty()) {
443 		m_controller->importSharkport(filename);
444 	}
445 }
446 
exportSharkport()447 void Window::exportSharkport() {
448 	QString filename = GBAApp::app()->getSaveFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
449 	if (!filename.isEmpty()) {
450 		m_controller->exportSharkport(filename);
451 	}
452 }
453 
openSettingsWindow()454 void Window::openSettingsWindow() {
455 	openSettingsWindow(SettingsView::Page::AV);
456 }
457 
openSettingsWindow(SettingsView::Page page)458 void Window::openSettingsWindow(SettingsView::Page page) {
459 	SettingsView* settingsWindow = new SettingsView(m_config, &m_inputController, m_shortcutController, &m_log);
460 #if defined(BUILD_GL) || defined(BUILD_GLES2)
461 	if (m_display->supportsShaders()) {
462 		settingsWindow->setShaderSelector(m_shaderView.get());
463 	}
464 #endif
465 	connect(settingsWindow, &SettingsView::displayDriverChanged, this, &Window::reloadDisplayDriver);
466 	connect(settingsWindow, &SettingsView::audioDriverChanged, this, &Window::reloadAudioDriver);
467 	connect(settingsWindow, &SettingsView::cameraDriverChanged, this, &Window::mustRestart);
468 	connect(settingsWindow, &SettingsView::cameraChanged, &m_inputController, &InputController::setCamera);
469 	connect(settingsWindow, &SettingsView::videoRendererChanged, this, &Window::changeRenderer);
470 	connect(settingsWindow, &SettingsView::languageChanged, this, &Window::mustRestart);
471 	connect(settingsWindow, &SettingsView::pathsChanged, this, &Window::reloadConfig);
472 #ifdef USE_SQLITE3
473 	connect(settingsWindow, &SettingsView::libraryCleared, m_libraryView, &LibraryController::clear);
474 #endif
475 	openView(settingsWindow);
476 	settingsWindow->selectPage(page);
477 }
478 
startVideoLog()479 void Window::startVideoLog() {
480 	QString filename = GBAApp::app()->getSaveFileName(this, tr("Select video log"), tr("Video logs (*.mvl)"));
481 	if (!filename.isEmpty()) {
482 		m_controller->startVideoLog(filename);
483 	}
484 }
485 
486 template <typename T, typename... A>
openTView(A...arg)487 std::function<void()> Window::openTView(A... arg) {
488 	return [=]() {
489 		T* view = new T(arg...);
490 		openView(view);
491 	};
492 }
493 
494 template <typename T, typename... A>
openControllerTView(A...arg)495 std::function<void()> Window::openControllerTView(A... arg) {
496 	return [=]() {
497 		T* view = new T(m_controller, arg...);
498 		openView(view);
499 	};
500 }
501 
502 template <typename T, typename... A>
openNamedTView(std::unique_ptr<T> * name,A...arg)503 std::function<void()> Window::openNamedTView(std::unique_ptr<T>* name, A... arg) {
504 	return [=]() {
505 		if (!*name) {
506 			*name = std::make_unique<T>(arg...);
507 			connect(this, &Window::shutdown, name->get(), &QWidget::close);
508 		}
509 		(*name)->show();
510 		(*name)->setFocus(Qt::PopupFocusReason);
511 	};
512 }
513 
514 template <typename T, typename... A>
openNamedControllerTView(std::unique_ptr<T> * name,A...arg)515 std::function<void()> Window::openNamedControllerTView(std::unique_ptr<T>* name, A... arg) {
516 	return [=]() {
517 		if (!*name) {
518 			*name = std::make_unique<T>(arg...);
519 			if (m_controller) {
520 				(*name)->setController(m_controller);
521 			}
522 			connect(this, &Window::shutdown, name->get(), &QWidget::close);
523 		}
524 		(*name)->show();
525 		(*name)->setFocus(Qt::PopupFocusReason);
526 	};
527 }
528 
529 #ifdef USE_GDB_STUB
gdbOpen()530 void Window::gdbOpen() {
531 	if (!m_gdbController) {
532 		m_gdbController = new GDBController(this);
533 	}
534 	GDBWindow* window = new GDBWindow(m_gdbController);
535 	m_gdbController->setController(m_controller);
536 	connect(m_controller.get(), &CoreController::stopping, window, &QWidget::close);
537 	openView(window);
538 }
539 #endif
540 
541 #ifdef USE_DEBUGGERS
consoleOpen()542 void Window::consoleOpen() {
543 	if (!m_console) {
544 		m_console = new DebuggerConsoleController(this);
545 	}
546 	DebuggerConsole* window = new DebuggerConsole(m_console);
547 	if (m_controller) {
548 		m_console->setController(m_controller);
549 	}
550 	openView(window);
551 }
552 #endif
553 
keyPressEvent(QKeyEvent * event)554 void Window::keyPressEvent(QKeyEvent* event) {
555 	if (event->isAutoRepeat()) {
556 		QWidget::keyPressEvent(event);
557 		return;
558 	}
559 	GBAKey key = m_inputController.mapKeyboard(event->key());
560 	if (key == GBA_KEY_NONE) {
561 		QWidget::keyPressEvent(event);
562 		return;
563 	}
564 	if (m_controller) {
565 		m_controller->addKey(key);
566 	}
567 	event->accept();
568 }
569 
keyReleaseEvent(QKeyEvent * event)570 void Window::keyReleaseEvent(QKeyEvent* event) {
571 	if (event->isAutoRepeat()) {
572 		QWidget::keyReleaseEvent(event);
573 		return;
574 	}
575 	GBAKey key = m_inputController.mapKeyboard(event->key());
576 	if (key == GBA_KEY_NONE) {
577 		QWidget::keyPressEvent(event);
578 		return;
579 	}
580 	if (m_controller) {
581 		m_controller->clearKey(key);
582 	}
583 	event->accept();
584 }
585 
resizeEvent(QResizeEvent *)586 void Window::resizeEvent(QResizeEvent*) {
587 	if (!isFullScreen()) {
588 		m_config->setOption("height", m_screenWidget->height());
589 		m_config->setOption("width", m_screenWidget->width());
590 	}
591 
592 	int factor = 0;
593 	QSize size(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
594 	if (m_controller) {
595 		size = m_controller->screenDimensions();
596 	}
597 	if (m_screenWidget->width() % size.width() == 0 && m_screenWidget->height() % size.height() == 0 &&
598 	    m_screenWidget->width() / size.width() == m_screenWidget->height() / size.height()) {
599 		factor = m_screenWidget->width() / size.width();
600 	}
601 	m_savedScale = factor;
602 	for (QMap<int, Action*>::iterator iter = m_frameSizes.begin(); iter != m_frameSizes.end(); ++iter) {
603 		iter.value()->setActive(iter.key() == factor);
604 	}
605 
606 	m_config->setOption("fullscreen", isFullScreen());
607 }
608 
showEvent(QShowEvent * event)609 void Window::showEvent(QShowEvent* event) {
610 	if (m_wasOpened) {
611 		if (event->spontaneous() && m_config->getOption("pauseOnMinimize").toInt() && m_controller) {
612 			focusCheck();
613 			if (m_autoresume) {
614 				m_controller->setPaused(false);
615 				m_autoresume = false;
616 			}
617 		}
618 		return;
619 	}
620 	m_wasOpened = true;
621 	resizeFrame(m_screenWidget->sizeHint());
622 	QVariant windowPos = m_config->getQtOption("windowPos");
623 	bool maximized = m_config->getQtOption("maximized").toBool();
624 	QRect geom = windowHandle()->screen()->availableGeometry();
625 	if (!windowPos.isNull() && geom.contains(windowPos.toPoint())) {
626 		move(windowPos.toPoint());
627 	} else {
628 		QRect rect = frameGeometry();
629 		rect.moveCenter(geom.center());
630 		move(rect.topLeft());
631 	}
632 	if (maximized) {
633 		showMaximized();
634 	}
635 	if (m_fullscreenOnStart) {
636 		enterFullScreen();
637 		m_fullscreenOnStart = false;
638 	}
639 	reloadDisplayDriver();
640 	setFocus();
641 }
642 
hideEvent(QHideEvent * event)643 void Window::hideEvent(QHideEvent* event) {
644 	if (!event->spontaneous()) {
645 		return;
646 	}
647 	if (!m_config->getOption("pauseOnMinimize").toInt() || !m_controller) {
648 		return;
649 	}
650 	if (!m_controller->isPaused()) {
651 		m_autoresume = true;
652 		m_controller->setPaused(true);
653 	}
654 }
655 
closeEvent(QCloseEvent * event)656 void Window::closeEvent(QCloseEvent* event) {
657 	emit shutdown();
658 	m_config->setQtOption("windowPos", pos());
659 	m_config->setQtOption("maximized", isMaximized());
660 
661 	if (m_savedScale > 0) {
662 		m_config->setOption("height", GBA_VIDEO_VERTICAL_PIXELS * m_savedScale);
663 		m_config->setOption("width", GBA_VIDEO_HORIZONTAL_PIXELS * m_savedScale);
664 	}
665 	saveConfig();
666 	if (m_controller) {
667 		event->ignore();
668 		m_pendingClose = true;
669 	} else {
670 		m_display.reset();
671 	}
672 }
673 
focusInEvent(QFocusEvent *)674 void Window::focusInEvent(QFocusEvent*) {
675 	m_display->forceDraw();
676 }
677 
focusOutEvent(QFocusEvent *)678 void Window::focusOutEvent(QFocusEvent*) {
679 }
680 
dragEnterEvent(QDragEnterEvent * event)681 void Window::dragEnterEvent(QDragEnterEvent* event) {
682 	if (event->mimeData()->hasFormat("text/uri-list")) {
683 		event->acceptProposedAction();
684 	}
685 }
686 
dropEvent(QDropEvent * event)687 void Window::dropEvent(QDropEvent* event) {
688 	QString uris = event->mimeData()->data("text/uri-list");
689 	uris = uris.trimmed();
690 	if (uris.contains("\n")) {
691 		// Only one file please
692 		return;
693 	}
694 	QUrl url(uris);
695 	if (!url.isLocalFile()) {
696 		// No remote loading
697 		return;
698 	}
699 	event->accept();
700 	setController(m_manager->loadGame(url.toLocalFile()), url.toLocalFile());
701 }
702 
mouseDoubleClickEvent(QMouseEvent * event)703 void Window::mouseDoubleClickEvent(QMouseEvent* event) {
704 	if (event->button() != Qt::LeftButton) {
705 		return;
706 	}
707 	toggleFullScreen();
708 }
709 
enterFullScreen()710 void Window::enterFullScreen() {
711 	if (!isVisible()) {
712 		m_fullscreenOnStart = true;
713 		return;
714 	}
715 	if (isFullScreen()) {
716 		return;
717 	}
718 	showFullScreen();
719 #ifndef Q_OS_MAC
720 	if (m_controller && !m_controller->isPaused()) {
721 		menuBar()->hide();
722 	}
723 #endif
724 }
725 
exitFullScreen()726 void Window::exitFullScreen() {
727 	if (!isFullScreen()) {
728 		return;
729 	}
730 	m_screenWidget->unsetCursor();
731 	menuBar()->show();
732 	showNormal();
733 }
734 
toggleFullScreen()735 void Window::toggleFullScreen() {
736 	if (isFullScreen()) {
737 		exitFullScreen();
738 	} else {
739 		enterFullScreen();
740 	}
741 }
742 
gameStarted()743 void Window::gameStarted() {
744 	for (Action* action : m_gameActions) {
745 		action->setEnabled(true);
746 	}
747 	for (auto action = m_platformActions.begin(); action != m_platformActions.end(); ++action) {
748 		action.value()->setEnabled(m_controller->platform() == action.key());
749 	}
750 	QSize size = m_controller->screenDimensions();
751 	m_screenWidget->setDimensions(size.width(), size.height());
752 	m_config->updateOption("lockIntegerScaling");
753 	m_config->updateOption("lockAspectRatio");
754 	m_config->updateOption("interframeBlending");
755 	m_config->updateOption("resampleVideo");
756 	m_config->updateOption("showOSD");
757 	if (m_savedScale > 0) {
758 		resizeFrame(size * m_savedScale);
759 	}
760 	attachWidget(m_display.get());
761 	setFocus();
762 
763 #ifndef Q_OS_MAC
764 	if (isFullScreen()) {
765 		menuBar()->hide();
766 	}
767 #endif
768 
769 	reloadAudioDriver();
770 	multiplayerChanged();
771 	updateTitle();
772 
773 	m_hitUnimplementedBiosCall = false;
774 	if (m_config->getOption("showFps", "1").toInt()) {
775 		m_fpsTimer.start();
776 		m_frameTimer.start();
777 	}
778 	m_focusCheck.start();
779 	if (m_display->underMouse()) {
780 		m_screenWidget->setCursor(Qt::BlankCursor);
781 	}
782 
783 	CoreController::Interrupter interrupter(m_controller);
784 	mCore* core = m_controller->thread()->core;
785 	m_actions.clearMenu("videoLayers");
786 	m_actions.clearMenu("audioChannels");
787 	const mCoreChannelInfo* videoLayers;
788 	const mCoreChannelInfo* audioChannels;
789 	size_t nVideo = core->listVideoLayers(core, &videoLayers);
790 	size_t nAudio = core->listAudioChannels(core, &audioChannels);
791 
792 	if (nVideo) {
793 		for (size_t i = 0; i < nVideo; ++i) {
794 			Action* action = m_actions.addBooleanAction(videoLayers[i].visibleName, QString("videoLayer.%1").arg(videoLayers[i].internalName), [this, videoLayers, i](bool enable) {
795 				m_controller->thread()->core->enableVideoLayer(m_controller->thread()->core, videoLayers[i].id, enable);
796 			}, "videoLayers");
797 			action->setActive(true);
798 		}
799 	}
800 	if (nAudio) {
801 		for (size_t i = 0; i < nAudio; ++i) {
802 			Action* action = m_actions.addBooleanAction(audioChannels[i].visibleName, QString("audioChannel.%1").arg(audioChannels[i].internalName), [this, audioChannels, i](bool enable) {
803 				m_controller->thread()->core->enableAudioChannel(m_controller->thread()->core, audioChannels[i].id, enable);
804 			}, "audioChannels");
805 			action->setActive(true);
806 		}
807 	}
808 	m_actions.rebuildMenu(menuBar(), this, *m_shortcutController);
809 
810 #ifdef USE_DISCORD_RPC
811 	DiscordCoordinator::gameStarted(m_controller);
812 #endif
813 }
814 
gameStopped()815 void Window::gameStopped() {
816 	for (Action* action : m_platformActions) {
817 		action->setEnabled(true);
818 	}
819 	for (Action* action : m_gameActions) {
820 		action->setEnabled(false);
821 	}
822 	setWindowFilePath(QString());
823 
824 	m_actions.clearMenu("videoLayers");
825 	m_actions.clearMenu("audioChannels");
826 
827 	m_fpsTimer.stop();
828 	m_focusCheck.stop();
829 
830 	if (m_audioProcessor) {
831 		m_audioProcessor->stop();
832 		m_audioProcessor.reset();
833 	}
834 	m_display->stopDrawing();
835 	detachWidget(m_display.get());
836 	setLogo();
837 	if (m_display) {
838 #ifdef M_CORE_GB
839 		m_display->setMinimumSize(GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
840 #elif defined(M_CORE_GBA)
841 		m_display->setMinimumSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
842 #endif
843 	}
844 
845 	m_controller.reset();
846 	updateTitle();
847 
848 	if (m_pendingClose) {
849 		m_display.reset();
850 		close();
851 	}
852 #ifndef Q_OS_MAC
853 	menuBar()->show();
854 #endif
855 
856 #ifdef USE_DISCORD_RPC
857 	DiscordCoordinator::gameStopped();
858 #endif
859 
860 	emit paused(false);
861 }
862 
gameCrashed(const QString & errorMessage)863 void Window::gameCrashed(const QString& errorMessage) {
864 	QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
865 	                                     tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
866 	                                     QMessageBox::Ok, this, Qt::Sheet);
867 	crash->setAttribute(Qt::WA_DeleteOnClose);
868 	crash->show();
869 }
870 
gameFailed()871 void Window::gameFailed() {
872 	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Start"),
873 	                                    tr("Could not start game."),
874 	                                    QMessageBox::Ok, this, Qt::Sheet);
875 	fail->setAttribute(Qt::WA_DeleteOnClose);
876 	fail->show();
877 }
878 
unimplementedBiosCall(int)879 void Window::unimplementedBiosCall(int) {
880 	// TODO: Mention which call?
881 	if (m_hitUnimplementedBiosCall) {
882 		return;
883 	}
884 	m_hitUnimplementedBiosCall = true;
885 
886 	QMessageBox* fail = new QMessageBox(
887 	    QMessageBox::Warning, tr("Unimplemented BIOS call"),
888 	    tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
889 	    QMessageBox::Ok, this, Qt::Sheet);
890 	fail->setAttribute(Qt::WA_DeleteOnClose);
891 	fail->show();
892 }
893 
reloadDisplayDriver()894 void Window::reloadDisplayDriver() {
895 	if (m_controller) {
896 		m_display->stopDrawing();
897 		detachWidget(m_display.get());
898 	}
899 	m_display = std::unique_ptr<Display>(Display::create(this));
900 	if (!m_display) {
901 		LOG(QT, ERROR) << tr("Failed to create an appropriate display device, falling back to software display. "
902 		                     "Games may run slowly, especially with larger windows.");
903 		Display::setDriver(Display::Driver::QT);
904 		m_display = std::unique_ptr<Display>(Display::create(this));
905 	}
906 #if defined(BUILD_GL) || defined(BUILD_GLES2)
907 	m_shaderView.reset();
908 	m_shaderView = std::make_unique<ShaderSelector>(m_display.get(), m_config);
909 #endif
910 
911 	connect(m_display.get(), &Display::hideCursor, [this]() {
912 		if (static_cast<QStackedLayout*>(m_screenWidget->layout())->currentWidget() == m_display.get()) {
913 			m_screenWidget->setCursor(Qt::BlankCursor);
914 		}
915 	});
916 	connect(m_display.get(), &Display::showCursor, [this]() {
917 		m_screenWidget->unsetCursor();
918 	});
919 
920 	const mCoreOptions* opts = m_config->options();
921 	m_display->lockAspectRatio(opts->lockAspectRatio);
922 	m_display->lockIntegerScaling(opts->lockIntegerScaling);
923 	m_display->interframeBlending(opts->interframeBlending);
924 	m_display->filter(opts->resampleVideo);
925 	m_config->updateOption("showOSD");
926 #if defined(BUILD_GL) || defined(BUILD_GLES2)
927 	if (opts->shader) {
928 		struct VDir* shader = VDirOpen(opts->shader);
929 		if (shader && m_display->supportsShaders()) {
930 			m_display->setShaders(shader);
931 			m_shaderView->refreshShaders();
932 			shader->close(shader);
933 		}
934 	}
935 #endif
936 
937 	if (m_controller) {
938 		attachDisplay();
939 
940 		attachWidget(m_display.get());
941 	}
942 #ifdef M_CORE_GB
943 	m_display->setMinimumSize(GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
944 #elif defined(M_CORE_GBA)
945 	m_display->setMinimumSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
946 #endif
947 }
948 
reloadAudioDriver()949 void Window::reloadAudioDriver() {
950 	if (!m_controller) {
951 		return;
952 	}
953 	if (m_audioProcessor) {
954 		m_audioProcessor->stop();
955 		m_audioProcessor.reset();
956 	}
957 
958 	const mCoreOptions* opts = m_config->options();
959 	m_audioProcessor = std::unique_ptr<AudioProcessor>(AudioProcessor::create());
960 	m_audioProcessor->setInput(m_controller);
961 	m_audioProcessor->setBufferSamples(opts->audioBuffers);
962 	m_audioProcessor->requestSampleRate(opts->sampleRate);
963 	m_audioProcessor->start();
964 	connect(m_controller.get(), &CoreController::stopping, m_audioProcessor.get(), &AudioProcessor::stop);
965 	connect(m_controller.get(), &CoreController::fastForwardChanged, m_audioProcessor.get(), &AudioProcessor::inputParametersChanged);
966 	connect(m_controller.get(), &CoreController::paused, m_audioProcessor.get(), &AudioProcessor::pause);
967 	connect(m_controller.get(), &CoreController::unpaused, m_audioProcessor.get(), &AudioProcessor::start);
968 }
969 
changeRenderer()970 void Window::changeRenderer() {
971 	if (!m_controller) {
972 		return;
973 	}
974 	if (m_config->getOption("hwaccelVideo").toInt() && m_display->supportsShaders() && m_controller->supportsFeature(CoreController::Feature::OPENGL)) {
975 		std::shared_ptr<VideoProxy> proxy = m_display->videoProxy();
976 		if (!proxy) {
977 			proxy = std::make_shared<VideoProxy>();
978 		}
979 		m_display->setVideoProxy(proxy);
980 		proxy->attach(m_controller.get());
981 
982 		int fb = m_display->framebufferHandle();
983 		if (fb >= 0) {
984 			m_controller->setFramebufferHandle(fb);
985 			m_config->updateOption("videoScale");
986 		}
987 	} else {
988 		m_controller->setFramebufferHandle(-1);
989 	}
990 }
991 
tryMakePortable()992 void Window::tryMakePortable() {
993 	QMessageBox* confirm = new QMessageBox(QMessageBox::Question, tr("Really make portable?"),
994 	                                       tr("This will make the emulator load its configuration from the same directory as the executable. Do you want to continue?"),
995 	                                       QMessageBox::Yes | QMessageBox::Cancel, this, Qt::Sheet);
996 	confirm->setAttribute(Qt::WA_DeleteOnClose);
997 	connect(confirm->button(QMessageBox::Yes), &QAbstractButton::clicked, m_config, &ConfigController::makePortable);
998 	confirm->show();
999 }
1000 
mustRestart()1001 void Window::mustRestart() {
1002 	if (m_mustRestart.isActive()) {
1003 		return;
1004 	}
1005 	m_mustRestart.start();
1006 	QMessageBox* dialog = new QMessageBox(QMessageBox::Warning, tr("Restart needed"),
1007 	                                      tr("Some changes will not take effect until the emulator is restarted."),
1008 	                                      QMessageBox::Ok, this, Qt::Sheet);
1009 	dialog->setAttribute(Qt::WA_DeleteOnClose);
1010 	dialog->show();
1011 }
1012 
recordFrame()1013 void Window::recordFrame() {
1014 	m_frameList.append(m_frameTimer.nsecsElapsed());
1015 	m_frameTimer.restart();
1016 }
1017 
showFPS()1018 void Window::showFPS() {
1019 	if (m_frameList.isEmpty()) {
1020 		updateTitle();
1021 		return;
1022 	}
1023 	qint64 total = 0;
1024 	for (qint64 t : m_frameList) {
1025 		total += t;
1026 	}
1027 	double fps = (m_frameList.size() * 1e10) / total;
1028 	m_frameList.clear();
1029 	fps = round(fps) / 10.f;
1030 	updateTitle(fps);
1031 }
1032 
updateTitle(float fps)1033 void Window::updateTitle(float fps) {
1034 	QString title;
1035 	if (m_config->getOption("dynamicTitle", 1).toInt() && m_controller) {
1036 		QString filePath = windowFilePath();
1037 		if (m_config->getOption("showFilename").toInt() && !filePath.isNull()) {
1038 			QFileInfo fileInfo(filePath);
1039 			title = fileInfo.fileName();
1040 		} else {
1041 			title = m_controller->title();
1042 		}
1043 
1044 		MultiplayerController* multiplayer = m_controller->multiplayerController();
1045 		if (multiplayer && multiplayer->attached() > 1) {
1046 			title += tr(" -  Player %1 of %2").arg(multiplayer->playerId(m_controller.get()) + 1).arg(multiplayer->attached());
1047 			for (Action* action : m_nonMpActions) {
1048 				action->setEnabled(false);
1049 			}
1050 		} else {
1051 			for (Action* action : m_nonMpActions) {
1052 				action->setEnabled(true);
1053 			}
1054 		}
1055 	}
1056 	if (title.isNull()) {
1057 		setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
1058 	} else if (fps < 0) {
1059 		setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
1060 	} else {
1061 		setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
1062 	}
1063 }
1064 
openStateWindow(LoadSave ls)1065 void Window::openStateWindow(LoadSave ls) {
1066 	if (m_stateWindow) {
1067 		return;
1068 	}
1069 	MultiplayerController* multiplayer = m_controller->multiplayerController();
1070 	if (multiplayer && multiplayer->attached() > 1) {
1071 		return;
1072 	}
1073 	bool wasPaused = m_controller->isPaused();
1074 	m_stateWindow = new LoadSaveState(m_controller);
1075 	connect(this, &Window::shutdown, m_stateWindow, &QWidget::close);
1076 	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
1077 		detachWidget(m_stateWindow);
1078 		static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(m_display.get());
1079 		m_stateWindow = nullptr;
1080 		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
1081 	});
1082 	if (!wasPaused) {
1083 		m_controller->setPaused(true);
1084 		connect(m_stateWindow, &LoadSaveState::closed, [this]() {
1085 			if (m_controller) {
1086 				m_controller->setPaused(false);
1087 			}
1088 		});
1089 	}
1090 	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
1091 	m_stateWindow->setMode(ls);
1092 	updateFrame();
1093 #ifndef Q_OS_MAC
1094 	menuBar()->show();
1095 #endif
1096 	attachWidget(m_stateWindow);
1097 }
1098 
setupMenu(QMenuBar * menubar)1099 void Window::setupMenu(QMenuBar* menubar) {
1100 	installEventFilter(m_shortcutController);
1101 
1102 	menubar->clear();
1103 	m_actions.addMenu(tr("&File"), "file");
1104 
1105 	m_actions.addAction(tr("Load &ROM..."), "loadROM", this, &Window::selectROM, "file", QKeySequence::Open);
1106 
1107 #ifdef USE_SQLITE3
1108 	m_actions.addAction(tr("Load ROM in archive..."), "loadROMInArchive", this, &Window::selectROMInArchive, "file");
1109 	m_actions.addAction(tr("Add folder to library..."), "addDirToLibrary", this, &Window::addDirToLibrary, "file");
1110 #endif
1111 
1112 	addGameAction(tr("Load alternate save game..."), "loadAlternateSave", [this]() {
1113 		this->selectSave(false);
1114 	}, "file");
1115 	addGameAction(tr("Load temporary save game..."), "loadTemporarySave", [this]() {
1116 		this->selectSave(true);
1117 	}, "file");
1118 
1119 	m_actions.addAction(tr("Load &patch..."), "loadPatch", this, &Window::selectPatch, "file");
1120 
1121 #ifdef M_CORE_GBA
1122 	m_actions.addAction(tr("Boot BIOS"), "bootBIOS", this, &Window::bootBIOS, "file");
1123 #endif
1124 
1125 	addGameAction(tr("Replace ROM..."), "replaceROM", this, &Window::replaceROM, "file");
1126 #ifdef M_CORE_GBA
1127 	Action* scanCard = addGameAction(tr("Scan e-Reader dotcodes..."), "scanCard", this, &Window::scanCard, "file");
1128 	m_platformActions.insert(mPLATFORM_GBA, scanCard);
1129 #endif
1130 
1131 	addGameAction(tr("ROM &info..."), "romInfo", openControllerTView<ROMInfo>(), "file");
1132 
1133 	m_actions.addMenu(tr("Recent"), "mru", "file");
1134 	m_actions.addSeparator("file");
1135 
1136 	m_actions.addAction(tr("Make portable"), "makePortable", this, &Window::tryMakePortable, "file");
1137 	m_actions.addSeparator("file");
1138 
1139 	Action* loadState = addGameAction(tr("&Load state"), "loadState", [this]() {
1140 		this->openStateWindow(LoadSave::LOAD);
1141 	}, "file", QKeySequence("F10"));
1142 	m_nonMpActions.append(loadState);
1143 
1144 	Action* loadStateFile = addGameAction(tr("Load state file..."), "loadStateFile", [this]() {
1145 		this->selectState(true);
1146 	}, "file");
1147 	m_nonMpActions.append(loadStateFile);
1148 
1149 	Action* saveState = addGameAction(tr("&Save state"), "saveState", [this]() {
1150 		this->openStateWindow(LoadSave::SAVE);
1151 	}, "file", QKeySequence("Shift+F10"));
1152 	m_nonMpActions.append(saveState);
1153 
1154 	Action* saveStateFile = addGameAction(tr("Save state file..."), "saveStateFile", [this]() {
1155 		this->selectState(false);
1156 	}, "file");
1157 	m_nonMpActions.append(saveStateFile);
1158 
1159 	m_actions.addMenu(tr("Quick load"), "quickLoad", "file");
1160 	m_actions.addMenu(tr("Quick save"), "quickSave", "file");
1161 
1162 	Action* quickLoad = addGameAction(tr("Load recent"), "quickLoad", [this] {
1163 		m_controller->loadState();
1164 	}, "quickLoad");
1165 	m_nonMpActions.append(quickLoad);
1166 
1167 	Action* quickSave = addGameAction(tr("Save recent"), "quickSave", [this] {
1168 		m_controller->saveState();
1169 	}, "quickSave");
1170 	m_nonMpActions.append(quickSave);
1171 
1172 	m_actions.addSeparator("quickLoad");
1173 	m_actions.addSeparator("quickSave");
1174 
1175 	Action* undoLoadState = addGameAction(tr("Undo load state"), "undoLoadState", &CoreController::loadBackupState, "quickLoad", QKeySequence("F11"));
1176 	m_nonMpActions.append(undoLoadState);
1177 
1178 	Action* undoSaveState = addGameAction(tr("Undo save state"), "undoSaveState", &CoreController::saveBackupState, "quickSave", QKeySequence("Shift+F11"));
1179 	m_nonMpActions.append(undoSaveState);
1180 
1181 	m_actions.addSeparator("quickLoad");
1182 	m_actions.addSeparator("quickSave");
1183 
1184 	for (int i = 1; i < 10; ++i) {
1185 		Action* quickLoad = addGameAction(tr("State &%1").arg(i),  QString("quickLoad.%1").arg(i), [this, i]() {
1186 			m_controller->loadState(i);
1187 		}, "quickLoad", QString("F%1").arg(i));
1188 		m_nonMpActions.append(quickLoad);
1189 
1190 		Action* quickSave = addGameAction(tr("State &%1").arg(i),  QString("quickSave.%1").arg(i), [this, i]() {
1191 			m_controller->saveState(i);
1192 		}, "quickSave", QString("Shift+F%1").arg(i));
1193 		m_nonMpActions.append(quickSave);
1194 	}
1195 
1196 	m_actions.addSeparator("file");
1197 	m_actions.addAction(tr("Load camera image..."), "loadCamImage", this, &Window::loadCamImage, "file");
1198 
1199 #ifdef M_CORE_GBA
1200 	m_actions.addSeparator("file");
1201 	m_actions.addAction(tr("Convert save game..."), "convertSave", openControllerTView<SaveConverter>(), "file");
1202 
1203 	Action* importShark = addGameAction(tr("Import GameShark Save..."), "importShark", this, &Window::importSharkport, "file");
1204 	m_platformActions.insert(mPLATFORM_GBA, importShark);
1205 
1206 	Action* exportShark = addGameAction(tr("Export GameShark Save..."), "exportShark", this, &Window::exportSharkport, "file");
1207 	m_platformActions.insert(mPLATFORM_GBA, exportShark);
1208 #endif
1209 
1210 	m_actions.addSeparator("file");
1211 	m_multiWindow = m_actions.addAction(tr("New multiplayer window"), "multiWindow", [this]() {
1212 		GBAApp::app()->newWindow();
1213 	}, "file");
1214 
1215 #ifdef M_CORE_GBA
1216 	Action* dolphin = m_actions.addAction(tr("Connect to Dolphin..."), "connectDolphin", openNamedTView<DolphinConnector>(&m_dolphinView, this), "file");
1217 	m_platformActions.insert(mPLATFORM_GBA, dolphin);
1218 #endif
1219 
1220 	m_actions.addSeparator("file");
1221 
1222 	m_actions.addAction(tr("Report bug..."), "bugReport", openTView<ReportView>(), "file");
1223 
1224 #ifndef Q_OS_MAC
1225 	m_actions.addSeparator("file");
1226 #endif
1227 
1228 	m_actions.addAction(tr("About..."), "about", openTView<AboutScreen>(), "file");
1229 
1230 #ifndef Q_OS_MAC
1231 	m_actions.addAction(tr("E&xit"), "quit", static_cast<QWidget*>(this), &QWidget::close, "file", QKeySequence::Quit);
1232 #endif
1233 
1234 	m_actions.addMenu(tr("&Emulation"), "emu");
1235 	addGameAction(tr("&Reset"), "reset", &CoreController::reset, "emu", QKeySequence("Ctrl+R"));
1236 	addGameAction(tr("Sh&utdown"), "shutdown", &CoreController::stop, "emu");
1237 	addGameAction(tr("Yank game pak"), "yank", &CoreController::yankPak, "emu");
1238 
1239 	m_actions.addSeparator("emu");
1240 
1241 	Action* pause = m_actions.addBooleanAction(tr("&Pause"), "pause", [this](bool paused) {
1242 		if (m_controller) {
1243 			m_controller->setPaused(paused);
1244 		} else {
1245 			m_pendingPause = paused;
1246 		}
1247 	}, "emu", QKeySequence("Ctrl+P"));
1248 	connect(this, &Window::paused, pause, &Action::setActive);
1249 
1250 	addGameAction(tr("&Next frame"), "frameAdvance", &CoreController::frameAdvance, "emu", QKeySequence("Ctrl+N"));
1251 
1252 	m_actions.addSeparator("emu");
1253 
1254 	m_actions.addHeldAction(tr("Fast forward (held)"), "holdFastForward", [this](bool held) {
1255 		if (m_controller) {
1256 			m_controller->setFastForward(held);
1257 		}
1258 	}, "emu", QKeySequence(Qt::Key_Tab));
1259 
1260 	addGameAction(tr("&Fast forward"), "fastForward", [this](bool value) {
1261 		m_controller->forceFastForward(value);
1262 	}, "emu", QKeySequence("Shift+Tab"));
1263 
1264 	m_actions.addMenu(tr("Fast forward speed"), "fastForwardSpeed", "emu");
1265 	ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
1266 	ffspeed->connect([this](const QVariant&) {
1267 		reloadConfig();
1268 	}, this);
1269 	ffspeed->addValue(tr("Unbounded"), -1.0f, &m_actions, "fastForwardSpeed");
1270 	ffspeed->setValue(QVariant(-1.0f));
1271 	m_actions.addSeparator("fastForwardSpeed");
1272 	for (int i = 2; i < 11; ++i) {
1273 		ffspeed->addValue(tr("%0x").arg(i), i, &m_actions, "fastForwardSpeed");
1274 	}
1275 	m_config->updateOption("fastForwardRatio");
1276 
1277 	Action* rewindHeld = m_actions.addHeldAction(tr("Rewind (held)"), "holdRewind", [this](bool held) {
1278 		if (m_controller) {
1279 			m_controller->setRewinding(held);
1280 		}
1281 	}, "emu", QKeySequence("`"));
1282 	m_nonMpActions.append(rewindHeld);
1283 
1284 	Action* rewind = addGameAction(tr("Re&wind"), "rewind", [this]() {
1285 		m_controller->rewind();
1286 	}, "emu", QKeySequence("~"));
1287 	m_nonMpActions.append(rewind);
1288 
1289 	Action* frameRewind = addGameAction(tr("Step backwards"), "frameRewind", [this] () {
1290 		m_controller->rewind(1);
1291 	}, "emu", QKeySequence("Ctrl+B"));
1292 	m_nonMpActions.append(frameRewind);
1293 
1294 	ConfigOption* videoSync = m_config->addOption("videoSync");
1295 	videoSync->addBoolean(tr("Sync to &video"), &m_actions, "emu");
1296 	videoSync->connect([this](const QVariant&) {
1297 		reloadConfig();
1298 	}, this);
1299 	m_config->updateOption("videoSync");
1300 
1301 	ConfigOption* audioSync = m_config->addOption("audioSync");
1302 	audioSync->addBoolean(tr("Sync to &audio"), &m_actions, "emu");
1303 	audioSync->connect([this](const QVariant&) {
1304 		reloadConfig();
1305 	}, this);
1306 	m_config->updateOption("audioSync");
1307 
1308 	m_actions.addSeparator("emu");
1309 
1310 	m_actions.addMenu(tr("Solar sensor"), "solar", "emu");
1311 	m_actions.addAction(tr("Increase solar level"), "increaseLuminanceLevel", &m_inputController, &InputController::increaseLuminanceLevel, "solar");
1312 	m_actions.addAction(tr("Decrease solar level"), "decreaseLuminanceLevel", &m_inputController, &InputController::decreaseLuminanceLevel, "solar");
1313 	m_actions.addAction(tr("Brightest solar level"), "maxLuminanceLevel", [this]() {
1314 		m_inputController.setLuminanceLevel(10);
1315 	}, "solar");
1316 	m_actions.addAction(tr("Darkest solar level"), "minLuminanceLevel", [this]() {
1317 		m_inputController.setLuminanceLevel(0);
1318 	}, "solar");
1319 
1320 	m_actions.addSeparator("solar");
1321 	for (int i = 0; i <= 10; ++i) {
1322 		m_actions.addAction(tr("Brightness %1").arg(QString::number(i)), QString("luminanceLevel.%1").arg(QString::number(i)), [this, i]() {
1323 			m_inputController.setLuminanceLevel(i);
1324 		}, "solar");
1325 	}
1326 
1327 #ifdef M_CORE_GB
1328 	Action* gbPrint = addGameAction(tr("Game Boy Printer..."), "gbPrint", [this]() {
1329 		PrinterView* view = new PrinterView(m_controller);
1330 		openView(view);
1331 		m_controller->attachPrinter();
1332 	}, "emu");
1333 	m_platformActions.insert(mPLATFORM_GB, gbPrint);
1334 #endif
1335 
1336 #ifdef M_CORE_GBA
1337 	Action* bcGate = addGameAction(tr("BattleChip Gate..."), "bcGate", openControllerTView<BattleChipView>(this), "emu");
1338 	m_platformActions.insert(mPLATFORM_GBA, bcGate);
1339 #endif
1340 
1341 	m_actions.addMenu(tr("Audio/&Video"), "av");
1342 	m_actions.addMenu(tr("Frame size"), "frame", "av");
1343 	for (int i = 1; i <= 8; ++i) {
1344 		Action* setSize = m_actions.addAction(tr("%1×").arg(QString::number(i)), QString("frame.%1x").arg(QString::number(i)), [this, i]() {
1345 			Action* setSize = m_frameSizes[i];
1346 			showNormal();
1347 			QSize size(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1348 			if (m_controller) {
1349 				size = m_controller->screenDimensions();
1350 			}
1351 			size *= i;
1352 			m_savedScale = i;
1353 			m_config->setOption("scaleMultiplier", i); // TODO: Port to other
1354 			resizeFrame(size);
1355 			setSize->setActive(true);
1356 		}, "frame");
1357 		setSize->setExclusive(true);
1358 		if (m_savedScale == i) {
1359 			setSize->setActive(true);
1360 		}
1361 		m_frameSizes[i] = setSize;
1362 	}
1363 	QKeySequence fullscreenKeys;
1364 #ifdef Q_OS_WIN
1365 	fullscreenKeys = QKeySequence("Alt+Return");
1366 #else
1367 	fullscreenKeys = QKeySequence("Ctrl+F");
1368 #endif
1369 	m_actions.addAction(tr("Toggle fullscreen"), "fullscreen", this, &Window::toggleFullScreen, "frame", fullscreenKeys);
1370 
1371 	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1372 	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), &m_actions, "av");
1373 	lockAspectRatio->connect([this](const QVariant& value) {
1374 		if (m_display) {
1375 			m_display->lockAspectRatio(value.toBool());
1376 		}
1377 		if (m_controller) {
1378 			m_screenWidget->setLockAspectRatio(value.toBool());
1379 		}
1380 	}, this);
1381 	m_config->updateOption("lockAspectRatio");
1382 
1383 	ConfigOption* lockIntegerScaling = m_config->addOption("lockIntegerScaling");
1384 	lockIntegerScaling->addBoolean(tr("Force integer scaling"), &m_actions, "av");
1385 	lockIntegerScaling->connect([this](const QVariant& value) {
1386 		if (m_display) {
1387 			m_display->lockIntegerScaling(value.toBool());
1388 		}
1389 		if (m_controller) {
1390 			m_screenWidget->setLockIntegerScaling(value.toBool());
1391 		}
1392 	}, this);
1393 	m_config->updateOption("lockIntegerScaling");
1394 
1395 	ConfigOption* interframeBlending = m_config->addOption("interframeBlending");
1396 	interframeBlending->addBoolean(tr("Interframe blending"), &m_actions, "av");
1397 	interframeBlending->connect([this](const QVariant& value) {
1398 		if (m_display) {
1399 			m_display->interframeBlending(value.toBool());
1400 		}
1401 	}, this);
1402 	m_config->updateOption("interframeBlending");
1403 
1404 	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1405 	resampleVideo->addBoolean(tr("Bilinear filtering"), &m_actions, "av");
1406 	resampleVideo->connect([this](const QVariant& value) {
1407 		if (m_display) {
1408 			m_display->filter(value.toBool());
1409 		}
1410 		if (m_controller) {
1411 			m_screenWidget->filter(value.toBool());
1412 		}
1413 	}, this);
1414 	m_config->updateOption("resampleVideo");
1415 
1416 	m_actions.addMenu(tr("Frame&skip"),"skip", "av");
1417 	ConfigOption* skip = m_config->addOption("frameskip");
1418 	skip->connect([this](const QVariant&) {
1419 		reloadConfig();
1420 	}, this);
1421 	for (int i = 0; i <= 10; ++i) {
1422 		skip->addValue(QString::number(i), i, &m_actions, "skip");
1423 	}
1424 	m_config->updateOption("frameskip");
1425 
1426 	m_actions.addSeparator("av");
1427 
1428 	ConfigOption* mute = m_config->addOption("mute");
1429 	mute->addBoolean(tr("Mute"), &m_actions, "av");
1430 	mute->connect([this](const QVariant& value) {
1431 		m_config->setOption("fastForwardMute", static_cast<bool>(value.toInt()));
1432 		reloadConfig();
1433 	}, this);
1434 
1435 	m_actions.addMenu(tr("FPS target"),"target", "av");
1436 	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1437 	QMap<double, Action*> fpsTargets;
1438 	for (int fps : {15, 30, 45, 60, 90, 120, 240}) {
1439 		fpsTargets[fps] = fpsTargetOption->addValue(QString::number(fps), fps, &m_actions, "target");
1440 	}
1441 	m_actions.addSeparator("target");
1442 	double nativeGB = double(GBA_ARM7TDMI_FREQUENCY) / double(VIDEO_TOTAL_LENGTH);
1443 	fpsTargets[nativeGB] = fpsTargetOption->addValue(tr("Native (59.7275)"), nativeGB, &m_actions, "target");
1444 
1445 	fpsTargetOption->connect([this, fpsTargets](const QVariant& value) {
1446 		reloadConfig();
1447 		for (auto iter = fpsTargets.begin(); iter != fpsTargets.end(); ++iter) {
1448 			bool enableSignals = iter.value()->blockSignals(true);
1449 			iter.value()->setActive(abs(iter.key() - value.toDouble()) < 0.001);
1450 			iter.value()->blockSignals(enableSignals);
1451 		}
1452 	}, this);
1453 	m_config->updateOption("fpsTarget");
1454 
1455 	m_actions.addSeparator("av");
1456 
1457 #ifdef USE_PNG
1458 	addGameAction(tr("Take &screenshot"), "screenshot", [this]() {
1459 		m_controller->screenshot();
1460 	}, "av", tr("F12"));
1461 #endif
1462 
1463 #ifdef USE_FFMPEG
1464 	addGameAction(tr("Record A/V..."), "recordOutput", openNamedControllerTView<VideoView>(&m_videoView), "av");
1465 	addGameAction(tr("Record GIF/WebP/APNG..."), "recordGIF", openNamedControllerTView<GIFView>(&m_gifView), "av");
1466 #endif
1467 
1468 	m_actions.addSeparator("av");
1469 	m_actions.addMenu(tr("Video layers"), "videoLayers", "av");
1470 	m_actions.addMenu(tr("Audio channels"), "audioChannels", "av");
1471 
1472 	addGameAction(tr("Adjust layer placement..."), "placementControl", openControllerTView<PlacementControl>(), "av");
1473 
1474 	m_actions.addMenu(tr("&Tools"), "tools");
1475 	m_actions.addAction(tr("View &logs..."), "viewLogs", static_cast<QWidget*>(m_logView), &QWidget::show, "tools");
1476 
1477 	m_actions.addAction(tr("Game &overrides..."), "overrideWindow", [this]() {
1478 		if (!m_overrideView) {
1479 			m_overrideView = std::make_unique<OverrideView>(m_config);
1480 			if (m_controller) {
1481 				m_overrideView->setController(m_controller);
1482 			}
1483 			connect(this, &Window::shutdown, m_overrideView.get(), &QWidget::close);
1484 		}
1485 		m_overrideView->show();
1486 		m_overrideView->recheck();
1487 	}, "tools");
1488 
1489 	m_actions.addAction(tr("Game Pak sensors..."), "sensorWindow",  openNamedControllerTView<SensorView>(&m_sensorView, &m_inputController), "tools");
1490 
1491 	addGameAction(tr("&Cheats..."), "cheatsWindow", openControllerTView<CheatsView>(), "tools");
1492 
1493 	m_actions.addSeparator("tools");
1494 	m_actions.addAction(tr("Settings..."), "settings", this, &Window::openSettingsWindow, "tools");
1495 
1496 #ifdef USE_DEBUGGERS
1497 	m_actions.addSeparator("tools");
1498 	m_actions.addAction(tr("Open debugger console..."), "debuggerWindow", this, &Window::consoleOpen, "tools");
1499 #ifdef USE_GDB_STUB
1500 	Action* gdbWindow = addGameAction(tr("Start &GDB server..."), "gdbWindow", this, &Window::gdbOpen, "tools");
1501 	m_platformActions.insert(mPLATFORM_GBA, gdbWindow);
1502 #endif
1503 #endif
1504 	m_actions.addSeparator("tools");
1505 
1506 	addGameAction(tr("View &palette..."), "paletteWindow", openControllerTView<PaletteView>(), "tools");
1507 	addGameAction(tr("View &sprites..."), "spriteWindow", openControllerTView<ObjView>(), "tools");
1508 	addGameAction(tr("View &tiles..."), "tileWindow", openControllerTView<TileView>(), "tools");
1509 	addGameAction(tr("View &map..."), "mapWindow", openControllerTView<MapView>(), "tools");
1510 
1511 	addGameAction(tr("&Frame inspector..."), "frameWindow", [this]() {
1512 		if (!m_frameView) {
1513 			m_frameView = new FrameView(m_controller);
1514 			connect(this, &Window::shutdown, this, [this]() {
1515 				if (m_frameView) {
1516 					m_frameView->close();
1517 				}
1518 			});
1519 			connect(m_frameView, &QObject::destroyed, this, [this]() {
1520 				m_frameView = nullptr;
1521 			});
1522 			m_frameView->setAttribute(Qt::WA_DeleteOnClose);
1523 		}
1524 		m_frameView->show();
1525 	}, "tools");
1526 
1527 	addGameAction(tr("View memory..."), "memoryView", openControllerTView<MemoryView>(), "tools");
1528 	addGameAction(tr("Search memory..."), "memorySearch", openControllerTView<MemorySearch>(), "tools");
1529 	addGameAction(tr("View &I/O registers..."), "ioViewer", openControllerTView<IOViewer>(), "tools");
1530 
1531 	m_actions.addSeparator("tools");
1532 	addGameAction(tr("Record debug video log..."), "recordVL", this, &Window::startVideoLog, "tools");
1533 	addGameAction(tr("Stop debug video log"), "stopVL", [this]() {
1534 		m_controller->endVideoLog();
1535 	}, "tools");
1536 
1537 	ConfigOption* skipBios = m_config->addOption("skipBios");
1538 	skipBios->connect([this](const QVariant&) {
1539 		reloadConfig();
1540 	}, this);
1541 
1542 	ConfigOption* useBios = m_config->addOption("useBios");
1543 	useBios->connect([this](const QVariant&) {
1544 		reloadConfig();
1545 	}, this);
1546 
1547 	ConfigOption* buffers = m_config->addOption("audioBuffers");
1548 	buffers->connect([this](const QVariant&) {
1549 		reloadConfig();
1550 	}, this);
1551 
1552 	ConfigOption* sampleRate = m_config->addOption("sampleRate");
1553 	sampleRate->connect([this](const QVariant&) {
1554 		reloadConfig();
1555 	}, this);
1556 
1557 	ConfigOption* volume = m_config->addOption("volume");
1558 	volume->connect([this](const QVariant&) {
1559 		reloadConfig();
1560 	}, this);
1561 
1562 	ConfigOption* volumeFf = m_config->addOption("fastForwardVolume");
1563 	volumeFf->connect([this](const QVariant&) {
1564 		reloadConfig();
1565 	}, this);
1566 
1567 	ConfigOption* muteFf = m_config->addOption("fastForwardMute");
1568 	muteFf->connect([this](const QVariant&) {
1569 		reloadConfig();
1570 	}, this);
1571 
1572 	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1573 	rewindEnable->connect([this](const QVariant&) {
1574 		reloadConfig();
1575 	}, this);
1576 
1577 	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1578 	rewindBufferCapacity->connect([this](const QVariant&) {
1579 		reloadConfig();
1580 	}, this);
1581 
1582 	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1583 	allowOpposingDirections->connect([this](const QVariant&) {
1584 		reloadConfig();
1585 	}, this);
1586 
1587 	ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1588 	saveStateExtdata->connect([this](const QVariant&) {
1589 		reloadConfig();
1590 	}, this);
1591 
1592 	ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1593 	loadStateExtdata->connect([this](const QVariant&) {
1594 		reloadConfig();
1595 	}, this);
1596 
1597 	ConfigOption* preload = m_config->addOption("preload");
1598 	preload->connect([this](const QVariant& value) {
1599 		m_manager->setPreload(value.toBool());
1600 	}, this);
1601 	m_config->updateOption("preload");
1602 
1603 	ConfigOption* showFps = m_config->addOption("showFps");
1604 	showFps->connect([this](const QVariant& value) {
1605 		if (!value.toInt()) {
1606 			m_fpsTimer.stop();
1607 			updateTitle();
1608 		} else if (m_controller) {
1609 			m_fpsTimer.start();
1610 			m_frameTimer.start();
1611 		}
1612 	}, this);
1613 
1614 	ConfigOption* showOSD = m_config->addOption("showOSD");
1615 	showOSD->connect([this](const QVariant& value) {
1616 		if (m_display) {
1617 			m_display->showOSDMessages(value.toBool());
1618 		}
1619 	}, this);
1620 
1621 	ConfigOption* videoScale = m_config->addOption("videoScale");
1622 	videoScale->connect([this](const QVariant& value) {
1623 		if (m_display) {
1624 			m_display->setVideoScale(value.toInt());
1625 		}
1626 	}, this);
1627 
1628 	ConfigOption* dynamicTitle = m_config->addOption("dynamicTitle");
1629 	dynamicTitle->connect([this](const QVariant&) {
1630 		updateTitle();
1631 	}, this);
1632 
1633 	m_actions.addHiddenAction(tr("Exit fullscreen"), "exitFullScreen", this, &Window::exitFullScreen, "frame", QKeySequence("Esc"));
1634 
1635 	m_actions.addHeldAction(tr("GameShark Button (held)"), "holdGSButton", [this](bool held) {
1636 		if (m_controller) {
1637 			mCheatPressButton(m_controller->cheatDevice(), held);
1638 		}
1639 	}, "tools", QKeySequence(Qt::Key_Apostrophe));
1640 
1641 	m_actions.addHiddenMenu(tr("Autofire"), "autofire");
1642 	m_actions.addHeldAction(tr("Autofire A"), "autofireA", [this](bool held) {
1643 		if (m_controller) {
1644 			m_controller->setAutofire(GBA_KEY_A, held);
1645 		}
1646 	}, "autofire");
1647 	m_actions.addHeldAction(tr("Autofire B"), "autofireB", [this](bool held) {
1648 		if (m_controller) {
1649 			m_controller->setAutofire(GBA_KEY_B, held);
1650 		}
1651 	}, "autofire");
1652 	m_actions.addHeldAction(tr("Autofire L"), "autofireL", [this](bool held) {
1653 		if (m_controller) {
1654 			m_controller->setAutofire(GBA_KEY_L, held);
1655 		}
1656 	}, "autofire");
1657 	m_actions.addHeldAction(tr("Autofire R"), "autofireR", [this](bool held) {
1658 		if (m_controller) {
1659 			m_controller->setAutofire(GBA_KEY_R, held);
1660 		}
1661 	}, "autofire");
1662 	m_actions.addHeldAction(tr("Autofire Start"), "autofireStart", [this](bool held) {
1663 		if (m_controller) {
1664 			m_controller->setAutofire(GBA_KEY_START, held);
1665 		}
1666 	}, "autofire");
1667 	m_actions.addHeldAction(tr("Autofire Select"), "autofireSelect", [this](bool held) {
1668 		if (m_controller) {
1669 			m_controller->setAutofire(GBA_KEY_SELECT, held);
1670 		}
1671 	}, "autofire");
1672 	m_actions.addHeldAction(tr("Autofire Up"), "autofireUp", [this](bool held) {
1673 		if (m_controller) {
1674 			m_controller->setAutofire(GBA_KEY_UP, held);
1675 		}
1676 	}, "autofire");
1677 	m_actions.addHeldAction(tr("Autofire Right"), "autofireRight", [this](bool held) {
1678 		if (m_controller) {
1679 			m_controller->setAutofire(GBA_KEY_RIGHT, held);
1680 		}
1681 	}, "autofire");
1682 	m_actions.addHeldAction(tr("Autofire Down"), "autofireDown", [this](bool held) {
1683 		if (m_controller) {
1684 			m_controller->setAutofire(GBA_KEY_DOWN, held);
1685 		}
1686 	}, "autofire");
1687 	m_actions.addHeldAction(tr("Autofire Left"), "autofireLeft", [this](bool held) {
1688 		if (m_controller) {
1689 			m_controller->setAutofire(GBA_KEY_LEFT, held);
1690 		}
1691 	}, "autofire");
1692 
1693 	for (Action* action : m_gameActions) {
1694 		action->setEnabled(false);
1695 	}
1696 
1697 	m_shortcutController->rebuildItems();
1698 	m_actions.rebuildMenu(menuBar(), this, *m_shortcutController);
1699 }
1700 
attachWidget(QWidget * widget)1701 void Window::attachWidget(QWidget* widget) {
1702 	m_screenWidget->layout()->addWidget(widget);
1703 	m_screenWidget->unsetCursor();
1704 	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1705 }
1706 
detachWidget(QWidget * widget)1707 void Window::detachWidget(QWidget* widget) {
1708 	m_screenWidget->layout()->removeWidget(widget);
1709 }
1710 
appendMRU(const QString & fname)1711 void Window::appendMRU(const QString& fname) {
1712 	int index = m_mruFiles.indexOf(fname);
1713 	if (index >= 0) {
1714 		m_mruFiles.removeAt(index);
1715 	}
1716 	m_mruFiles.prepend(fname);
1717 	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1718 		m_mruFiles.removeLast();
1719 	}
1720 	updateMRU();
1721 }
1722 
clearMRU()1723 void Window::clearMRU() {
1724 	m_mruFiles.clear();
1725 	updateMRU();
1726 }
1727 
updateMRU()1728 void Window::updateMRU() {
1729 	m_actions.clearMenu("mru");
1730 	int i = 0;
1731 	for (const QString& file : m_mruFiles) {
1732 		QString displayName(QDir::toNativeSeparators(file).replace("&", "&&"));
1733 		m_actions.addAction(displayName, QString("mru.%1").arg(QString::number(i)), [this, file]() {
1734 			setController(m_manager->loadGame(file), file);
1735 		}, "mru", QString("Ctrl+%1").arg(i));
1736 		++i;
1737 	}
1738 	m_config->setMRU(m_mruFiles);
1739 	m_config->write();
1740 	m_actions.addSeparator("mru");
1741 	m_actions.addAction(tr("Clear"), "resetMru", this, &Window::clearMRU, "mru");
1742 
1743 	m_actions.rebuildMenu(menuBar(), this, *m_shortcutController);
1744 }
1745 
addGameAction(const QString & visibleName,const QString & name,Action::Function function,const QString & menu,const QKeySequence & shortcut)1746 Action* Window::addGameAction(const QString& visibleName, const QString& name, Action::Function function, const QString& menu, const QKeySequence& shortcut) {
1747 	Action* action = m_actions.addAction(visibleName, name, [this, function]() {
1748 		if (m_controller) {
1749 			function();
1750 		}
1751 	}, menu, shortcut);
1752 	m_gameActions.append(action);
1753 	return action;
1754 }
1755 
1756 template<typename T, typename V>
addGameAction(const QString & visibleName,const QString & name,T * obj,V (T::* method)(),const QString & menu,const QKeySequence & shortcut)1757 Action* Window::addGameAction(const QString& visibleName, const QString& name, T* obj, V (T::*method)(), const QString& menu, const QKeySequence& shortcut) {
1758 	return addGameAction(visibleName, name, [this, obj, method]() {
1759 		(obj->*method)();
1760 	}, menu, shortcut);
1761 }
1762 
1763 template<typename V>
addGameAction(const QString & visibleName,const QString & name,V (CoreController::* method)(),const QString & menu,const QKeySequence & shortcut)1764 Action* Window::addGameAction(const QString& visibleName, const QString& name, V (CoreController::*method)(), const QString& menu, const QKeySequence& shortcut) {
1765 	return addGameAction(visibleName, name, [this, method]() {
1766 		(m_controller.get()->*method)();
1767 	}, menu, shortcut);
1768 }
1769 
addGameAction(const QString & visibleName,const QString & name,Action::BooleanFunction function,const QString & menu,const QKeySequence & shortcut)1770 Action* Window::addGameAction(const QString& visibleName, const QString& name, Action::BooleanFunction function, const QString& menu, const QKeySequence& shortcut) {
1771 	Action* action = m_actions.addBooleanAction(visibleName, name, [this, function](bool value) {
1772 		if (m_controller) {
1773 			function(value);
1774 		}
1775 	}, menu, shortcut);
1776 	m_gameActions.append(action);
1777 	return action;
1778 }
1779 
focusCheck()1780 void Window::focusCheck() {
1781 	if (!m_config->getOption("pauseOnFocusLost").toInt() || !m_controller) {
1782 		return;
1783 	}
1784 	if (QGuiApplication::focusWindow() && m_autoresume) {
1785 		m_controller->setPaused(false);
1786 		m_autoresume = false;
1787 	} else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1788 		m_autoresume = true;
1789 		m_controller->setPaused(true);
1790 	}
1791 }
1792 
updateFrame()1793 void Window::updateFrame() {
1794 	QPixmap pixmap;
1795 	pixmap.convertFromImage(m_controller->getPixels());
1796 	m_screenWidget->setPixmap(pixmap);
1797 	emit paused(true);
1798 }
1799 
setController(CoreController * controller,const QString & fname)1800 void Window::setController(CoreController* controller, const QString& fname) {
1801 	if (!controller) {
1802 		return;
1803 	}
1804 	if (m_pendingClose) {
1805 		return;
1806 	}
1807 
1808 	if (m_controller) {
1809 		m_controller->stop();
1810 		QTimer::singleShot(0, this, [this, controller, fname]() {
1811 			setController(controller, fname);
1812 		});
1813 		return;
1814 	}
1815 	if (!fname.isEmpty()) {
1816 		setWindowFilePath(fname);
1817 		appendMRU(fname);
1818 	}
1819 
1820 	if (!m_display) {
1821 		reloadDisplayDriver();
1822 	}
1823 
1824 	m_controller = std::shared_ptr<CoreController>(controller);
1825 	m_inputController.recalibrateAxes();
1826 	m_controller->setInputController(&m_inputController);
1827 	m_controller->setLogger(&m_log);
1828 
1829 	connect(this, &Window::shutdown, [this]() {
1830 		if (!m_controller) {
1831 			return;
1832 		}
1833 		m_controller->stop();
1834 		disconnect(m_controller.get(), &CoreController::started, this, &Window::gameStarted);
1835 	});
1836 
1837 	connect(m_controller.get(), &CoreController::started, this, &Window::gameStarted);
1838 	connect(m_controller.get(), &CoreController::started, &m_inputController, &InputController::suspendScreensaver);
1839 	connect(m_controller.get(), &CoreController::stopping, this, &Window::gameStopped);
1840 	{
1841 		connect(m_controller.get(), &CoreController::stopping, [this]() {
1842 			m_controller.reset();
1843 		});
1844 	}
1845 	connect(m_controller.get(), &CoreController::stopping, &m_inputController, &InputController::resumeScreensaver);
1846 	connect(m_controller.get(), &CoreController::paused, this, &Window::updateFrame);
1847 
1848 #ifndef Q_OS_MAC
1849 	connect(m_controller.get(), &CoreController::paused, menuBar(), &QWidget::show);
1850 	connect(m_controller.get(), &CoreController::unpaused, [this]() {
1851 		if(isFullScreen()) {
1852 			menuBar()->hide();
1853 		}
1854 	});
1855 #endif
1856 
1857 	connect(m_controller.get(), &CoreController::paused, &m_inputController, &InputController::resumeScreensaver);
1858 	connect(m_controller.get(), &CoreController::unpaused, [this]() {
1859 		emit paused(false);
1860 	});
1861 	connect(m_controller.get(), &CoreController::unpaused, &m_inputController, &InputController::suspendScreensaver);
1862 	connect(m_controller.get(), &CoreController::frameAvailable, this, &Window::recordFrame);
1863 	connect(m_controller.get(), &CoreController::crashed, this, &Window::gameCrashed);
1864 	connect(m_controller.get(), &CoreController::failed, this, &Window::gameFailed);
1865 	connect(m_controller.get(), &CoreController::unimplementedBiosCall, this, &Window::unimplementedBiosCall);
1866 
1867 #ifdef USE_GDB_STUB
1868 	if (m_gdbController) {
1869 		m_gdbController->setController(m_controller);
1870 	}
1871 #endif
1872 
1873 #ifdef USE_DEBUGGERS
1874 	if (m_console) {
1875 		m_console->setController(m_controller);
1876 	}
1877 #endif
1878 
1879 #ifdef USE_FFMPEG
1880 	if (m_gifView) {
1881 		m_gifView->setController(m_controller);
1882 	}
1883 
1884 	if (m_videoView) {
1885 		m_videoView->setController(m_controller);
1886 	}
1887 #endif
1888 
1889 	if (m_sensorView) {
1890 		m_sensorView->setController(m_controller);
1891 	}
1892 
1893 	if (m_overrideView) {
1894 		m_overrideView->setController(m_controller);
1895 	}
1896 
1897 	if (!m_pendingPatch.isEmpty()) {
1898 		m_controller->loadPatch(m_pendingPatch);
1899 		m_pendingPatch = QString();
1900 	}
1901 
1902 	attachDisplay();
1903 	m_controller->loadConfig(m_config);
1904 	m_controller->start();
1905 
1906 	if (!m_pendingState.isEmpty()) {
1907 		m_controller->loadState(m_pendingState);
1908 		m_pendingState = QString();
1909 	}
1910 
1911 	if (m_pendingPause) {
1912 		m_controller->setPaused(true);
1913 		m_pendingPause = false;
1914 	}
1915 }
1916 
attachDisplay()1917 void Window::attachDisplay() {
1918 	connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::resizeContext);
1919 	connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::forceDraw);
1920 	connect(m_controller.get(), &CoreController::rewound, m_display.get(), &Display::forceDraw);
1921 	connect(m_controller.get(), &CoreController::paused, m_display.get(), &Display::pauseDrawing);
1922 	connect(m_controller.get(), &CoreController::unpaused, m_display.get(), &Display::unpauseDrawing);
1923 	connect(m_controller.get(), &CoreController::frameAvailable, m_display.get(), &Display::framePosted);
1924 	connect(m_controller.get(), &CoreController::statusPosted, m_display.get(), &Display::showMessage);
1925 	connect(m_controller.get(), &CoreController::didReset, m_display.get(), &Display::resizeContext);
1926 	connect(m_display.get(), &Display::drawingStarted, this, &Window::changeRenderer);
1927 	m_display->startDrawing(m_controller);
1928 }
1929 
setLogo()1930 void Window::setLogo() {
1931 	m_screenWidget->setPixmap(m_logo);
1932 	m_screenWidget->setDimensions(m_logo.width(), m_logo.height());
1933 	m_screenWidget->setLockIntegerScaling(false);
1934 	m_screenWidget->setLockAspectRatio(true);
1935 	m_screenWidget->filter(true);
1936 	m_screenWidget->unsetCursor();
1937 }
1938 
WindowBackground(QWidget * parent)1939 WindowBackground::WindowBackground(QWidget* parent)
1940 	: QWidget(parent)
1941 {
1942 	setLayout(new QStackedLayout());
1943 	layout()->setContentsMargins(0, 0, 0, 0);
1944 }
1945 
setPixmap(const QPixmap & pmap)1946 void WindowBackground::setPixmap(const QPixmap& pmap) {
1947 	m_pixmap = pmap;
1948 	update();
1949 }
1950 
setSizeHint(const QSize & hint)1951 void WindowBackground::setSizeHint(const QSize& hint) {
1952 	m_sizeHint = hint;
1953 }
1954 
sizeHint() const1955 QSize WindowBackground::sizeHint() const {
1956 	return m_sizeHint;
1957 }
1958 
setDimensions(int width,int height)1959 void WindowBackground::setDimensions(int width, int height) {
1960 	m_aspectWidth = width;
1961 	m_aspectHeight = height;
1962 }
1963 
setLockIntegerScaling(bool lock)1964 void WindowBackground::setLockIntegerScaling(bool lock) {
1965 	m_lockIntegerScaling = lock;
1966 }
1967 
setLockAspectRatio(bool lock)1968 void WindowBackground::setLockAspectRatio(bool lock) {
1969 	m_lockAspectRatio = lock;
1970 }
1971 
filter(bool filter)1972 void WindowBackground::filter(bool filter) {
1973 	m_filter = filter;
1974 }
1975 
paintEvent(QPaintEvent * event)1976 void WindowBackground::paintEvent(QPaintEvent* event) {
1977 	QWidget::paintEvent(event);
1978 	const QPixmap& logo = pixmap();
1979 	QPainter painter(this);
1980 	painter.setRenderHint(QPainter::SmoothPixmapTransform, m_filter);
1981 	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1982 	QRect full(clampSize(QSize(m_aspectWidth, m_aspectHeight), size(), m_lockAspectRatio, m_lockIntegerScaling));
1983 	painter.drawPixmap(full, logo);
1984 }
1985