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