src/platform/qt/Window.cpp (view raw)
1/* Copyright (c) 2013-2014 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 <QFileDialog>
9#include <QFileInfo>
10#include <QKeyEvent>
11#include <QKeySequence>
12#include <QMenuBar>
13#include <QMessageBox>
14#include <QMimeData>
15#include <QPainter>
16#include <QStackedLayout>
17
18#include "CheatsView.h"
19#include "ConfigController.h"
20#include "DisplayGL.h"
21#include "GameController.h"
22#include "GBAKeyEditor.h"
23#include "GDBController.h"
24#include "GDBWindow.h"
25#include "GIFView.h"
26#include "LoadSaveState.h"
27#include "LogView.h"
28#include "MultiplayerController.h"
29#include "MemoryView.h"
30#include "OverrideView.h"
31#include "PaletteView.h"
32#include "SensorView.h"
33#include "SettingsView.h"
34#include "ShortcutController.h"
35#include "ShortcutView.h"
36#include "VideoView.h"
37
38extern "C" {
39#include "platform/commandline.h"
40}
41
42using namespace QGBA;
43
44Window::Window(ConfigController* config, int playerId, QWidget* parent)
45 : QMainWindow(parent)
46 , m_logView(new LogView())
47 , m_stateWindow(nullptr)
48 , m_screenWidget(new WindowBackground())
49 , m_logo(":/res/mgba-1024.png")
50 , m_config(config)
51 , m_inputController(playerId)
52#ifdef USE_FFMPEG
53 , m_videoView(nullptr)
54#endif
55#ifdef USE_MAGICK
56 , m_gifView(nullptr)
57#endif
58#ifdef USE_GDB_STUB
59 , m_gdbController(nullptr)
60#endif
61 , m_mruMenu(nullptr)
62 , m_shortcutController(new ShortcutController(this))
63 , m_playerId(playerId)
64{
65 setWindowTitle(PROJECT_NAME);
66 setFocusPolicy(Qt::StrongFocus);
67 setAcceptDrops(true);
68 m_controller = new GameController(this);
69 m_controller->setInputController(&m_inputController);
70 m_controller->setOverrides(m_config->overrides());
71
72 QGLFormat format(QGLFormat(QGL::Rgba | QGL::DoubleBuffer));
73 format.setSwapInterval(1);
74 m_display = new DisplayGL(format, this);
75
76 m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
77 m_logo = m_logo; // Free memory left over in old pixmap
78
79 m_screenWidget->setMinimumSize(m_display->minimumSize());
80 m_screenWidget->setSizePolicy(m_display->sizePolicy());
81 m_screenWidget->setSizeHint(m_display->minimumSize() * 2);
82 m_screenWidget->setPixmap(m_logo);
83 m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
84 setCentralWidget(m_screenWidget);
85
86 QVariant windowPos = m_config->getQtOption("windowPos");
87 if (!windowPos.isNull()) {
88 move(windowPos.toPoint());
89 }
90
91 connect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));
92 connect(m_controller, SIGNAL(gameStarted(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
93 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_display, SLOT(stopDrawing()));
94 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), this, SLOT(gameStopped()));
95 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
96 connect(m_controller, SIGNAL(stateLoaded(GBAThread*)), m_display, SLOT(forceDraw()));
97 connect(m_controller, SIGNAL(rewound(GBAThread*)), m_display, SLOT(forceDraw()));
98 connect(m_controller, SIGNAL(gamePaused(GBAThread*)), m_display, SLOT(pauseDrawing()));
99#ifndef Q_OS_MAC
100 connect(m_controller, SIGNAL(gamePaused(GBAThread*)), menuBar(), SLOT(show()));
101 connect(m_controller, &GameController::gameUnpaused, [this]() {
102 if(isFullScreen()) {
103 menuBar()->hide();
104 }
105 });
106#endif
107 connect(m_controller, SIGNAL(gamePaused(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
108 connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), m_display, SLOT(unpauseDrawing()));
109 connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
110 connect(m_controller, SIGNAL(postLog(int, const QString&)), m_logView, SLOT(postLog(int, const QString&)));
111 connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
112 connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), m_display, SLOT(framePosted(const uint32_t*)));
113 connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
114 connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
115 connect(m_controller, SIGNAL(unimplementedBiosCall(int)), this, SLOT(unimplementedBiosCall(int)));
116 connect(m_controller, SIGNAL(statusPosted(const QString&)), m_display, SLOT(showMessage(const QString&)));
117 connect(m_logView, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
118 connect(m_logView, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
119 connect(m_logView, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
120 connect(this, SIGNAL(startDrawing(GBAThread*)), m_display, SLOT(startDrawing(GBAThread*)), Qt::QueuedConnection);
121 connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
122 connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
123 connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
124 connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
125 connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
126 connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));
127
128 m_logView->setLevels(GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL | GBA_LOG_STATUS);
129 m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
130
131 m_shortcutController->setConfigController(m_config);
132 setupMenu(menuBar());
133}
134
135Window::~Window() {
136 delete m_logView;
137
138#ifdef USE_FFMPEG
139 delete m_videoView;
140#endif
141
142#ifdef USE_MAGICK
143 delete m_gifView;
144#endif
145}
146
147void Window::argumentsPassed(GBAArguments* args) {
148 loadConfig();
149
150 if (args->patch) {
151 m_controller->loadPatch(args->patch);
152 }
153
154 if (args->fname) {
155 m_controller->loadGame(args->fname, args->dirmode);
156 }
157}
158
159void Window::resizeFrame(int width, int height) {
160 QSize newSize(width, height);
161 newSize -= m_screenWidget->size();
162 newSize += size();
163 resize(newSize);
164}
165
166void Window::setConfig(ConfigController* config) {
167 m_config = config;
168}
169
170void Window::loadConfig() {
171 const GBAOptions* opts = m_config->options();
172
173 m_logView->setLevels(opts->logLevel);
174
175 m_controller->setOptions(opts);
176 m_display->lockAspectRatio(opts->lockAspectRatio);
177 m_display->filter(opts->resampleVideo);
178
179 if (opts->bios) {
180 m_controller->loadBIOS(opts->bios);
181 }
182
183 if (opts->fpsTarget) {
184 emit fpsTargetChanged(opts->fpsTarget);
185 }
186
187 if (opts->audioBuffers) {
188 emit audioBufferSamplesChanged(opts->audioBuffers);
189 }
190
191 if (opts->width && opts->height) {
192 resizeFrame(opts->width, opts->height);
193 }
194
195 if (opts->fullscreen) {
196 enterFullScreen();
197 }
198
199 m_inputController.setScreensaverSuspendable(opts->suspendScreensaver);
200
201 m_mruFiles = m_config->getMRU();
202 updateMRU();
203
204 m_inputController.setConfiguration(m_config);
205}
206
207void Window::saveConfig() {
208 m_inputController.saveConfiguration();
209 m_config->write();
210}
211
212void Window::selectROM() {
213 bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
214 if (doPause) {
215 m_controller->setPaused(true);
216 }
217 QString filename = QFileDialog::getOpenFileName(this, tr("Select ROM"), m_config->getQtOption("lastDirectory").toString(), tr("Game Boy Advance ROMs (*.gba *.zip *.rom *.bin)"));
218 if (doPause) {
219 m_controller->setPaused(false);
220 }
221 if (!filename.isEmpty()) {
222 m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
223 m_controller->loadGame(filename);
224 }
225}
226
227void Window::selectBIOS() {
228 bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
229 if (doPause) {
230 m_controller->setPaused(true);
231 }
232 QString filename = QFileDialog::getOpenFileName(this, tr("Select BIOS"), m_config->getQtOption("lastDirectory").toString());
233 if (doPause) {
234 m_controller->setPaused(false);
235 }
236 if (!filename.isEmpty()) {
237 m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
238 m_config->setOption("bios", filename);
239 m_config->updateOption("bios");
240 m_config->setOption("useBios", true);
241 m_config->updateOption("useBios");
242 m_controller->loadBIOS(filename);
243 }
244}
245
246void Window::selectPatch() {
247 bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
248 if (doPause) {
249 m_controller->setPaused(true);
250 }
251 QString filename = QFileDialog::getOpenFileName(this, tr("Select patch"), m_config->getQtOption("lastDirectory").toString(), tr("Patches (*.ips *.ups *.bps)"));
252 if (doPause) {
253 m_controller->setPaused(false);
254 }
255 if (!filename.isEmpty()) {
256 m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
257 m_controller->loadPatch(filename);
258 }
259}
260
261void Window::openView(QWidget* widget) {
262 connect(this, SIGNAL(shutdown()), widget, SLOT(close()));
263 widget->setAttribute(Qt::WA_DeleteOnClose);
264 widget->show();
265}
266
267void Window::importSharkport() {
268 bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
269 if (doPause) {
270 m_controller->setPaused(true);
271 }
272 QString filename = QFileDialog::getOpenFileName(this, tr("Select save"), m_config->getQtOption("lastDirectory").toString(), tr("GameShark saves (*.sps *.xps)"));
273 if (doPause) {
274 m_controller->setPaused(false);
275 }
276 if (!filename.isEmpty()) {
277 m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
278 m_controller->importSharkport(filename);
279 }
280}
281
282void Window::exportSharkport() {
283 bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
284 if (doPause) {
285 m_controller->setPaused(true);
286 }
287 QString filename = QFileDialog::getSaveFileName(this, tr("Select save"), m_config->getQtOption("lastDirectory").toString(), tr("GameShark saves (*.sps *.xps)"));
288 if (doPause) {
289 m_controller->setPaused(false);
290 }
291 if (!filename.isEmpty()) {
292 m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
293 m_controller->exportSharkport(filename);
294 }
295}
296
297void Window::openKeymapWindow() {
298 GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, InputController::KEYBOARD);
299 openView(keyEditor);
300}
301
302void Window::openSettingsWindow() {
303 SettingsView* settingsWindow = new SettingsView(m_config);
304 connect(settingsWindow, SIGNAL(biosLoaded(const QString&)), m_controller, SLOT(loadBIOS(const QString&)));
305 connect(settingsWindow, SIGNAL(audioDriverChanged()), m_controller, SLOT(reloadAudioDriver()));
306 openView(settingsWindow);
307}
308
309void Window::openShortcutWindow() {
310#ifdef BUILD_SDL
311 m_inputController.recalibrateAxes();
312#endif
313 ShortcutView* shortcutView = new ShortcutView();
314 shortcutView->setController(m_shortcutController);
315 openView(shortcutView);
316}
317
318void Window::openOverrideWindow() {
319 OverrideView* overrideWindow = new OverrideView(m_controller, m_config);
320 openView(overrideWindow);
321}
322
323void Window::openSensorWindow() {
324 SensorView* sensorWindow = new SensorView(m_controller, &m_inputController);
325 openView(sensorWindow);
326}
327
328void Window::openCheatsWindow() {
329 CheatsView* cheatsWindow = new CheatsView(m_controller);
330 openView(cheatsWindow);
331}
332
333void Window::openPaletteWindow() {
334 PaletteView* paletteWindow = new PaletteView(m_controller);
335 openView(paletteWindow);
336}
337
338void Window::openMemoryWindow() {
339 MemoryView* memoryWindow = new MemoryView(m_controller);
340 openView(memoryWindow);
341}
342
343#ifdef BUILD_SDL
344void Window::openGamepadWindow() {
345 const char* profile = m_inputController.profileForType(SDL_BINDING_BUTTON);
346 GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, SDL_BINDING_BUTTON, profile);
347 openView(keyEditor);
348}
349#endif
350
351#ifdef USE_FFMPEG
352void Window::openVideoWindow() {
353 if (!m_videoView) {
354 m_videoView = new VideoView();
355 connect(m_videoView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
356 connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
357 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(stopRecording()));
358 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(close()));
359 connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
360 }
361 m_videoView->show();
362}
363#endif
364
365#ifdef USE_MAGICK
366void Window::openGIFWindow() {
367 if (!m_gifView) {
368 m_gifView = new GIFView();
369 connect(m_gifView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
370 connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
371 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(stopRecording()));
372 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(close()));
373 connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
374 }
375 m_gifView->show();
376}
377#endif
378
379#ifdef USE_GDB_STUB
380void Window::gdbOpen() {
381 if (!m_gdbController) {
382 m_gdbController = new GDBController(m_controller, this);
383 }
384 GDBWindow* window = new GDBWindow(m_gdbController);
385 connect(this, SIGNAL(shutdown()), window, SLOT(close()));
386 window->setAttribute(Qt::WA_DeleteOnClose);
387 window->show();
388}
389#endif
390
391void Window::keyPressEvent(QKeyEvent* event) {
392 if (event->isAutoRepeat()) {
393 QWidget::keyPressEvent(event);
394 return;
395 }
396 GBAKey key = m_inputController.mapKeyboard(event->key());
397 if (key == GBA_KEY_NONE) {
398 QWidget::keyPressEvent(event);
399 return;
400 }
401 m_controller->keyPressed(key);
402 event->accept();
403}
404
405void Window::keyReleaseEvent(QKeyEvent* event) {
406 if (event->isAutoRepeat()) {
407 QWidget::keyReleaseEvent(event);
408 return;
409 }
410 GBAKey key = m_inputController.mapKeyboard(event->key());
411 if (key == GBA_KEY_NONE) {
412 QWidget::keyPressEvent(event);
413 return;
414 }
415 m_controller->keyReleased(key);
416 event->accept();
417}
418
419void Window::resizeEvent(QResizeEvent*) {
420 m_config->setOption("height", m_screenWidget->height());
421 m_config->setOption("width", m_screenWidget->width());
422 m_config->setOption("fullscreen", isFullScreen());
423}
424
425void Window::closeEvent(QCloseEvent* event) {
426 emit shutdown();
427 m_config->setQtOption("windowPos", pos());
428 saveConfig();
429 QMainWindow::closeEvent(event);
430}
431
432void Window::focusOutEvent(QFocusEvent*) {
433 m_controller->setTurbo(false, false);
434 m_controller->clearKeys();
435}
436
437void Window::dragEnterEvent(QDragEnterEvent* event) {
438 if (event->mimeData()->hasFormat("text/uri-list")) {
439 event->acceptProposedAction();
440 }
441}
442
443void Window::dropEvent(QDropEvent* event) {
444 QString uris = event->mimeData()->data("text/uri-list");
445 uris = uris.trimmed();
446 if (uris.contains("\n")) {
447 // Only one file please
448 return;
449 }
450 QUrl url(uris);
451 if (!url.isLocalFile()) {
452 // No remote loading
453 return;
454 }
455 event->accept();
456 m_controller->loadGame(url.path());
457}
458
459void Window::mouseDoubleClickEvent(QMouseEvent* event) {
460 if (event->button() != Qt::LeftButton) {
461 return;
462 }
463 toggleFullScreen();
464}
465
466void Window::enterFullScreen() {
467 if (isFullScreen()) {
468 return;
469 }
470 showFullScreen();
471#ifndef Q_OS_MAC
472 if (m_controller->isLoaded() && !m_controller->isPaused()) {
473 menuBar()->hide();
474 }
475#endif
476}
477
478void Window::exitFullScreen() {
479 if (!isFullScreen()) {
480 return;
481 }
482 showNormal();
483 menuBar()->show();
484}
485
486void Window::toggleFullScreen() {
487 if (isFullScreen()) {
488 exitFullScreen();
489 } else {
490 enterFullScreen();
491 }
492}
493
494void Window::gameStarted(GBAThread* context) {
495 char title[13] = { '\0' };
496 MutexLock(&context->stateMutex);
497 if (context->state < THREAD_EXITING) {
498 emit startDrawing(context);
499 GBAGetGameTitle(context->gba, title);
500 } else {
501 MutexUnlock(&context->stateMutex);
502 return;
503 }
504 MutexUnlock(&context->stateMutex);
505 foreach (QAction* action, m_gameActions) {
506 action->setDisabled(false);
507 }
508 appendMRU(context->fname);
509 setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
510 attachWidget(m_display);
511
512#ifndef Q_OS_MAC
513 if(isFullScreen()) {
514 menuBar()->hide();
515 }
516#endif
517
518 m_hitUnimplementedBiosCall = false;
519 m_fpsTimer.start();
520}
521
522void Window::gameStopped() {
523 foreach (QAction* action, m_gameActions) {
524 action->setDisabled(true);
525 }
526 setWindowTitle(tr(PROJECT_NAME));
527 detachWidget(m_display);
528 m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
529 m_screenWidget->setPixmap(m_logo);
530
531 m_fpsTimer.stop();
532}
533
534void Window::gameCrashed(const QString& errorMessage) {
535 QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
536 tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
537 QMessageBox::Ok, this, Qt::Sheet);
538 crash->setAttribute(Qt::WA_DeleteOnClose);
539 crash->show();
540}
541
542void Window::gameFailed() {
543 QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
544 tr("Could not load game. Are you sure it's in the correct format?"),
545 QMessageBox::Ok, this, Qt::Sheet);
546 fail->setAttribute(Qt::WA_DeleteOnClose);
547 fail->show();
548}
549
550void Window::unimplementedBiosCall(int call) {
551 if (m_hitUnimplementedBiosCall) {
552 return;
553 }
554 m_hitUnimplementedBiosCall = true;
555
556 QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Unimplemented BIOS call"),
557 tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
558 QMessageBox::Ok, this, Qt::Sheet);
559 fail->setAttribute(Qt::WA_DeleteOnClose);
560 fail->show();
561}
562
563void Window::recordFrame() {
564 m_frameList.append(QDateTime::currentDateTime());
565 while (m_frameList.count() > FRAME_LIST_SIZE) {
566 m_frameList.removeFirst();
567 }
568}
569
570void Window::showFPS() {
571 char gameTitle[13] = { '\0' };
572 GBAGetGameTitle(m_controller->thread()->gba, gameTitle);
573
574 QString title(gameTitle);
575 std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
576 if (multiplayer && multiplayer->attached() > 1) {
577 title += tr(" - Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
578 }
579 if (m_frameList.isEmpty()) {
580 setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
581 return;
582 }
583 qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
584 float fps = (m_frameList.count() - 1) * 10000.f / interval;
585 fps = round(fps) / 10.f;
586 setWindowTitle(tr(PROJECT_NAME " - %1 (%2 fps)").arg(title).arg(fps));
587}
588
589void Window::openStateWindow(LoadSave ls) {
590 if (m_stateWindow) {
591 return;
592 }
593 bool wasPaused = m_controller->isPaused();
594 m_stateWindow = new LoadSaveState(m_controller);
595 connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
596 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
597 connect(m_stateWindow, &LoadSaveState::closed, [this]() {
598 m_screenWidget->layout()->removeWidget(m_stateWindow);
599 m_stateWindow = nullptr;
600 QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
601 });
602 if (!wasPaused) {
603 m_controller->setPaused(true);
604 connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
605 }
606 m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
607 m_stateWindow->setMode(ls);
608 attachWidget(m_stateWindow);
609}
610
611void Window::setupMenu(QMenuBar* menubar) {
612 menubar->clear();
613 QMenu* fileMenu = menubar->addMenu(tr("&File"));
614 m_shortcutController->addMenu(fileMenu);
615 installEventFilter(m_shortcutController);
616 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open), "loadROM");
617 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
618 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
619
620 m_mruMenu = fileMenu->addMenu(tr("Recent"));
621
622 fileMenu->addSeparator();
623
624 QAction* loadState = new QAction(tr("&Load state"), fileMenu);
625 loadState->setShortcut(tr("F10"));
626 connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
627 m_gameActions.append(loadState);
628 addControlledAction(fileMenu, loadState, "loadState");
629
630 QAction* saveState = new QAction(tr("&Save state"), fileMenu);
631 saveState->setShortcut(tr("Shift+F10"));
632 connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
633 m_gameActions.append(saveState);
634 addControlledAction(fileMenu, saveState, "saveState");
635
636 QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
637 QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
638 m_shortcutController->addMenu(quickLoadMenu);
639 m_shortcutController->addMenu(quickSaveMenu);
640 int i;
641 for (i = 1; i < 10; ++i) {
642 QAction* quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
643 quickLoad->setShortcut(tr("F%1").arg(i));
644 connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
645 m_gameActions.append(quickLoad);
646 addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
647
648 QAction* quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
649 quickSave->setShortcut(tr("Shift+F%1").arg(i));
650 connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
651 m_gameActions.append(quickSave);
652 addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
653 }
654
655 fileMenu->addSeparator();
656 QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
657 connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
658 m_gameActions.append(importShark);
659 addControlledAction(fileMenu, importShark, "importShark");
660
661 QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
662 connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
663 m_gameActions.append(exportShark);
664 addControlledAction(fileMenu, exportShark, "exportShark");
665
666 fileMenu->addSeparator();
667 QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
668 connect(multiWindow, &QAction::triggered, [this]() {
669 std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
670 if (!multiplayer) {
671 multiplayer = std::make_shared<MultiplayerController>();
672 m_controller->setMultiplayerController(multiplayer);
673 }
674 Window* w2 = new Window(m_config, multiplayer->attached());
675 w2->setAttribute(Qt::WA_DeleteOnClose);
676#ifndef Q_OS_MAC
677 w2->show();
678#endif
679 w2->loadConfig();
680 w2->controller()->setMultiplayerController(multiplayer);
681#ifdef Q_OS_MAC
682 w2->show();
683#endif
684 });
685 addControlledAction(fileMenu, multiWindow, "multiWindow");
686
687#ifndef Q_OS_MAC
688 addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
689#endif
690
691 QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
692 m_shortcutController->addMenu(emulationMenu);
693 QAction* reset = new QAction(tr("&Reset"), emulationMenu);
694 reset->setShortcut(tr("Ctrl+R"));
695 connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
696 m_gameActions.append(reset);
697 addControlledAction(emulationMenu, reset, "reset");
698
699 QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
700 connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
701 m_gameActions.append(shutdown);
702 addControlledAction(emulationMenu, shutdown, "shutdown");
703 emulationMenu->addSeparator();
704
705 QAction* pause = new QAction(tr("&Pause"), emulationMenu);
706 pause->setChecked(false);
707 pause->setCheckable(true);
708 pause->setShortcut(tr("Ctrl+P"));
709 connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
710 connect(m_controller, &GameController::gamePaused, [this, pause]() {
711 pause->setChecked(true);
712
713 QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
714 QPixmap pixmap;
715 pixmap.convertFromImage(currentImage.rgbSwapped());
716 m_screenWidget->setPixmap(pixmap);
717 m_screenWidget->setLockAspectRatio(3, 2);
718 });
719 connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
720 m_gameActions.append(pause);
721 addControlledAction(emulationMenu, pause, "pause");
722
723 QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
724 frameAdvance->setShortcut(tr("Ctrl+N"));
725 connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
726 m_gameActions.append(frameAdvance);
727 addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
728
729 emulationMenu->addSeparator();
730
731 m_shortcutController->addFunctions(emulationMenu, [this]() {
732 m_controller->setTurbo(true, false);
733 }, [this]() {
734 m_controller->setTurbo(false, false);
735 }, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
736
737 QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
738 turbo->setCheckable(true);
739 turbo->setChecked(false);
740 turbo->setShortcut(tr("Shift+Tab"));
741 connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
742 addControlledAction(emulationMenu, turbo, "fastForward");
743
744 QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
745 rewind->setShortcut(tr("`"));
746 connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
747 m_gameActions.append(rewind);
748 addControlledAction(emulationMenu, rewind, "rewind");
749
750 QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
751 frameRewind->setShortcut(tr("Ctrl+B"));
752 connect(frameRewind, &QAction::triggered, [this] () {
753 m_controller->rewind(1);
754 });
755 m_gameActions.append(frameRewind);
756 addControlledAction(emulationMenu, frameRewind, "frameRewind");
757
758 ConfigOption* videoSync = m_config->addOption("videoSync");
759 videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
760 videoSync->connect([this](const QVariant& value) {
761 m_controller->setVideoSync(value.toBool());
762 }, this);
763 m_config->updateOption("videoSync");
764
765 ConfigOption* audioSync = m_config->addOption("audioSync");
766 audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
767 audioSync->connect([this](const QVariant& value) {
768 m_controller->setAudioSync(value.toBool());
769 }, this);
770 m_config->updateOption("audioSync");
771
772 emulationMenu->addSeparator();
773
774 QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
775 m_shortcutController->addMenu(solarMenu);
776 QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
777 connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
778 addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
779
780 QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
781 connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
782 addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
783
784 QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
785 connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
786 addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
787
788 QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
789 connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
790 addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
791
792 solarMenu->addSeparator();
793 for (int i = 0; i <= 10; ++i) {
794 QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
795 connect(setSolar, &QAction::triggered, [this, i]() {
796 m_controller->setLuminanceLevel(i);
797 });
798 addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
799 }
800
801 QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
802 m_shortcutController->addMenu(avMenu);
803 QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
804 m_shortcutController->addMenu(frameMenu, avMenu);
805 for (int i = 1; i <= 6; ++i) {
806 QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
807 connect(setSize, &QAction::triggered, [this, i]() {
808 showNormal();
809 resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
810 });
811 addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
812 }
813 addControlledAction(frameMenu, frameMenu->addAction(tr("Fullscreen"), this, SLOT(toggleFullScreen()), QKeySequence("Ctrl+F")), "fullscreen");
814
815 ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
816 lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
817 lockAspectRatio->connect([this](const QVariant& value) {
818 m_display->lockAspectRatio(value.toBool());
819 }, this);
820 m_config->updateOption("lockAspectRatio");
821
822 ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
823 resampleVideo->addBoolean(tr("Resample video"), avMenu);
824 resampleVideo->connect([this](const QVariant& value) {
825 m_display->filter(value.toBool());
826 }, this);
827 m_config->updateOption("resampleVideo");
828
829 QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
830 ConfigOption* skip = m_config->addOption("frameskip");
831 skip->connect([this](const QVariant& value) {
832 m_controller->setFrameskip(value.toInt());
833 }, this);
834 for (int i = 0; i <= 10; ++i) {
835 skip->addValue(QString::number(i), i, skipMenu);
836 }
837 m_config->updateOption("frameskip");
838
839 avMenu->addSeparator();
840
841 QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
842 ConfigOption* buffers = m_config->addOption("audioBuffers");
843 buffers->connect([this](const QVariant& value) {
844 emit audioBufferSamplesChanged(value.toInt());
845 }, this);
846 buffers->addValue(tr("512"), 512, buffersMenu);
847 buffers->addValue(tr("768"), 768, buffersMenu);
848 buffers->addValue(tr("1024"), 1024, buffersMenu);
849 buffers->addValue(tr("2048"), 2048, buffersMenu);
850 buffers->addValue(tr("4096"), 4096, buffersMenu);
851 m_config->updateOption("audioBuffers");
852
853 avMenu->addSeparator();
854
855 QMenu* target = avMenu->addMenu(tr("FPS target"));
856 ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
857 fpsTargetOption->connect([this](const QVariant& value) {
858 emit fpsTargetChanged(value.toFloat());
859 }, this);
860 fpsTargetOption->addValue(tr("15"), 15, target);
861 fpsTargetOption->addValue(tr("30"), 30, target);
862 fpsTargetOption->addValue(tr("45"), 45, target);
863 fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
864 fpsTargetOption->addValue(tr("60"), 60, target);
865 fpsTargetOption->addValue(tr("90"), 90, target);
866 fpsTargetOption->addValue(tr("120"), 120, target);
867 fpsTargetOption->addValue(tr("240"), 240, target);
868 m_config->updateOption("fpsTarget");
869
870#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
871 avMenu->addSeparator();
872#endif
873
874#ifdef USE_PNG
875 QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
876 screenshot->setShortcut(tr("F12"));
877 connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
878 m_gameActions.append(screenshot);
879 addControlledAction(avMenu, screenshot, "screenshot");
880#endif
881
882#ifdef USE_FFMPEG
883 QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
884 recordOutput->setShortcut(tr("F11"));
885 connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
886 addControlledAction(avMenu, recordOutput, "recordOutput");
887#endif
888
889#ifdef USE_MAGICK
890 QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
891 recordGIF->setShortcut(tr("Shift+F11"));
892 connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
893 addControlledAction(avMenu, recordGIF, "recordGIF");
894#endif
895
896 avMenu->addSeparator();
897 QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
898
899 for (int i = 0; i < 4; ++i) {
900 QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
901 enableBg->setCheckable(true);
902 enableBg->setChecked(true);
903 connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->video.renderer->disableBG[i] = !enable; });
904 m_gameActions.append(enableBg);
905 addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
906 }
907
908 QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
909 enableObj->setCheckable(true);
910 enableObj->setChecked(true);
911 connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->thread()->gba->video.renderer->disableOBJ = !enable; });
912 m_gameActions.append(enableObj);
913 addControlledAction(videoLayers, enableObj, "enableOBJ");
914
915 QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
916
917 for (int i = 0; i < 4; ++i) {
918 QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
919 enableCh->setCheckable(true);
920 enableCh->setChecked(true);
921 connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableCh[i] = !enable; });
922 m_gameActions.append(enableCh);
923 addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
924 }
925
926 QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
927 enableChA->setCheckable(true);
928 enableChA->setChecked(true);
929 connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChA = !enable; });
930 m_gameActions.append(enableChA);
931 addControlledAction(audioChannels, enableChA, QString("enableChA"));
932
933 QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
934 enableChB->setCheckable(true);
935 enableChB->setChecked(true);
936 connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChB = !enable; });
937 m_gameActions.append(enableChB);
938 addControlledAction(audioChannels, enableChB, QString("enableChB"));
939
940 QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
941 m_shortcutController->addMenu(toolsMenu);
942 QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
943 connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
944 addControlledAction(toolsMenu, viewLogs, "viewLogs");
945
946 QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
947 connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
948 addControlledAction(toolsMenu, overrides, "overrideWindow");
949
950 QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
951 connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
952 addControlledAction(toolsMenu, sensors, "sensorWindow");
953
954 QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
955 connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
956 addControlledAction(toolsMenu, cheats, "cheatsWindow");
957
958#ifdef USE_GDB_STUB
959 QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
960 connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
961 addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
962#endif
963
964 toolsMenu->addSeparator();
965 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())), "settings");
966 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())), "shortcuts");
967
968 QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
969 connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
970 addControlledAction(toolsMenu, keymap, "remapKeyboard");
971
972#ifdef BUILD_SDL
973 QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
974 connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
975 addControlledAction(toolsMenu, gamepad, "remapGamepad");
976#endif
977
978 toolsMenu->addSeparator();
979
980 QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
981 connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
982 m_gameActions.append(paletteView);
983 addControlledAction(toolsMenu, paletteView, "paletteWindow");
984
985 QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
986 connect(memoryView, SIGNAL(triggered()), this, SLOT(openMemoryWindow()));
987 m_gameActions.append(memoryView);
988 addControlledAction(toolsMenu, memoryView, "memoryView");
989
990 ConfigOption* skipBios = m_config->addOption("skipBios");
991 skipBios->connect([this](const QVariant& value) {
992 m_controller->setSkipBIOS(value.toBool());
993 }, this);
994
995 ConfigOption* volume = m_config->addOption("volume");
996 volume->connect([this](const QVariant& value) {
997 m_controller->setVolume(value.toInt());
998 }, this);
999
1000 ConfigOption* mute = m_config->addOption("mute");
1001 mute->connect([this](const QVariant& value) {
1002 m_controller->setMute(value.toBool());
1003 }, this);
1004
1005 ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1006 rewindEnable->connect([this](const QVariant& value) {
1007 m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
1008 }, this);
1009
1010 ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1011 rewindBufferCapacity->connect([this](const QVariant& value) {
1012 m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
1013 }, this);
1014
1015 ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
1016 rewindBufferInterval->connect([this](const QVariant& value) {
1017 m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
1018 }, this);
1019
1020 ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1021 allowOpposingDirections->connect([this](const QVariant& value) {
1022 m_inputController.setAllowOpposing(value.toBool());
1023 }, this);
1024
1025 QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1026 connect(exitFullScreen, SIGNAL(triggered()), this, SLOT(exitFullScreen()));
1027 exitFullScreen->setShortcut(QKeySequence("Esc"));
1028 addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1029
1030 foreach (QAction* action, m_gameActions) {
1031 action->setDisabled(true);
1032 }
1033}
1034
1035void Window::attachWidget(QWidget* widget) {
1036 m_screenWidget->layout()->addWidget(widget);
1037 static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1038}
1039
1040void Window::detachWidget(QWidget* widget) {
1041 m_screenWidget->layout()->removeWidget(widget);
1042}
1043
1044void Window::appendMRU(const QString& fname) {
1045 int index = m_mruFiles.indexOf(fname);
1046 if (index >= 0) {
1047 m_mruFiles.removeAt(index);
1048 }
1049 m_mruFiles.prepend(fname);
1050 while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1051 m_mruFiles.removeLast();
1052 }
1053 updateMRU();
1054}
1055
1056void Window::updateMRU() {
1057 if (!m_mruMenu) {
1058 return;
1059 }
1060 m_mruMenu->clear();
1061 int i = 0;
1062 for (const QString& file : m_mruFiles) {
1063 QAction* item = new QAction(file, m_mruMenu);
1064 item->setShortcut(QString("Ctrl+%1").arg(i));
1065 connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1066 m_mruMenu->addAction(item);
1067 ++i;
1068 }
1069 m_config->setMRU(m_mruFiles);
1070 m_config->write();
1071 m_mruMenu->setEnabled(i > 0);
1072}
1073
1074QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1075 addHiddenAction(menu, action, name);
1076 menu->addAction(action);
1077 return action;
1078}
1079
1080QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1081 m_shortcutController->addAction(menu, action, name);
1082 action->setShortcutContext(Qt::WidgetShortcut);
1083 addAction(action);
1084 return action;
1085}
1086
1087WindowBackground::WindowBackground(QWidget* parent)
1088 : QLabel(parent)
1089{
1090 setLayout(new QStackedLayout());
1091 layout()->setContentsMargins(0, 0, 0, 0);
1092 setAlignment(Qt::AlignCenter);
1093}
1094
1095void WindowBackground::setSizeHint(const QSize& hint) {
1096 m_sizeHint = hint;
1097}
1098
1099QSize WindowBackground::sizeHint() const {
1100 return m_sizeHint;
1101}
1102
1103void WindowBackground::setLockAspectRatio(int width, int height) {
1104 m_aspectWidth = width;
1105 m_aspectHeight = height;
1106}
1107
1108void WindowBackground::paintEvent(QPaintEvent*) {
1109 const QPixmap* logo = pixmap();
1110 if (!logo) {
1111 return;
1112 }
1113 QPainter painter(this);
1114 painter.setRenderHint(QPainter::SmoothPixmapTransform);
1115 painter.fillRect(QRect(QPoint(), size()), Qt::black);
1116 QSize s = size();
1117 QSize ds = s;
1118 if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
1119 ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
1120 } else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
1121 ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
1122 }
1123 QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1124 QRect full(origin, ds);
1125 painter.drawPixmap(full, *logo);
1126}