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