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