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