-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathSDLMain.cpp
1643 lines (1479 loc) · 44.4 KB
/
SDLMain.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 <cstdlib>
#include <unistd.h>
#include <pwd.h>
#include "ppsspp_config.h"
#if PPSSPP_PLATFORM(MAC)
#include "SDL2/SDL.h"
#include "SDL2/SDL_syswm.h"
#else
#include "SDL.h"
#include "SDL_syswm.h"
#endif
#include "SDL/SDLJoystick.h"
SDLJoystick *joystick = NULL;
#if PPSSPP_PLATFORM(RPI)
#include <bcm_host.h>
#endif
#include <atomic>
#include <algorithm>
#include <cmath>
#include <csignal>
#include <thread>
#include <locale>
#include "Common/System/Display.h"
#include "Common/System/System.h"
#include "Common/System/Request.h"
#include "Common/System/NativeApp.h"
#include "ext/glslang/glslang/Public/ShaderLang.h"
#include "Common/Data/Format/PNGLoad.h"
#include "Common/Net/Resolve.h"
#include "Common/File/FileUtil.h"
#include "NKCodeFromSDL.h"
#include "Common/Math/math_util.h"
#include "Common/GPU/OpenGL/GLRenderManager.h"
#include "Common/Profiler/Profiler.h"
#include "Common/Log/LogManager.h"
#if defined(VK_USE_PLATFORM_XLIB_KHR)
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#elif defined(VK_USE_PLATFORM_XCB_KHR)
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xlib-xcb.h>
#endif
#include "Common/GraphicsContext.h"
#include "Common/TimeUtil.h"
#include "Common/Input/InputState.h"
#include "Common/Input/KeyCodes.h"
#include "Common/Data/Collections/ConstMap.h"
#include "Common/Data/Encoding/Utf8.h"
#include "Common/Thread/ThreadUtil.h"
#include "Core/System.h"
#include "Core/Core.h"
#include "Core/Config.h"
#include "Core/ConfigValues.h"
#include "SDLGLGraphicsContext.h"
#include "SDLVulkanGraphicsContext.h"
#if PPSSPP_PLATFORM(MAC)
#include "SDL2/SDL_vulkan.h"
#else
#include "SDL_vulkan.h"
#endif
#if PPSSPP_PLATFORM(MAC) || PPSSPP_PLATFORM(IOS)
#include "UI/DarwinFileSystemServices.h"
#endif
#if PPSSPP_PLATFORM(MAC)
#include "CocoaBarItems.h"
#endif
#if PPSSPP_PLATFORM(SWITCH)
#define LIBNX_SWKBD_LIMIT 500 // enforced by HOS
extern u32 __nx_applet_type; // Not exposed through a header?
#endif
GlobalUIState lastUIState = UISTATE_MENU;
GlobalUIState GetUIState();
static bool g_QuitRequested = false;
static bool g_RestartRequested = false;
static int g_DesktopWidth = 0;
static int g_DesktopHeight = 0;
static float g_DesktopDPI = 1.0f;
static float g_ForcedDPI = 0.0f; // if this is 0.0f, use g_DesktopDPI
static float g_RefreshRate = 60.f;
static int g_sampleRate = 44100;
static bool g_rebootEmuThread = false;
static SDL_AudioSpec g_retFmt;
static bool g_textFocusChanged;
static bool g_textFocus;
// Window state to be transferred to the main SDL thread.
static std::mutex g_mutexWindow;
struct WindowState {
std::string title;
bool toggleFullScreenNextFrame;
int toggleFullScreenType;
bool clipboardDataAvailable;
std::string clipboardString;
bool update;
};
static WindowState g_windowState;
int getDisplayNumber(void) {
int displayNumber = 0;
char * displayNumberStr;
//get environment
displayNumberStr=getenv("SDL_VIDEO_FULLSCREEN_HEAD");
if (displayNumberStr) {
displayNumber = atoi(displayNumberStr);
}
return displayNumber;
}
void sdl_mixaudio_callback(void *userdata, Uint8 *stream, int len) {
NativeMix((short *)stream, len / (2 * 2), g_sampleRate);
}
static SDL_AudioDeviceID audioDev = 0;
// Must be called after NativeInit().
static void InitSDLAudioDevice(const std::string &name = "") {
SDL_AudioSpec fmt;
memset(&fmt, 0, sizeof(fmt));
fmt.freq = g_sampleRate;
fmt.format = AUDIO_S16;
fmt.channels = 2;
fmt.samples = 256;
fmt.callback = &sdl_mixaudio_callback;
fmt.userdata = nullptr;
std::string startDevice = name;
if (startDevice.empty()) {
startDevice = g_Config.sAudioDevice;
}
audioDev = 0;
if (!startDevice.empty()) {
audioDev = SDL_OpenAudioDevice(startDevice.c_str(), 0, &fmt, &g_retFmt, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);
if (audioDev <= 0) {
WARN_LOG(Log::Audio, "Failed to open audio device: %s", startDevice.c_str());
}
}
if (audioDev <= 0) {
INFO_LOG(Log::Audio, "SDL: Trying a different audio device");
audioDev = SDL_OpenAudioDevice(nullptr, 0, &fmt, &g_retFmt, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);
}
if (audioDev <= 0) {
ERROR_LOG(Log::Audio, "Failed to open audio device: %s", SDL_GetError());
} else {
if (g_retFmt.samples != fmt.samples) // Notify, but still use it
ERROR_LOG(Log::Audio, "Output audio samples: %d (requested: %d)", g_retFmt.samples, fmt.samples);
if (g_retFmt.format != fmt.format || g_retFmt.channels != fmt.channels) {
ERROR_LOG(Log::Audio, "Sound buffer format does not match requested format.");
ERROR_LOG(Log::Audio, "Output audio freq: %d (requested: %d)", g_retFmt.freq, fmt.freq);
ERROR_LOG(Log::Audio, "Output audio format: %d (requested: %d)", g_retFmt.format, fmt.format);
ERROR_LOG(Log::Audio, "Output audio channels: %d (requested: %d)", g_retFmt.channels, fmt.channels);
ERROR_LOG(Log::Audio, "Provided output format does not match requirement, turning audio off");
SDL_CloseAudioDevice(audioDev);
}
SDL_PauseAudioDevice(audioDev, 0);
}
}
static void StopSDLAudioDevice() {
if (audioDev > 0) {
SDL_PauseAudioDevice(audioDev, 1);
SDL_CloseAudioDevice(audioDev);
}
}
static void UpdateScreenDPI(SDL_Window *window) {
int drawable_width, window_width;
SDL_GetWindowSize(window, &window_width, NULL);
if (g_Config.iGPUBackend == (int)GPUBackend::OPENGL)
SDL_GL_GetDrawableSize(window, &drawable_width, NULL);
else if (g_Config.iGPUBackend == (int)GPUBackend::VULKAN)
SDL_Vulkan_GetDrawableSize(window, &drawable_width, NULL);
else {
// If we add SDL support for more platforms, we'll end up here.
g_DesktopDPI = 1.0f;
return;
}
// Round up a little otherwise there would be a gap sometimes
// in fractional scaling
g_DesktopDPI = ((float) drawable_width + 1.0f) / window_width;
// Temporary hack
#if PPSSPP_PLATFORM(MAC) || PPSSPP_PLATFORM(IOS)
if (g_Config.iGPUBackend == (int)GPUBackend::VULKAN) {
g_DesktopDPI = 1.0f;
}
#endif
}
// Simple implementations of System functions
void System_Toast(std::string_view text) {
#ifdef _WIN32
std::wstring str = ConvertUTF8ToWString(text);
MessageBox(0, str.c_str(), L"Toast!", MB_ICONINFORMATION);
#else
printf("%*.s", (int)text.length(), text.data());
#endif
}
void System_ShowKeyboard() {
// Irrelevant on PC
}
void System_Vibrate(int length_ms) {
// Ignore on PC
}
bool System_MakeRequest(SystemRequestType type, int requestId, const std::string ¶m1, const std::string ¶m2, int64_t param3, int64_t param4) {
switch (type) {
case SystemRequestType::RESTART_APP:
g_RestartRequested = true;
// TODO: Also save param1 and then split it into an argv.
return true;
case SystemRequestType::EXIT_APP:
// Do a clean exit
g_QuitRequested = true;
return true;
#if PPSSPP_PLATFORM(SWITCH)
case SystemRequestType::INPUT_TEXT_MODAL:
{
// swkbd only works on "real" titles
if (__nx_applet_type != AppletType_Application && __nx_applet_type != AppletType_SystemApplication) {
g_requestManager.PostSystemFailure(requestId);
return true;
}
SwkbdConfig kbd;
Result rc = swkbdCreate(&kbd, 0);
if (R_SUCCEEDED(rc)) {
char buf[LIBNX_SWKBD_LIMIT] = {'\0'};
swkbdConfigMakePresetDefault(&kbd);
swkbdConfigSetHeaderText(&kbd, param1.c_str());
swkbdConfigSetInitialText(&kbd, param2.c_str());
rc = swkbdShow(&kbd, buf, sizeof(buf));
swkbdClose(&kbd);
g_requestManager.PostSystemSuccess(requestId, buf);
return true;
}
g_requestManager.PostSystemFailure(requestId);
return true;
}
#endif // PPSSPP_PLATFORM(SWITCH)
#if PPSSPP_PLATFORM(MAC) || PPSSPP_PLATFORM(IOS)
case SystemRequestType::BROWSE_FOR_FILE:
{
DarwinDirectoryPanelCallback callback = [requestId] (bool success, Path path) {
if (success) {
g_requestManager.PostSystemSuccess(requestId, path.c_str());
} else {
g_requestManager.PostSystemFailure(requestId);
}
};
BrowseFileType fileType = (BrowseFileType)param3;
DarwinFileSystemServices::presentDirectoryPanel(callback, /* allowFiles = */ true, /* allowDirectories = */ false, fileType);
return true;
}
case SystemRequestType::BROWSE_FOR_FOLDER:
{
DarwinDirectoryPanelCallback callback = [requestId] (bool success, Path path) {
if (success) {
g_requestManager.PostSystemSuccess(requestId, path.c_str());
} else {
g_requestManager.PostSystemFailure(requestId);
}
};
DarwinFileSystemServices::presentDirectoryPanel(callback, /* allowFiles = */ false, /* allowDirectories = */ true);
return true;
}
#endif
case SystemRequestType::TOGGLE_FULLSCREEN_STATE:
{
std::lock_guard<std::mutex> guard(g_mutexWindow);
g_windowState.update = true;
g_windowState.toggleFullScreenNextFrame = true;
if (param1 == "1") {
g_windowState.toggleFullScreenType = 1;
} else if (param1 == "0") {
g_windowState.toggleFullScreenType = 0;
} else {
// Just toggle.
g_windowState.toggleFullScreenType = -1;
}
return true;
}
case SystemRequestType::SET_WINDOW_TITLE:
{
std::lock_guard<std::mutex> guard(g_mutexWindow);
const char *app_name = System_GetPropertyBool(SYSPROP_APP_GOLD) ? "PPSSPP Gold" : "PPSSPP";
g_windowState.title = param1.empty() ? app_name : param1;
g_windowState.update = true;
return true;
}
case SystemRequestType::COPY_TO_CLIPBOARD:
{
std::lock_guard<std::mutex> guard(g_mutexWindow);
g_windowState.clipboardString = param1;
g_windowState.clipboardDataAvailable = true;
g_windowState.update = true;
return true;
}
case SystemRequestType::SHOW_FILE_IN_FOLDER:
{
#if PPSSPP_PLATFORM(WINDOWS)
SFGAOF flags;
PIDLIST_ABSOLUTE pidl = nullptr;
HRESULT hr = SHParseDisplayName(ConvertUTF8ToWString(ReplaceAll(path, "/", "\\")).c_str(), nullptr, &pidl, 0, &flags);
if (pidl) {
if (SUCCEEDED(hr))
SHOpenFolderAndSelectItems(pidl, 0, NULL, 0);
CoTaskMemFree(pidl);
}
#elif PPSSPP_PLATFORM(MAC)
OSXShowInFinder(param1.c_str());
#elif (PPSSPP_PLATFORM(LINUX) && !PPSSPP_PLATFORM(ANDROID))
pid_t pid = fork();
if (pid < 0)
return true;
if (pid == 0) {
execlp("xdg-open", "xdg-open", param1.c_str(), nullptr);
exit(1);
}
#endif /* PPSSPP_PLATFORM(WINDOWS) */
return true;
}
case SystemRequestType::NOTIFY_UI_EVENT:
{
switch ((UIEventNotification)param3) {
case UIEventNotification::TEXT_GOTFOCUS:
g_textFocus = true;
g_textFocusChanged = true;
break;
case UIEventNotification::POPUP_CLOSED:
case UIEventNotification::TEXT_LOSTFOCUS:
g_textFocus = false;
g_textFocusChanged = true;
break;
default:
break;
}
return true;
}
default:
return false;
}
}
void System_AskForPermission(SystemPermission permission) {}
PermissionStatus System_GetPermissionStatus(SystemPermission permission) { return PERMISSION_STATUS_GRANTED; }
void System_LaunchUrl(LaunchUrlType urlType, const char *url) {
switch (urlType) {
case LaunchUrlType::BROWSER_URL:
case LaunchUrlType::MARKET_URL:
{
#if PPSSPP_PLATFORM(SWITCH)
Uuid uuid = { 0 };
WebWifiConfig conf;
webWifiCreate(&conf, NULL, url, uuid, 0);
webWifiShow(&conf, NULL);
#elif defined(MOBILE_DEVICE)
INFO_LOG(Log::System, "Would have gone to %s but LaunchBrowser is not implemented on this platform", url);
#elif defined(_WIN32)
std::wstring wurl = ConvertUTF8ToWString(url);
ShellExecute(NULL, L"open", wurl.c_str(), NULL, NULL, SW_SHOWNORMAL);
#elif defined(__APPLE__)
OSXOpenURL(url);
#else
std::string command = std::string("xdg-open ") + url;
int err = system(command.c_str());
if (err) {
INFO_LOG(Log::System, "Would have gone to %s but xdg-utils seems not to be installed", url);
}
#endif
break;
}
case LaunchUrlType::EMAIL_ADDRESS:
{
#if defined(MOBILE_DEVICE)
INFO_LOG(Log::System, "Would have opened your email client for %s but LaunchEmail is not implemented on this platform", url);
#elif defined(_WIN32)
std::wstring mailto = std::wstring(L"mailto:") + ConvertUTF8ToWString(url);
ShellExecute(NULL, L"open", mailto.c_str(), NULL, NULL, SW_SHOWNORMAL);
#elif defined(__APPLE__)
std::string mailToURL = std::string("mailto:") + url;
OSXOpenURL(mailToURL.c_str());
#else
std::string command = std::string("xdg-email ") + url;
int err = system(command.c_str());
if (err) {
INFO_LOG(Log::System, "Would have gone to %s but xdg-utils seems not to be installed", url);
}
#endif
break;
}
}
}
std::string System_GetProperty(SystemProperty prop) {
switch (prop) {
case SYSPROP_NAME:
#ifdef _WIN32
return "SDL:Windows";
#elif __linux__
return "SDL:Linux";
#elif __APPLE__
return "SDL:macOS";
#elif PPSSPP_PLATFORM(SWITCH)
return "SDL:Horizon";
#else
return "SDL:";
#endif
case SYSPROP_LANGREGION: {
// Get user-preferred locale from OS
setlocale(LC_ALL, "");
std::string locale(setlocale(LC_ALL, NULL));
// Set c and c++ strings back to POSIX
std::locale::global(std::locale("POSIX"));
if (!locale.empty()) {
// Technically, this is an opaque string, but try to find the locale code.
size_t messagesPos = locale.find("LC_MESSAGES=");
if (messagesPos != std::string::npos) {
messagesPos += strlen("LC_MESSAGES=");
size_t semi = locale.find(';', messagesPos);
locale = locale.substr(messagesPos, semi - messagesPos);
}
if (locale.find("_", 0) != std::string::npos) {
if (locale.find(".", 0) != std::string::npos) {
return locale.substr(0, locale.find(".",0));
}
return locale;
}
}
return "en_US";
}
case SYSPROP_CLIPBOARD_TEXT:
return SDL_HasClipboardText() ? SDL_GetClipboardText() : "";
case SYSPROP_AUDIO_DEVICE_LIST:
{
std::string result;
for (int i = 0; i < SDL_GetNumAudioDevices(0); ++i) {
const char *name = SDL_GetAudioDeviceName(i, 0);
if (!name) {
continue;
}
if (i == 0) {
result = name;
} else {
result.append(1, '\0');
result.append(name);
}
}
return result;
}
case SYSPROP_BUILD_VERSION:
return PPSSPP_GIT_VERSION;
case SYSPROP_USER_DOCUMENTS_DIR:
{
const char *home = getenv("HOME");
return home ? std::string(home) : "/";
}
default:
return "";
}
}
std::vector<std::string> System_GetPropertyStringVec(SystemProperty prop) {
std::vector<std::string> result;
switch (prop) {
case SYSPROP_TEMP_DIRS:
if (getenv("TMPDIR") && strlen(getenv("TMPDIR")) != 0)
result.push_back(getenv("TMPDIR"));
if (getenv("TMP") && strlen(getenv("TMP")) != 0)
result.push_back(getenv("TMP"));
if (getenv("TEMP") && strlen(getenv("TEMP")) != 0)
result.push_back(getenv("TEMP"));
return result;
default:
return result;
}
}
int64_t System_GetPropertyInt(SystemProperty prop) {
switch (prop) {
case SYSPROP_AUDIO_SAMPLE_RATE:
return g_retFmt.freq;
case SYSPROP_AUDIO_FRAMES_PER_BUFFER:
return g_retFmt.samples;
case SYSPROP_DEVICE_TYPE:
#if defined(MOBILE_DEVICE)
return DEVICE_TYPE_MOBILE;
#else
return DEVICE_TYPE_DESKTOP;
#endif
case SYSPROP_DISPLAY_COUNT:
return SDL_GetNumVideoDisplays();
case SYSPROP_KEYBOARD_LAYOUT:
{
char q, w, y;
q = SDL_GetKeyFromScancode(SDL_SCANCODE_Q);
w = SDL_GetKeyFromScancode(SDL_SCANCODE_W);
y = SDL_GetKeyFromScancode(SDL_SCANCODE_Y);
if (q == 'a' && w == 'z' && y == 'y')
return KEYBOARD_LAYOUT_AZERTY;
else if (q == 'q' && w == 'w' && y == 'z')
return KEYBOARD_LAYOUT_QWERTZ;
return KEYBOARD_LAYOUT_QWERTY;
}
case SYSPROP_DISPLAY_XRES:
return g_DesktopWidth;
case SYSPROP_DISPLAY_YRES:
return g_DesktopHeight;
default:
return -1;
}
}
float System_GetPropertyFloat(SystemProperty prop) {
switch (prop) {
case SYSPROP_DISPLAY_REFRESH_RATE:
return g_RefreshRate;
case SYSPROP_DISPLAY_DPI:
return (g_ForcedDPI == 0.0f ? g_DesktopDPI : g_ForcedDPI) * 96.0;
case SYSPROP_DISPLAY_SAFE_INSET_LEFT:
case SYSPROP_DISPLAY_SAFE_INSET_RIGHT:
case SYSPROP_DISPLAY_SAFE_INSET_TOP:
case SYSPROP_DISPLAY_SAFE_INSET_BOTTOM:
return 0.0f;
default:
return -1;
}
}
bool System_GetPropertyBool(SystemProperty prop) {
switch (prop) {
case SYSPROP_HAS_TEXT_CLIPBOARD:
case SYSPROP_CAN_SHOW_FILE:
#if PPSSPP_PLATFORM(WINDOWS) || PPSSPP_PLATFORM(MAC) || (PPSSPP_PLATFORM(LINUX) && !PPSSPP_PLATFORM(ANDROID))
return true;
#else
return false;
#endif
case SYSPROP_HAS_OPEN_DIRECTORY:
#if PPSSPP_PLATFORM(WINDOWS)
return true;
#elif PPSSPP_PLATFORM(MAC) || (PPSSPP_PLATFORM(LINUX) && !PPSSPP_PLATFORM(ANDROID))
return true;
#endif
case SYSPROP_HAS_BACK_BUTTON:
return true;
#if PPSSPP_PLATFORM(SWITCH)
case SYSPROP_HAS_TEXT_INPUT_DIALOG:
return __nx_applet_type == AppletType_Application || __nx_applet_type != AppletType_SystemApplication;
#endif
case SYSPROP_HAS_KEYBOARD:
return true;
case SYSPROP_APP_GOLD:
#ifdef GOLD
return true;
#else
return false;
#endif
case SYSPROP_CAN_JIT:
return true;
case SYSPROP_SUPPORTS_OPEN_FILE_IN_EDITOR:
return true; // FileUtil.cpp: OpenFileInEditor
#ifndef HTTPS_NOT_AVAILABLE
case SYSPROP_SUPPORTS_HTTPS:
return !g_Config.bDisableHTTPS;
#endif
#if PPSSPP_PLATFORM(MAC)
case SYSPROP_HAS_FOLDER_BROWSER:
case SYSPROP_HAS_FILE_BROWSER:
return true;
#endif
case SYSPROP_HAS_ACCELEROMETER:
#if defined(MOBILE_DEVICE)
return true;
#else
return false;
#endif
default:
return false;
}
}
void System_Notify(SystemNotification notification) {
switch (notification) {
case SystemNotification::AUDIO_RESET_DEVICE:
StopSDLAudioDevice();
InitSDLAudioDevice();
break;
default:
break;
}
}
// returns -1 on failure
static int parseInt(const char *str) {
int val;
int retval = sscanf(str, "%d", &val);
printf("%i = scanf %s\n", retval, str);
if (retval != 1) {
return -1;
} else {
return val;
}
}
static float parseFloat(const char *str) {
float val;
int retval = sscanf(str, "%f", &val);
printf("%i = sscanf %s\n", retval, str);
if (retval != 1) {
return -1.0f;
} else {
return val;
}
}
void UpdateWindowState(SDL_Window *window) {
SDL_SetWindowTitle(window, g_windowState.title.c_str());
if (g_windowState.toggleFullScreenNextFrame) {
g_windowState.toggleFullScreenNextFrame = false;
Uint32 window_flags = SDL_GetWindowFlags(window);
if (g_windowState.toggleFullScreenType == -1) {
window_flags ^= SDL_WINDOW_FULLSCREEN_DESKTOP;
} else if (g_windowState.toggleFullScreenType == 1) {
window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
} else {
window_flags &= ~SDL_WINDOW_FULLSCREEN_DESKTOP;
}
SDL_SetWindowFullscreen(window, window_flags);
}
if (g_windowState.clipboardDataAvailable) {
SDL_SetClipboardText(g_windowState.clipboardString.c_str());
g_windowState.clipboardDataAvailable = false;
g_windowState.clipboardString.clear();
}
g_windowState.update = false;
}
enum class EmuThreadState {
DISABLED,
START_REQUESTED,
RUNNING,
QUIT_REQUESTED,
STOPPED,
};
static std::thread emuThread;
static std::atomic<int> emuThreadState((int)EmuThreadState::DISABLED);
static void EmuThreadFunc(GraphicsContext *graphicsContext) {
SetCurrentThreadName("EmuThread");
// There's no real requirement that NativeInit happen on this thread.
// We just call the update/render loop here.
emuThreadState = (int)EmuThreadState::RUNNING;
NativeInitGraphics(graphicsContext);
while (emuThreadState != (int)EmuThreadState::QUIT_REQUESTED) {
NativeFrame(graphicsContext);
}
emuThreadState = (int)EmuThreadState::STOPPED;
graphicsContext->StopThread();
NativeShutdownGraphics();
}
static void EmuThreadStart(GraphicsContext *context) {
emuThreadState = (int)EmuThreadState::START_REQUESTED;
emuThread = std::thread(&EmuThreadFunc, context);
}
static void EmuThreadStop(const char *reason) {
emuThreadState = (int)EmuThreadState::QUIT_REQUESTED;
}
static void EmuThreadJoin() {
emuThread.join();
emuThread = std::thread();
}
struct InputStateTracker {
void MouseCaptureControl() {
bool captureMouseCondition = g_Config.bMouseControl && ((GetUIState() == UISTATE_INGAME && g_Config.bMouseConfine) || g_Config.bMapMouse);
if (mouseCaptured != captureMouseCondition) {
mouseCaptured = captureMouseCondition;
if (captureMouseCondition)
SDL_SetRelativeMouseMode(SDL_TRUE);
else
SDL_SetRelativeMouseMode(SDL_FALSE);
}
}
int mouseDown; // bitflags
bool mouseCaptured;
};
static void ProcessSDLEvent(SDL_Window *window, const SDL_Event &event, InputStateTracker *inputTracker) {
// We have to juggle around 3 kinds of "DPI spaces" if a logical DPI is
// provided (through --dpi, it is equal to system DPI if unspecified):
// - SDL gives us motion events in "system DPI" points
// - Native_UpdateScreenScale expects pixels, so in a way "96 DPI" points
// - The UI code expects motion events in "logical DPI" points
float mx = event.motion.x * g_DesktopDPI * g_display.dpi_scale_x;
float my = event.motion.y * g_DesktopDPI * g_display.dpi_scale_x;
switch (event.type) {
case SDL_QUIT:
g_QuitRequested = 1;
break;
#if !defined(MOBILE_DEVICE)
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_SIZE_CHANGED: // better than RESIZED, more general
{
int new_width = event.window.data1;
int new_height = event.window.data2;
// The size given by SDL is in point-units, convert these to
// pixels before passing to Native_UpdateScreenScale()
int new_width_px = new_width * g_DesktopDPI;
int new_height_px = new_height * g_DesktopDPI;
Native_NotifyWindowHidden(false);
Uint32 window_flags = SDL_GetWindowFlags(window);
bool fullscreen = (window_flags & SDL_WINDOW_FULLSCREEN);
// This one calls NativeResized if the size changed.
Native_UpdateScreenScale(new_width_px, new_height_px);
// Set variable here in case fullscreen was toggled by hotkey
if (g_Config.UseFullScreen() != fullscreen) {
g_Config.bFullScreen = fullscreen;
g_Config.iForceFullScreen = -1;
} else {
// It is possible for the monitor to change DPI, so recalculate
// DPI on each resize event.
UpdateScreenDPI(window);
}
if (!g_Config.bFullScreen) {
g_Config.iWindowWidth = new_width;
g_Config.iWindowHeight = new_height;
}
// Hide/Show cursor correctly toggling fullscreen
if (lastUIState == UISTATE_INGAME && fullscreen && !g_Config.bShowTouchControls) {
SDL_ShowCursor(SDL_DISABLE);
} else if (lastUIState != UISTATE_INGAME || !fullscreen) {
SDL_ShowCursor(SDL_ENABLE);
}
break;
}
case SDL_WINDOWEVENT_MOVED:
{
Uint32 window_flags = SDL_GetWindowFlags(window);
bool fullscreen = (window_flags & SDL_WINDOW_FULLSCREEN);
if (!fullscreen) {
g_Config.iWindowX = (int)event.window.data1;
g_Config.iWindowY = (int)event.window.data2;
}
break;
}
case SDL_WINDOWEVENT_MINIMIZED:
case SDL_WINDOWEVENT_HIDDEN:
Native_NotifyWindowHidden(true);
break;
case SDL_WINDOWEVENT_EXPOSED:
case SDL_WINDOWEVENT_SHOWN:
Native_NotifyWindowHidden(false);
break;
default:
break;
}
break;
#endif
case SDL_KEYDOWN:
{
if (event.key.repeat > 0) { break;}
int k = event.key.keysym.sym;
KeyInput key;
key.flags = KEY_DOWN;
auto mapped = KeyMapRawSDLtoNative.find(k);
if (mapped == KeyMapRawSDLtoNative.end() || mapped->second == NKCODE_UNKNOWN) {
break;
}
key.keyCode = mapped->second;
key.deviceId = DEVICE_ID_KEYBOARD;
NativeKey(key);
#ifdef _DEBUG
if (k == SDLK_F7) {
printf("f7 pressed - rebooting emuthread\n");
g_rebootEmuThread = true;
}
#endif
// Convenience subset of what
// "Enable standard shortcut keys"
// does on Windows.
if(g_Config.bSystemControls) {
bool ctrl = bool(event.key.keysym.mod & KMOD_CTRL);
if (ctrl && (k == SDLK_w))
{
if (Core_IsStepping())
Core_Resume();
Core_Stop();
System_PostUIMessage(UIMessage::REQUEST_GAME_STOP);
// NOTE: Unlike Windows version, this
// does not need Core_WaitInactive();
// since SDL does not have a separate
// UI thread.
}
if (ctrl && (k == SDLK_b))
{
System_PostUIMessage(UIMessage::REQUEST_GAME_RESET);
Core_Resume();
}
}
break;
}
case SDL_KEYUP:
{
if (event.key.repeat > 0) { break;}
int k = event.key.keysym.sym;
KeyInput key;
key.flags = KEY_UP;
auto mapped = KeyMapRawSDLtoNative.find(k);
if (mapped == KeyMapRawSDLtoNative.end() || mapped->second == NKCODE_UNKNOWN) {
break;
}
key.keyCode = mapped->second;
key.deviceId = DEVICE_ID_KEYBOARD;
NativeKey(key);
break;
}
case SDL_TEXTINPUT:
{
int pos = 0;
int c = u8_nextchar(event.text.text, &pos, strlen(event.text.text));
KeyInput key;
key.flags = KEY_CHAR;
key.unicodeChar = c;
key.deviceId = DEVICE_ID_KEYBOARD;
NativeKey(key);
break;
}
// This behavior doesn't feel right on a macbook with a touchpad.
#if !PPSSPP_PLATFORM(MAC)
case SDL_FINGERMOTION:
{
int w, h;
SDL_GetWindowSize(window, &w, &h);
TouchInput input;
input.id = event.tfinger.fingerId;
input.x = event.tfinger.x * w * g_DesktopDPI * g_display.dpi_scale_x;
input.y = event.tfinger.y * h * g_DesktopDPI * g_display.dpi_scale_x;
input.flags = TOUCH_MOVE;
input.timestamp = event.tfinger.timestamp;
NativeTouch(input);
break;
}
case SDL_FINGERDOWN:
{
int w, h;
SDL_GetWindowSize(window, &w, &h);
TouchInput input;
input.id = event.tfinger.fingerId;
input.x = event.tfinger.x * w * g_DesktopDPI * g_display.dpi_scale_x;
input.y = event.tfinger.y * h * g_DesktopDPI * g_display.dpi_scale_x;
input.flags = TOUCH_DOWN;
input.timestamp = event.tfinger.timestamp;
NativeTouch(input);
KeyInput key;
key.deviceId = DEVICE_ID_MOUSE;
key.keyCode = NKCODE_EXT_MOUSEBUTTON_1;
key.flags = KEY_DOWN;
NativeKey(key);
break;
}
case SDL_FINGERUP:
{
int w, h;
SDL_GetWindowSize(window, &w, &h);
TouchInput input;
input.id = event.tfinger.fingerId;
input.x = event.tfinger.x * w * g_DesktopDPI * g_display.dpi_scale_x;
input.y = event.tfinger.y * h * g_DesktopDPI * g_display.dpi_scale_x;
input.flags = TOUCH_UP;
input.timestamp = event.tfinger.timestamp;
NativeTouch(input);
KeyInput key;
key.deviceId = DEVICE_ID_MOUSE;
key.keyCode = NKCODE_EXT_MOUSEBUTTON_1;
key.flags = KEY_UP;
NativeKey(key);
break;
}
#endif
case SDL_MOUSEBUTTONDOWN:
switch (event.button.button) {
case SDL_BUTTON_LEFT:
{
inputTracker->mouseDown |= 1;
TouchInput input{};
input.x = mx;
input.y = my;
input.flags = TOUCH_DOWN | TOUCH_MOUSE;
input.buttons = 1;
input.id = 0;
NativeTouch(input);
KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_1, KEY_DOWN);
NativeKey(key);
}
break;
case SDL_BUTTON_RIGHT:
{
inputTracker->mouseDown |= 2;
TouchInput input{};
input.x = mx;
input.y = my;
input.flags = TOUCH_DOWN | TOUCH_MOUSE;
input.buttons = 2;
input.id = 0;
NativeTouch(input);
KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, KEY_DOWN);
NativeKey(key);
}
break;
case SDL_BUTTON_MIDDLE:
{
KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_3, KEY_DOWN);
NativeKey(key);
}
break;
case SDL_BUTTON_X1:
{
KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_4, KEY_DOWN);
NativeKey(key);
}
break;
case SDL_BUTTON_X2:
{
KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_5, KEY_DOWN);
NativeKey(key);
}
break;
}
break;
case SDL_MOUSEWHEEL:
{
KeyInput key;
key.deviceId = DEVICE_ID_MOUSE;
key.flags = KEY_DOWN;
#if SDL_VERSION_ATLEAST(2, 0, 18)
if (event.wheel.preciseY != 0.0f) {
// Should the scale be DPI-driven?