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