/
qthost.cpp
2229 lines (1871 loc) · 64.4 KB
/
qthost.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "qthost.h"
#include "common/assert.h"
#include "common/byte_stream.h"
#include "common/crash_handler.h"
#include "common/file_system.h"
#include "common/log.h"
#include "common/path.h"
#include "common/string_util.h"
#include "core/cheats.h"
#include "core/controller.h"
#include "core/game_database.h"
#include "core/gpu.h"
#include "core/host.h"
#include "core/host_settings.h"
#include "core/memory_card.h"
#include "core/spu.h"
#include "core/system.h"
#include "displaywidget.h"
#include "frontend-common/fullscreen_ui.h"
#include "frontend-common/game_list.h"
#include "frontend-common/imgui_manager.h"
#include "frontend-common/imgui_overlays.h"
#include "frontend-common/input_manager.h"
#include "imgui.h"
#include "mainwindow.h"
#include "qtprogresscallback.h"
#include "qtutils.h"
#include "scmversion/scmversion.h"
#include "util/audio_stream.h"
#include "util/ini_settings_interface.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtCore/QEventLoop>
#include <QtCore/QFile>
#include <QtCore/QTimer>
#include <QtGui/QClipboard>
#include <QtGui/QKeyEvent>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMessageBox>
#include <algorithm>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <memory>
Log_SetChannel(EmuThread);
#ifdef _WIN32
#include "common/windows_headers.h"
#include <ShlObj.h>
#endif
#ifdef WITH_CHEEVOS
#include "frontend-common/achievements.h"
#endif
static constexpr u32 SETTINGS_VERSION = 3;
static constexpr u32 SETTINGS_SAVE_DELAY = 1000;
/// Interval at which the controllers are polled when the system is not active.
static constexpr u32 BACKGROUND_CONTROLLER_POLLING_INTERVAL = 100;
/// Poll at half the vsync rate for FSUI to reduce the chance of getting a press+release in the same frame.
static constexpr u32 FULLSCREEN_UI_CONTROLLER_POLLING_INTERVAL = 8;
//////////////////////////////////////////////////////////////////////////
// Local function declarations
//////////////////////////////////////////////////////////////////////////
namespace QtHost {
static void RegisterTypes();
static bool InitializeConfig(std::string settings_filename);
static bool ShouldUsePortableMode();
static void SetAppRoot();
static void SetResourcesDirectory();
static void SetDataDirectory();
static bool SetCriticalFolders();
static void SetDefaultSettings(SettingsInterface& si, bool system, bool controller);
static void SaveSettings();
static void InitializeEarlyConsole();
static void HookSignals();
static void PrintCommandLineVersion();
static void PrintCommandLineHelp(const char* progname);
static bool ParseCommandLineParametersAndInitializeConfig(QApplication& app,
std::shared_ptr<SystemBootParameters>& boot_params);
} // namespace QtHost
static std::unique_ptr<INISettingsInterface> s_base_settings_interface;
static std::unique_ptr<QTimer> s_settings_save_timer;
static bool s_batch_mode = false;
static bool s_nogui_mode = false;
static bool s_start_fullscreen_ui = false;
static bool s_start_fullscreen_ui_fullscreen = false;
EmuThread* g_emu_thread;
EmuThread::EmuThread(QThread* ui_thread) : QThread(), m_ui_thread(ui_thread) {}
EmuThread::~EmuThread() = default;
void QtHost::RegisterTypes()
{
// Register any standard types we need elsewhere
qRegisterMetaType<std::optional<bool>>();
qRegisterMetaType<std::function<void()>>("std::function<void()>");
qRegisterMetaType<std::shared_ptr<SystemBootParameters>>();
qRegisterMetaType<const GameList::Entry*>();
qRegisterMetaType<GPURenderer>("GPURenderer");
qRegisterMetaType<InputBindingKey>("InputBindingKey");
}
bool QtHost::InBatchMode()
{
return s_batch_mode;
}
bool QtHost::InNoGUIMode()
{
return s_nogui_mode;
}
QString QtHost::GetAppNameAndVersion()
{
return QStringLiteral("DuckStation %1 (%2)").arg(g_scm_tag_str).arg(g_scm_branch_str);
}
QString QtHost::GetAppConfigSuffix()
{
#if defined(_DEBUGFAST)
return QStringLiteral(" [DebugFast]");
#elif defined(_DEBUG)
return QStringLiteral(" [Debug]");
#else
return QString();
#endif
}
QString QtHost::GetResourcesBasePath()
{
return QString::fromStdString(EmuFolders::Resources);
}
bool QtHost::InitializeConfig(std::string settings_filename)
{
if (!SetCriticalFolders())
return false;
if (settings_filename.empty())
settings_filename = Path::Combine(EmuFolders::DataRoot, "settings.ini");
Log_InfoPrintf("Loading config from %s.", settings_filename.c_str());
s_base_settings_interface = std::make_unique<INISettingsInterface>(std::move(settings_filename));
Host::Internal::SetBaseSettingsLayer(s_base_settings_interface.get());
uint settings_version;
if (!s_base_settings_interface->Load() ||
!s_base_settings_interface->GetUIntValue("Main", "SettingsVersion", &settings_version) ||
settings_version != SETTINGS_VERSION)
{
if (s_base_settings_interface->ContainsValue("Main", "SettingsVersion"))
{
// NOTE: No point translating this, because there's no config loaded, so no language loaded.
Host::ReportErrorAsync("Error", fmt::format("Settings version {} does not match expected version {}, resetting.",
settings_version, SETTINGS_VERSION));
}
s_base_settings_interface->SetUIntValue("Main", "SettingsVersion", SETTINGS_VERSION);
SetDefaultSettings(*s_base_settings_interface, true, true);
s_base_settings_interface->Save();
}
EmuFolders::LoadConfig(*s_base_settings_interface.get());
EmuFolders::EnsureFoldersExist();
// We need to create the console window early, otherwise it appears behind the main window.
if (!Log::IsConsoleOutputEnabled() &&
s_base_settings_interface->GetBoolValue("Logging", "LogToConsole", Settings::DEFAULT_LOG_TO_CONSOLE))
{
Log::SetConsoleOutputParams(true, nullptr, LOGLEVEL_NONE);
}
InstallTranslator();
return true;
}
bool QtHost::SetCriticalFolders()
{
SetAppRoot();
SetResourcesDirectory();
SetDataDirectory();
// logging of directories in case something goes wrong super early
Log_DevPrintf("AppRoot Directory: %s", EmuFolders::AppRoot.c_str());
Log_DevPrintf("DataRoot Directory: %s", EmuFolders::DataRoot.c_str());
Log_DevPrintf("Resources Directory: %s", EmuFolders::Resources.c_str());
// Write crash dumps to the data directory, since that'll be accessible for certain.
CrashHandler::SetWriteDirectory(EmuFolders::DataRoot);
// the resources directory should exist, bail out if not
if (!FileSystem::DirectoryExists(EmuFolders::Resources.c_str()))
{
QMessageBox::critical(nullptr, QStringLiteral("Error"),
QStringLiteral("Resources directory is missing, your installation is incomplete."));
return false;
}
return true;
}
bool QtHost::ShouldUsePortableMode()
{
// Check whether portable.ini exists in the program directory.
return (FileSystem::FileExists(Path::Combine(EmuFolders::AppRoot, "portable.txt").c_str()) ||
FileSystem::FileExists(Path::Combine(EmuFolders::AppRoot, "settings.ini").c_str()));
}
void QtHost::SetAppRoot()
{
std::string program_path(FileSystem::GetProgramPath());
Log_InfoPrintf("Program Path: %s", program_path.c_str());
EmuFolders::AppRoot = Path::Canonicalize(Path::GetDirectory(program_path));
}
void QtHost::SetResourcesDirectory()
{
#ifndef __APPLE__
// On Windows/Linux, these are in the binary directory.
EmuFolders::Resources = Path::Combine(EmuFolders::AppRoot, "resources");
#else
// On macOS, this is in the bundle resources directory.
EmuFolders::Resources = Path::Canonicalize(Path::Combine(EmuFolders::AppRoot, "../Resources"));
#endif
}
void QtHost::SetDataDirectory()
{
if (ShouldUsePortableMode())
{
EmuFolders::DataRoot = EmuFolders::AppRoot;
return;
}
#if defined(_WIN32)
// On Windows, use My Documents\DuckStation.
PWSTR documents_directory;
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Documents, 0, NULL, &documents_directory)))
{
if (std::wcslen(documents_directory) > 0)
EmuFolders::DataRoot = Path::Combine(StringUtil::WideStringToUTF8String(documents_directory), "DuckStation");
CoTaskMemFree(documents_directory);
}
#elif defined(__linux__)
// Use $XDG_CONFIG_HOME/duckstation if it exists.
const char* xdg_config_home = getenv("XDG_CONFIG_HOME");
if (xdg_config_home && Path::IsAbsolute(xdg_config_home))
{
EmuFolders::DataRoot = Path::Combine(xdg_config_home, "duckstation");
}
else
{
// Use ~/.local/share/duckstation otherwise.
const char* home_dir = getenv("HOME");
if (home_dir)
{
// ~/.local/share should exist, but just in case it doesn't and this is a fresh profile..
const std::string local_dir(Path::Combine(home_dir, ".local"));
const std::string share_dir(Path::Combine(local_dir, "share"));
FileSystem::EnsureDirectoryExists(local_dir.c_str(), false);
FileSystem::EnsureDirectoryExists(share_dir.c_str(), false);
EmuFolders::DataRoot = Path::Combine(share_dir, "duckstation");
}
}
#elif defined(__APPLE__)
static constexpr char MAC_DATA_DIR[] = "Library/Application Support/DuckStation";
const char* home_dir = getenv("HOME");
if (home_dir)
EmuFolders::DataRoot = Path::Combine(home_dir, MAC_DATA_DIR);
#endif
// make sure it exists
if (!EmuFolders::DataRoot.empty() && !FileSystem::DirectoryExists(EmuFolders::DataRoot.c_str()))
{
// we're in trouble if we fail to create this directory... but try to hobble on with portable
if (!FileSystem::EnsureDirectoryExists(EmuFolders::DataRoot.c_str(), false))
EmuFolders::DataRoot.clear();
}
// couldn't determine the data directory? fallback to portable.
if (EmuFolders::DataRoot.empty())
EmuFolders::DataRoot = EmuFolders::AppRoot;
}
#if 0
void QtHost::UpdateFolders()
{
// TODO: This should happen with the VM thread paused.
auto lock = Host::GetSettingsLock();
EmuFolders::LoadConfig(*s_base_settings_interface.get());
EmuFolders::EnsureFoldersExist();
}
#endif
void Host::LoadSettings(SettingsInterface& si, std::unique_lock<std::mutex>& lock)
{
CommonHost::LoadSettings(si, lock);
g_emu_thread->loadSettings(si);
}
void EmuThread::loadSettings(SettingsInterface& si)
{
//
}
void EmuThread::setInitialState()
{
m_is_fullscreen = Host::GetBaseBoolSettingValue("Main", "StartFullscreen", false);
m_is_rendering_to_main = shouldRenderToMain();
m_is_surfaceless = false;
}
void Host::CheckForSettingsChanges(const Settings& old_settings)
{
CommonHost::CheckForSettingsChanges(old_settings);
g_emu_thread->checkForSettingsChanges(old_settings);
}
void EmuThread::checkForSettingsChanges(const Settings& old_settings)
{
const bool render_to_main = shouldRenderToMain();
if (m_is_rendering_to_main != render_to_main)
{
m_is_rendering_to_main = render_to_main;
updateDisplayState();
}
QMetaObject::invokeMethod(g_main_window, &MainWindow::checkForSettingChanges, Qt::QueuedConnection);
}
void EmuThread::setDefaultSettings(bool system /* = true */, bool controller /* = true */)
{
if (isOnThread())
{
QMetaObject::invokeMethod(this, "setDefaultSettings", Qt::QueuedConnection);
return;
}
auto lock = Host::GetSettingsLock();
QtHost::SetDefaultSettings(*s_base_settings_interface, system, controller);
QtHost::QueueSettingsSave();
applySettings(false);
if (system)
emit settingsResetToDefault();
}
void QtHost::SetDefaultSettings(SettingsInterface& si, bool system, bool controller)
{
if (system)
{
System::SetDefaultSettings(si);
CommonHost::SetDefaultSettings(si);
EmuFolders::SetDefaults();
EmuFolders::Save(si);
}
if (controller)
{
CommonHost::SetDefaultControllerSettings(si);
CommonHost::SetDefaultHotkeyBindings(si);
}
}
bool EmuThread::shouldRenderToMain() const
{
return !Host::GetBaseBoolSettingValue("Main", "RenderToSeparateWindow", false) && !QtHost::InNoGUIMode();
}
void Host::RequestResizeHostDisplay(s32 new_window_width, s32 new_window_height)
{
if (g_emu_thread->isFullscreen())
return;
emit g_emu_thread->displaySizeRequested(new_window_width, new_window_height);
}
void EmuThread::applySettings(bool display_osd_messages /* = false */)
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, "applySettings", Qt::QueuedConnection, Q_ARG(bool, display_osd_messages));
return;
}
System::ApplySettings(display_osd_messages);
if (!FullscreenUI::IsInitialized() && System::IsPaused())
redrawDisplayWindow();
}
void EmuThread::reloadGameSettings(bool display_osd_messages /* = false */)
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, "reloadGameSettings", Qt::QueuedConnection, Q_ARG(bool, display_osd_messages));
return;
}
System::ReloadGameSettings(display_osd_messages);
if (!FullscreenUI::IsInitialized() && System::IsPaused())
redrawDisplayWindow();
}
void EmuThread::updateEmuFolders()
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, &EmuThread::updateEmuFolders, Qt::QueuedConnection);
return;
}
EmuFolders::Update();
}
void EmuThread::startFullscreenUI()
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, &EmuThread::startFullscreenUI, Qt::QueuedConnection);
return;
}
if (System::IsValid())
return;
// we want settings loaded so we choose the correct renderer
// this also sorts out input sources.
System::LoadSettings(false);
setInitialState();
m_run_fullscreen_ui = true;
if (s_start_fullscreen_ui_fullscreen)
m_is_fullscreen = true;
if (!acquireHostDisplay(Settings::GetRenderAPIForRenderer(g_settings.gpu_renderer)))
{
m_run_fullscreen_ui = false;
return;
}
// poll more frequently so we don't lose events
stopBackgroundControllerPollTimer();
startBackgroundControllerPollTimer();
wakeThread();
}
void EmuThread::stopFullscreenUI()
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, &EmuThread::stopFullscreenUI, Qt::QueuedConnection);
// wait until the host display is gone
while (g_host_display)
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents, 1);
return;
}
if (System::IsValid())
shutdownSystem();
if (!g_host_display)
return;
m_run_fullscreen_ui = false;
releaseHostDisplay();
}
void EmuThread::bootSystem(std::shared_ptr<SystemBootParameters> params)
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, "bootSystem", Qt::QueuedConnection,
Q_ARG(std::shared_ptr<SystemBootParameters>, std::move(params)));
return;
}
setInitialState();
if (!System::BootSystem(std::move(*params)))
return;
// force a frame to be drawn to repaint the window
renderDisplay(false);
}
void EmuThread::bootOrLoadState(std::string path)
{
DebugAssert(isOnThread());
if (System::IsValid())
{
System::LoadState(path.c_str());
}
else
{
std::shared_ptr<SystemBootParameters> params = std::make_shared<SystemBootParameters>();
params->save_state = std::move(path);
bootSystem(std::move(params));
}
}
void EmuThread::resumeSystemFromMostRecentState()
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, &EmuThread::resumeSystemFromMostRecentState, Qt::QueuedConnection);
return;
}
// shouldn't be doing this with a system running
if (System::IsValid())
return;
std::string state_filename(System::GetMostRecentResumeSaveStatePath());
if (state_filename.empty())
{
emit errorReported(tr("Error"), tr("No resume save state found."));
return;
}
bootOrLoadState(std::move(state_filename));
}
void EmuThread::onDisplayWindowKeyEvent(int key, bool pressed)
{
DebugAssert(isOnThread());
InputManager::InvokeEvents(InputManager::MakeHostKeyboardKey(key), static_cast<float>(pressed),
GenericInputBinding::Unknown);
}
void EmuThread::onDisplayWindowTextEntered(const QString& text)
{
DebugAssert(isOnThread());
ImGuiManager::AddTextInput(text.toStdString());
}
void EmuThread::onDisplayWindowMouseMoveEvent(bool relative, float x, float y)
{
// display might be null here if the event happened after shutdown
DebugAssert(isOnThread());
if (!relative)
{
if (g_host_display)
g_host_display->SetMousePosition(static_cast<s32>(x), static_cast<s32>(y));
InputManager::UpdatePointerAbsolutePosition(0, x, y);
ImGuiManager::UpdateMousePosition(x, y);
}
else
{
if (x != 0.0f)
InputManager::UpdatePointerRelativeDelta(0, InputPointerAxis::X, x);
if (y != 0.0f)
InputManager::UpdatePointerRelativeDelta(0, InputPointerAxis::Y, y);
if (g_host_display)
{
const float abs_x = static_cast<float>(g_host_display->GetMousePositionX()) + x;
const float abs_y = static_cast<float>(g_host_display->GetMousePositionY()) + y;
g_host_display->SetMousePosition(static_cast<s32>(abs_x), static_cast<s32>(abs_y));
ImGuiManager::UpdateMousePosition(abs_x, abs_y);
}
}
}
void EmuThread::onDisplayWindowMouseButtonEvent(int button, bool pressed)
{
DebugAssert(isOnThread());
InputManager::InvokeEvents(InputManager::MakePointerButtonKey(0, button), static_cast<float>(pressed),
GenericInputBinding::Unknown);
}
void EmuThread::onDisplayWindowMouseWheelEvent(const QPoint& delta_angle)
{
DebugAssert(isOnThread());
const float dx = std::clamp(static_cast<float>(delta_angle.x()) / QtUtils::MOUSE_WHEEL_DELTA, -1.0f, 1.0f);
if (dx != 0.0f)
InputManager::UpdatePointerRelativeDelta(0, InputPointerAxis::WheelX, dx);
const float dy = std::clamp(static_cast<float>(delta_angle.y()) / QtUtils::MOUSE_WHEEL_DELTA, -1.0f, 1.0f);
if (dy != 0.0f)
InputManager::UpdatePointerRelativeDelta(0, InputPointerAxis::WheelY, dy);
}
void EmuThread::onDisplayWindowResized(int width, int height)
{
// this can be null if it was destroyed and the main thread is late catching up
if (!g_host_display)
return;
Log_DevPrintf("Display window resized to %dx%d", width, height);
g_host_display->ResizeRenderWindow(width, height);
ImGuiManager::WindowResized();
System::HostDisplayResized();
// re-render the display, since otherwise it will be out of date and stretched if paused
if (System::IsValid())
{
if (m_is_exclusive_fullscreen && !g_host_display->IsFullscreen())
{
// we lost exclusive fullscreen, switch to borderless
Host::AddOSDMessage(Host::TranslateStdString("OSDMessage", "Lost exclusive fullscreen."), 10.0f);
m_is_exclusive_fullscreen = false;
m_is_fullscreen = false;
m_lost_exclusive_fullscreen = true;
}
// force redraw if we're paused
if (!System::IsRunning() && !FullscreenUI::HasActiveWindow())
renderDisplay(false);
}
}
void EmuThread::redrawDisplayWindow()
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, "redrawDisplayWindow", Qt::QueuedConnection);
return;
}
if (!g_host_display || System::IsShutdown())
return;
renderDisplay(false);
}
void EmuThread::toggleFullscreen()
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, "toggleFullscreen", Qt::QueuedConnection);
return;
}
setFullscreen(!m_is_fullscreen);
}
void EmuThread::setFullscreen(bool fullscreen)
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, "setFullscreen", Qt::QueuedConnection, Q_ARG(bool, fullscreen));
return;
}
if (!g_host_display || m_is_fullscreen == fullscreen)
return;
m_is_fullscreen = fullscreen;
updateDisplayState();
}
bool Host::IsFullscreen()
{
return g_emu_thread->isFullscreen();
}
void Host::SetFullscreen(bool enabled)
{
g_emu_thread->setFullscreen(enabled);
}
void EmuThread::setSurfaceless(bool surfaceless)
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, "setSurfaceless", Qt::QueuedConnection, Q_ARG(bool, surfaceless));
return;
}
if (!g_host_display || m_is_surfaceless == surfaceless)
return;
m_is_surfaceless = surfaceless;
updateDisplayState();
}
void EmuThread::requestDisplaySize(float scale)
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, "requestDisplaySize", Qt::QueuedConnection, Q_ARG(float, scale));
return;
}
if (!System::IsValid())
return;
System::RequestDisplaySize(scale);
}
bool EmuThread::acquireHostDisplay(RenderAPI api)
{
if (g_host_display)
{
if (g_host_display->GetRenderAPI() == api)
{
// current is fine
return true;
}
// otherwise we need to switch
releaseHostDisplay();
}
g_host_display = Host::CreateDisplayForAPI(api);
if (!g_host_display)
return false;
if (!createDisplayRequested(m_is_fullscreen, m_is_rendering_to_main))
{
emit destroyDisplayRequested();
g_host_display.reset();
return false;
}
if (!g_host_display->MakeRenderContextCurrent() ||
!g_host_display->InitializeRenderDevice(EmuFolders::Cache, g_settings.gpu_use_debug_device,
g_settings.gpu_threaded_presentation) ||
!ImGuiManager::Initialize() || !CommonHost::CreateHostDisplayResources())
{
ImGuiManager::Shutdown();
CommonHost::ReleaseHostDisplayResources();
g_host_display->DestroyRenderDevice();
emit destroyDisplayRequested();
g_host_display.reset();
return false;
}
m_is_exclusive_fullscreen = g_host_display->IsFullscreen();
if (m_run_fullscreen_ui)
{
if (!FullscreenUI::Initialize())
{
Log_ErrorPrint("Failed to initialize fullscreen UI");
releaseHostDisplay();
m_run_fullscreen_ui = false;
return false;
}
// start with vsync on
g_host_display->SetVSync(true);
}
return true;
}
void EmuThread::connectDisplaySignals(DisplayWidget* widget)
{
widget->disconnect(this);
connect(widget, &DisplayWidget::windowResizedEvent, this, &EmuThread::onDisplayWindowResized);
connect(widget, &DisplayWidget::windowRestoredEvent, this, &EmuThread::redrawDisplayWindow);
connect(widget, &DisplayWidget::windowKeyEvent, this, &EmuThread::onDisplayWindowKeyEvent);
connect(widget, &DisplayWidget::windowTextEntered, this, &EmuThread::onDisplayWindowTextEntered);
connect(widget, &DisplayWidget::windowMouseMoveEvent, this, &EmuThread::onDisplayWindowMouseMoveEvent);
connect(widget, &DisplayWidget::windowMouseButtonEvent, this, &EmuThread::onDisplayWindowMouseButtonEvent);
connect(widget, &DisplayWidget::windowMouseWheelEvent, this, &EmuThread::onDisplayWindowMouseWheelEvent);
}
void EmuThread::updateDisplayState()
{
if (!g_host_display)
return;
// this expects the context to get moved back to us afterwards
g_host_display->DoneRenderContextCurrent();
updateDisplayRequested(m_is_fullscreen, m_is_rendering_to_main && !m_is_fullscreen, m_is_surfaceless);
if (!g_host_display->MakeRenderContextCurrent())
Panic("Failed to make device context current after updating");
m_is_exclusive_fullscreen = g_host_display->IsFullscreen();
ImGuiManager::WindowResized();
System::HostDisplayResized();
if (!System::IsShutdown())
{
System::UpdateSoftwareCursor();
if (!FullscreenUI::IsInitialized() || System::IsPaused())
redrawDisplayWindow();
}
System::UpdateSpeedLimiterState();
}
void EmuThread::releaseHostDisplay()
{
if (!g_host_display)
return;
CommonHost::ReleaseHostDisplayResources();
ImGuiManager::Shutdown();
g_host_display->DestroyRenderDevice();
emit destroyDisplayRequested();
g_host_display.reset();
m_is_fullscreen = false;
}
void Host::OnSystemStarting()
{
CommonHost::OnSystemStarting();
emit g_emu_thread->systemStarting();
}
void Host::OnSystemStarted()
{
CommonHost::OnSystemStarted();
g_emu_thread->wakeThread();
g_emu_thread->stopBackgroundControllerPollTimer();
emit g_emu_thread->systemStarted();
}
void Host::OnSystemPaused()
{
CommonHost::OnSystemPaused();
emit g_emu_thread->systemPaused();
g_emu_thread->startBackgroundControllerPollTimer();
g_emu_thread->renderDisplay(false);
}
void Host::OnSystemResumed()
{
CommonHost::OnSystemResumed();
// if we were surfaceless (view->game list, system->unpause), get our display widget back
if (g_emu_thread->isSurfaceless())
g_emu_thread->setSurfaceless(false);
emit g_emu_thread->systemResumed();
g_emu_thread->wakeThread();
g_emu_thread->stopBackgroundControllerPollTimer();
}
void Host::OnSystemDestroyed()
{
CommonHost::OnSystemDestroyed();
g_emu_thread->resetPerformanceCounters();
g_emu_thread->startBackgroundControllerPollTimer();
emit g_emu_thread->systemDestroyed();
// re-wake thread when we're running fsui, otherwise it won't draw
if (g_emu_thread->isRunningFullscreenUI())
g_emu_thread->wakeThread();
}
void EmuThread::reloadInputSources()
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, &EmuThread::reloadInputSources, Qt::QueuedConnection);
return;
}
std::unique_lock<std::mutex> lock = Host::GetSettingsLock();
SettingsInterface* si = Host::GetSettingsInterface();
SettingsInterface* bindings_si = Host::GetSettingsInterfaceForBindings();
InputManager::ReloadSources(*si, lock);
InputManager::ReloadBindings(*si, *bindings_si);
}
void EmuThread::reloadInputBindings()
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, &EmuThread::reloadInputBindings, Qt::QueuedConnection);
return;
}
auto lock = Host::GetSettingsLock();
SettingsInterface* si = Host::GetSettingsInterface();
SettingsInterface* bindings_si = Host::GetSettingsInterfaceForBindings();
InputManager::ReloadBindings(*si, *bindings_si);
}
void EmuThread::enumerateInputDevices()
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, &EmuThread::enumerateInputDevices, Qt::QueuedConnection);
return;
}
const std::vector<std::pair<std::string, std::string>> devs(InputManager::EnumerateDevices());
QList<QPair<QString, QString>> qdevs;
qdevs.reserve(devs.size());
for (const std::pair<std::string, std::string>& dev : devs)
qdevs.emplace_back(QString::fromStdString(dev.first), QString::fromStdString(dev.second));
onInputDevicesEnumerated(qdevs);
}
void EmuThread::enumerateVibrationMotors()
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, &EmuThread::enumerateVibrationMotors, Qt::QueuedConnection);
return;
}
const std::vector<InputBindingKey> motors(InputManager::EnumerateMotors());
QList<InputBindingKey> qmotors;
qmotors.reserve(motors.size());
for (InputBindingKey key : motors)
qmotors.push_back(key);
onVibrationMotorsEnumerated(qmotors);
}
void EmuThread::shutdownSystem(bool save_state /* = true */)
{
if (!isOnThread())
{
System::CancelPendingStartup();
QMetaObject::invokeMethod(this, "shutdownSystem", Qt::QueuedConnection, Q_ARG(bool, save_state));
return;
}
System::ShutdownSystem(save_state);
}
void EmuThread::resetSystem()
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, &EmuThread::resetSystem, Qt::QueuedConnection);
return;
}
System::ResetSystem();
}
void EmuThread::setSystemPaused(bool paused, bool wait_until_paused /* = false */)
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, "setSystemPaused",
wait_until_paused ? Qt::BlockingQueuedConnection : Qt::QueuedConnection,
Q_ARG(bool, paused), Q_ARG(bool, wait_until_paused));
return;
}
System::PauseSystem(paused);
}
void EmuThread::changeDisc(const QString& new_disc_filename)
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, "changeDisc", Qt::QueuedConnection, Q_ARG(const QString&, new_disc_filename));
return;
}
if (System::IsShutdown())
return;
if (!new_disc_filename.isEmpty())
System::InsertMedia(new_disc_filename.toStdString().c_str());
else
System::RemoveMedia();
}
void EmuThread::changeDiscFromPlaylist(quint32 index)
{
if (!isOnThread())
{
QMetaObject::invokeMethod(this, "changeDiscFromPlaylist", Qt::QueuedConnection, Q_ARG(quint32, index));
return;
}
if (System::IsShutdown())
return;
if (!System::SwitchMediaSubImage(index))