Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Qt/QtMain.cpp
3185 views
1
/*
2
* Copyright (c) 2012 Sacha Refshauge
3
*
4
*/
5
// Qt 4.7+ / 5.0+ implementation of the framework.
6
// Currently supports: Android, Linux, Windows, Mac OSX
7
8
#include "ppsspp_config.h"
9
#include <QApplication>
10
#include <QClipboard>
11
#include <QDesktopWidget>
12
#include <QDesktopServices>
13
#include <QDir>
14
#include <QFile>
15
#include <QFileDialog>
16
#include <QLocale>
17
#include <QScreen>
18
#include <QThread>
19
#include <QUrl>
20
21
#include "ext/glslang/glslang/Public/ShaderLang.h"
22
23
#if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
24
#include <QStandardPaths>
25
#ifdef QT_HAS_SYSTEMINFO
26
#include <QScreenSaver>
27
#endif
28
#endif
29
30
#ifdef SDL
31
#include "SDL/SDLJoystick.h"
32
#include "SDL_audio.h"
33
#include "SDL_keyboard.h"
34
#endif
35
36
#include "Common/Audio/AudioBackend.h"
37
#include "Common/System/NativeApp.h"
38
#include "Common/System/Request.h"
39
#include "Common/GPU/OpenGL/GLFeatures.h"
40
#include "Common/Math/math_util.h"
41
#include "Common/Profiler/Profiler.h"
42
43
#include "QtMain.h"
44
#include "Qt/mainwindow.h"
45
#include "Common/Data/Text/I18n.h"
46
#include "Common/Thread/ThreadUtil.h"
47
#include "Common/Data/Encoding/Utf8.h"
48
#include "Common/StringUtils.h"
49
#include "Common/TimeUtil.h"
50
#include "Common/Log/LogManager.h"
51
52
#include "Core/Config.h"
53
#include "Core/ConfigValues.h"
54
#include "Core/HW/Camera.h"
55
#include "Core/Debugger/SymbolMap.h"
56
57
#include <signal.h>
58
#include <string.h>
59
60
// AUDIO
61
#define AUDIO_FREQ 44100
62
#define AUDIO_CHANNELS 2
63
#define AUDIO_SAMPLES 2048
64
#define AUDIO_SAMPLESIZE 16
65
#define AUDIO_BUFFERS 5
66
67
MainUI *emugl = nullptr;
68
static float refreshRate = 60.f;
69
static int browseFileEvent = -1;
70
static int browseFolderEvent = -1;
71
static int inputBoxEvent = -1;
72
73
QTCamera *qtcamera = nullptr;
74
MainWindow *g_mainWindow;
75
76
#ifdef SDL
77
SDL_AudioSpec g_retFmt;
78
79
static SDL_AudioDeviceID audioDev = 0;
80
81
extern void mixaudio(void *userdata, Uint8 *stream, int len) {
82
NativeMix((short *)stream, len / 4, AUDIO_FREQ, userdata);
83
}
84
85
static void InitSDLAudioDevice() {
86
SDL_AudioSpec fmt;
87
memset(&fmt, 0, sizeof(fmt));
88
fmt.freq = 44100;
89
fmt.format = AUDIO_S16;
90
fmt.channels = 2;
91
fmt.samples = std::max(g_Config.iSDLAudioBufferSize, 128);
92
fmt.callback = &mixaudio;
93
fmt.userdata = nullptr;
94
95
audioDev = 0;
96
if (!g_Config.sAudioDevice.empty()) {
97
audioDev = SDL_OpenAudioDevice(g_Config.sAudioDevice.c_str(), 0, &fmt, &g_retFmt, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);
98
if (audioDev <= 0) {
99
WARN_LOG(Log::Audio, "Failed to open preferred audio device %s", g_Config.sAudioDevice.c_str());
100
}
101
}
102
if (audioDev <= 0) {
103
audioDev = SDL_OpenAudioDevice(nullptr, 0, &fmt, &g_retFmt, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);
104
}
105
if (audioDev <= 0) {
106
ERROR_LOG(Log::Audio, "Failed to open audio: %s", SDL_GetError());
107
} else {
108
if (g_retFmt.samples != fmt.samples) // Notify, but still use it
109
ERROR_LOG(Log::Audio, "Output audio samples: %d (requested: %d)", g_retFmt.samples, fmt.samples);
110
if (g_retFmt.format != fmt.format || g_retFmt.channels != fmt.channels) {
111
ERROR_LOG(Log::Audio, "Sound buffer format does not match requested format.");
112
ERROR_LOG(Log::Audio, "Output audio freq: %d (requested: %d)", g_retFmt.freq, fmt.freq);
113
ERROR_LOG(Log::Audio, "Output audio format: %d (requested: %d)", g_retFmt.format, fmt.format);
114
ERROR_LOG(Log::Audio, "Output audio channels: %d (requested: %d)", g_retFmt.channels, fmt.channels);
115
ERROR_LOG(Log::Audio, "Provided output format does not match requirement, turning audio off");
116
SDL_CloseAudioDevice(audioDev);
117
}
118
SDL_PauseAudioDevice(audioDev, 0);
119
}
120
}
121
122
static void StopSDLAudioDevice() {
123
if (audioDev > 0) {
124
SDL_PauseAudioDevice(audioDev, 1);
125
SDL_CloseAudioDevice(audioDev);
126
}
127
}
128
#endif
129
130
std::string System_GetProperty(SystemProperty prop) {
131
switch (prop) {
132
case SYSPROP_NAME:
133
#if defined(__ANDROID__)
134
return "Qt:Android";
135
#elif defined(Q_OS_LINUX)
136
return "Qt:Linux";
137
#elif defined(_WIN32)
138
return "Qt:Windows";
139
#elif defined(Q_OS_MAC)
140
return "Qt:macOS";
141
#else
142
return "Qt";
143
#endif
144
case SYSPROP_LANGREGION:
145
return QLocale::system().name().toStdString();
146
case SYSPROP_CLIPBOARD_TEXT:
147
return QApplication::clipboard()->text().toStdString();
148
#if defined(SDL)
149
case SYSPROP_AUDIO_DEVICE_LIST:
150
{
151
std::string result;
152
for (int i = 0; i < SDL_GetNumAudioDevices(0); ++i) {
153
const char *name = SDL_GetAudioDeviceName(i, 0);
154
if (!name) {
155
continue;
156
}
157
158
if (i == 0) {
159
result = name;
160
} else {
161
result.append(1, '\0');
162
result.append(name);
163
}
164
}
165
return result;
166
}
167
#endif
168
case SYSPROP_BUILD_VERSION:
169
return PPSSPP_GIT_VERSION;
170
default:
171
return "";
172
}
173
}
174
175
std::vector<std::string> System_GetPropertyStringVec(SystemProperty prop) {
176
std::vector<std::string> result;
177
switch (prop) {
178
case SYSPROP_TEMP_DIRS:
179
if (getenv("TMPDIR") && strlen(getenv("TMPDIR")) != 0)
180
result.push_back(getenv("TMPDIR"));
181
if (getenv("TMP") && strlen(getenv("TMP")) != 0)
182
result.push_back(getenv("TMP"));
183
if (getenv("TEMP") && strlen(getenv("TEMP")) != 0)
184
result.push_back(getenv("TEMP"));
185
return result;
186
187
default:
188
return result;
189
}
190
}
191
192
int64_t System_GetPropertyInt(SystemProperty prop) {
193
switch (prop) {
194
#if defined(SDL)
195
case SYSPROP_AUDIO_SAMPLE_RATE:
196
return g_retFmt.freq;
197
case SYSPROP_AUDIO_FRAMES_PER_BUFFER:
198
return g_retFmt.samples;
199
case SYSPROP_KEYBOARD_LAYOUT:
200
{
201
// TODO: Use Qt APIs for detecting this
202
char q, w, y;
203
q = SDL_GetKeyFromScancode(SDL_SCANCODE_Q);
204
w = SDL_GetKeyFromScancode(SDL_SCANCODE_W);
205
y = SDL_GetKeyFromScancode(SDL_SCANCODE_Y);
206
if (q == 'a' && w == 'z' && y == 'y')
207
return KEYBOARD_LAYOUT_AZERTY;
208
else if (q == 'q' && w == 'w' && y == 'z')
209
return KEYBOARD_LAYOUT_QWERTZ;
210
return KEYBOARD_LAYOUT_QWERTY;
211
}
212
#endif
213
case SYSPROP_DEVICE_TYPE:
214
#if defined(__ANDROID__)
215
return DEVICE_TYPE_MOBILE;
216
#elif defined(Q_OS_LINUX)
217
return DEVICE_TYPE_DESKTOP;
218
#elif defined(_WIN32)
219
return DEVICE_TYPE_DESKTOP;
220
#elif defined(Q_OS_MAC)
221
return DEVICE_TYPE_DESKTOP;
222
#else
223
return DEVICE_TYPE_DESKTOP;
224
#endif
225
case SYSPROP_DISPLAY_COUNT:
226
return QApplication::screens().size();
227
default:
228
return -1;
229
}
230
}
231
232
float System_GetPropertyFloat(SystemProperty prop) {
233
switch (prop) {
234
case SYSPROP_DISPLAY_REFRESH_RATE:
235
return refreshRate;
236
case SYSPROP_DISPLAY_LOGICAL_DPI:
237
return QApplication::primaryScreen()->logicalDotsPerInch();
238
case SYSPROP_DISPLAY_DPI:
239
return QApplication::primaryScreen()->physicalDotsPerInch();
240
case SYSPROP_DISPLAY_SAFE_INSET_LEFT:
241
case SYSPROP_DISPLAY_SAFE_INSET_RIGHT:
242
case SYSPROP_DISPLAY_SAFE_INSET_TOP:
243
case SYSPROP_DISPLAY_SAFE_INSET_BOTTOM:
244
return 0.0f;
245
default:
246
return -1;
247
}
248
}
249
250
bool System_GetPropertyBool(SystemProperty prop) {
251
switch (prop) {
252
case SYSPROP_HAS_TEXT_CLIPBOARD:
253
return true;
254
case SYSPROP_HAS_BACK_BUTTON:
255
return true;
256
case SYSPROP_HAS_IMAGE_BROWSER:
257
case SYSPROP_HAS_FILE_BROWSER:
258
case SYSPROP_HAS_FOLDER_BROWSER:
259
case SYSPROP_HAS_OPEN_DIRECTORY:
260
case SYSPROP_HAS_TEXT_INPUT_DIALOG:
261
case SYSPROP_CAN_SHOW_FILE:
262
return true;
263
case SYSPROP_SUPPORTS_OPEN_FILE_IN_EDITOR:
264
return true; // FileUtil.cpp: OpenFileInEditor
265
case SYSPROP_APP_GOLD:
266
#ifdef GOLD
267
return true;
268
#else
269
return false;
270
#endif
271
case SYSPROP_CAN_JIT:
272
return true;
273
case SYSPROP_HAS_KEYBOARD:
274
return true;
275
default:
276
return false;
277
}
278
}
279
280
void System_Notify(SystemNotification notification) {
281
switch (notification) {
282
case SystemNotification::BOOT_DONE:
283
g_symbolMap->SortSymbols();
284
g_mainWindow->Notify(MainWindowMsg::BOOT_DONE);
285
break;
286
case SystemNotification::SYMBOL_MAP_UPDATED:
287
if (g_symbolMap)
288
g_symbolMap->SortSymbols();
289
break;
290
case SystemNotification::AUDIO_RESET_DEVICE:
291
#ifdef SDL
292
StopSDLAudioDevice();
293
InitSDLAudioDevice();
294
#endif
295
break;
296
default:
297
break;
298
}
299
}
300
301
// TODO: Find a better version to pass parameters to HandleCustomEvent.
302
static std::string g_param1;
303
static std::string g_param2;
304
static int g_param3;
305
static int g_requestId;
306
307
bool MainUI::HandleCustomEvent(QEvent *e) {
308
if (e->type() == browseFileEvent) {
309
BrowseFileType fileType = (BrowseFileType)g_param3;
310
const char *filter = "All files (*.*)";
311
switch (fileType) {
312
case BrowseFileType::BOOTABLE:
313
filter = "PSP ROMs (*.iso *.cso *.chd *.pbp *.elf *.zip *.ppdmp)";
314
break;
315
case BrowseFileType::IMAGE:
316
filter = "Pictures (*.jpg *.png)";
317
break;
318
case BrowseFileType::INI:
319
filter = "INI files (*.ini)";
320
break;
321
case BrowseFileType::DB:
322
filter = "DB files (*.db)";
323
break;
324
case BrowseFileType::SOUND_EFFECT:
325
filter = "WAVE files (*.wav *.mp3)";
326
break;
327
case BrowseFileType::ZIP:
328
filter = "ZIP files (*.zip)";
329
break;
330
case BrowseFileType::ATRAC3:
331
filter = "AT3 files (*.at3)";
332
break;
333
case BrowseFileType::ANY:
334
break;
335
}
336
337
QString fileName = QFileDialog::getOpenFileName(nullptr, g_param1.c_str(), g_Config.currentDirectory.c_str(), filter);
338
if (QFile::exists(fileName)) {
339
g_requestManager.PostSystemSuccess(g_requestId, fileName.toStdString().c_str());
340
} else {
341
g_requestManager.PostSystemFailure(g_requestId);
342
}
343
} else if (e->type() == browseFolderEvent) {
344
QString title = QString::fromStdString(g_param1);
345
QString fileName = QFileDialog::getExistingDirectory(nullptr, title, g_Config.currentDirectory.c_str());
346
if (QDir(fileName).exists()) {
347
g_requestManager.PostSystemSuccess(g_requestId, fileName.toStdString().c_str());
348
} else {
349
g_requestManager.PostSystemFailure(g_requestId);
350
}
351
} else if (e->type() == inputBoxEvent) {
352
QString title = QString::fromStdString(g_param1);
353
QString defaultValue = QString::fromStdString(g_param2);
354
QString text = emugl->InputBoxGetQString(title, defaultValue);
355
if (text.isEmpty()) {
356
g_requestManager.PostSystemFailure(g_requestId);
357
} else {
358
g_requestManager.PostSystemSuccess(g_requestId, text.toStdString().c_str());
359
}
360
} else {
361
return false;
362
}
363
return true;
364
}
365
366
bool System_MakeRequest(SystemRequestType type, int requestId, const std::string &param1, const std::string &param2, int64_t param3, int64_t param4) {
367
switch (type) {
368
case SystemRequestType::EXIT_APP:
369
qApp->exit(0);
370
return true;
371
case SystemRequestType::RESTART_APP:
372
// Should find a way to properly restart the app.
373
qApp->exit(0);
374
return true;
375
case SystemRequestType::COPY_TO_CLIPBOARD:
376
QApplication::clipboard()->setText(param1.c_str());
377
return true;
378
case SystemRequestType::SET_WINDOW_TITLE:
379
{
380
std::string title = std::string("PPSSPP ") + PPSSPP_GIT_VERSION;
381
if (!param1.empty())
382
title += std::string(" - ") + param1;
383
#ifdef _DEBUG
384
title += " (debug)";
385
#endif
386
g_mainWindow->SetWindowTitleAsync(title);
387
return true;
388
}
389
case SystemRequestType::INPUT_TEXT_MODAL:
390
{
391
g_requestId = requestId;
392
g_param1 = param1;
393
g_param2 = param2;
394
g_param3 = param3;
395
QCoreApplication::postEvent(emugl, new QEvent((QEvent::Type)inputBoxEvent));
396
return true;
397
}
398
case SystemRequestType::BROWSE_FOR_IMAGE:
399
// Fall back to file browser.
400
return System_MakeRequest(SystemRequestType::BROWSE_FOR_FILE, requestId, param1, param2, (int)BrowseFileType::IMAGE, 0);
401
case SystemRequestType::BROWSE_FOR_FILE:
402
g_requestId = requestId;
403
g_param1 = param1;
404
g_param2 = param2;
405
g_param3 = param3;
406
QCoreApplication::postEvent(emugl, new QEvent((QEvent::Type)browseFileEvent));
407
return true;
408
case SystemRequestType::BROWSE_FOR_FOLDER:
409
g_requestId = requestId;
410
g_param1 = param1;
411
g_param2 = param2;
412
QCoreApplication::postEvent(emugl, new QEvent((QEvent::Type)browseFolderEvent));
413
return true;
414
case SystemRequestType::CAMERA_COMMAND:
415
if (!strncmp(param1.c_str(), "startVideo", 10)) {
416
int width = 0, height = 0;
417
sscanf(param1.c_str(), "startVideo_%dx%d", &width, &height);
418
emit(qtcamera->onStartCamera(width, height));
419
} else if (param1 == "stopVideo") {
420
emit(qtcamera->onStopCamera());
421
}
422
return true;
423
case SystemRequestType::SHOW_FILE_IN_FOLDER:
424
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromUtf8(param1.c_str())));
425
return true;
426
default:
427
return false;
428
}
429
}
430
431
void System_Toast(std::string_view text) {}
432
433
void System_AskForPermission(SystemPermission permission) {}
434
PermissionStatus System_GetPermissionStatus(SystemPermission permission) { return PERMISSION_STATUS_GRANTED; }
435
436
void System_Vibrate(int length_ms) {
437
if (length_ms == -1 || length_ms == -3)
438
length_ms = 50;
439
else if (length_ms == -2)
440
length_ms = 25;
441
}
442
443
void System_LaunchUrl(LaunchUrlType urlType, const char *url)
444
{
445
QDesktopServices::openUrl(QUrl(url));
446
}
447
448
AudioBackend *System_CreateAudioBackend() {
449
// Use legacy mechanisms.
450
return nullptr;
451
}
452
453
static int mainInternal(QApplication &a) {
454
#ifdef MOBILE_DEVICE
455
emugl = new MainUI();
456
emugl->resize(g_display.pixel_xres, g_display.pixel_yres);
457
emugl->showFullScreen();
458
#endif
459
EnableFZ();
460
// Disable screensaver
461
#if defined(QT_HAS_SYSTEMINFO)
462
QScreenSaver ssObject(emugl);
463
ssObject.setScreenSaverEnabled(false);
464
#endif
465
466
#ifdef SDL
467
SDLJoystick joy(true);
468
joy.registerEventHandler();
469
SDL_Init(SDL_INIT_AUDIO);
470
InitSDLAudioDevice();
471
#else
472
QScopedPointer<MainAudio> audio(new MainAudio());
473
audio->run();
474
#endif
475
476
browseFileEvent = QEvent::registerEventType();
477
browseFolderEvent = QEvent::registerEventType();
478
inputBoxEvent = QEvent::registerEventType();
479
480
int retval = a.exec();
481
delete emugl;
482
return retval;
483
}
484
485
void MainUI::EmuThreadFunc() {
486
SetCurrentThreadName("EmuThread");
487
488
// There's no real requirement that NativeInit happen on this thread, though it can't hurt...
489
// We just call the update/render loop here. NativeInitGraphics should be here though.
490
NativeInitGraphics(graphicsContext);
491
492
emuThreadState = (int)EmuThreadState::RUNNING;
493
while (emuThreadState != (int)EmuThreadState::QUIT_REQUESTED) {
494
updateAccelerometer();
495
NativeFrame(graphicsContext);
496
}
497
emuThreadState = (int)EmuThreadState::STOPPED;
498
499
NativeShutdownGraphics();
500
graphicsContext->StopThread();
501
}
502
503
void MainUI::EmuThreadStart() {
504
emuThreadState = (int)EmuThreadState::START_REQUESTED;
505
emuThread = std::thread([&]() { this->EmuThreadFunc(); } );
506
}
507
508
void MainUI::EmuThreadStop() {
509
emuThreadState = (int)EmuThreadState::QUIT_REQUESTED;
510
}
511
512
void MainUI::EmuThreadJoin() {
513
emuThread.join();
514
emuThread = std::thread();
515
}
516
517
MainUI::MainUI(QWidget *parent)
518
: QGLWidget(parent) {
519
emuThreadState = (int)EmuThreadState::DISABLED;
520
setAttribute(Qt::WA_AcceptTouchEvents);
521
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
522
setAttribute(Qt::WA_LockLandscapeOrientation);
523
#endif
524
#if defined(MOBILE_DEVICE)
525
acc = new QAccelerometer(this);
526
acc->start();
527
#endif
528
setFocus();
529
setFocusPolicy(Qt::StrongFocus);
530
startTimer(16);
531
}
532
533
MainUI::~MainUI() {
534
INFO_LOG(Log::System, "MainUI::Destructor");
535
if (emuThreadState != (int)EmuThreadState::DISABLED) {
536
INFO_LOG(Log::System, "EmuThreadStop");
537
EmuThreadStop();
538
while (graphicsContext->ThreadFrame()) {
539
// Need to keep eating frames to allow the EmuThread to exit correctly.
540
continue;
541
}
542
EmuThreadJoin();
543
}
544
#if defined(MOBILE_DEVICE)
545
delete acc;
546
#endif
547
graphicsContext->Shutdown();
548
delete graphicsContext;
549
graphicsContext = nullptr;
550
}
551
552
QString MainUI::InputBoxGetQString(QString title, QString defaultValue) {
553
bool ok;
554
QString text = QInputDialog::getText(this, title, title, QLineEdit::Normal, defaultValue, &ok);
555
if (!ok)
556
text = QString();
557
return text;
558
}
559
560
void MainUI::resizeGL(int w, int h) {
561
if (Native_UpdateScreenScale(w, h, UIScaleFactorToMultiplier(g_Config.iUIScaleFactor))) {
562
System_PostUIMessage(UIMessage::GPU_RENDER_RESIZED);
563
}
564
xscale = w / this->width();
565
yscale = h / this->height();
566
567
PSP_CoreParameter().pixelWidth = g_display.pixel_xres;
568
PSP_CoreParameter().pixelHeight = g_display.pixel_yres;
569
}
570
571
void MainUI::timerEvent(QTimerEvent *) {
572
updateGL();
573
emit newFrame();
574
}
575
576
void MainUI::changeEvent(QEvent *e) {
577
QGLWidget::changeEvent(e);
578
if (e->type() == QEvent::WindowStateChange)
579
Native_NotifyWindowHidden(isMinimized());
580
}
581
582
bool MainUI::event(QEvent *e) {
583
TouchInput input;
584
QList<QTouchEvent::TouchPoint> touchPoints;
585
586
switch (e->type()) {
587
case QEvent::TouchBegin:
588
case QEvent::TouchUpdate:
589
case QEvent::TouchEnd:
590
touchPoints = static_cast<QTouchEvent *>(e)->touchPoints();
591
foreach (const QTouchEvent::TouchPoint &touchPoint, touchPoints) {
592
switch (touchPoint.state()) {
593
case Qt::TouchPointStationary:
594
break;
595
case Qt::TouchPointPressed:
596
case Qt::TouchPointReleased:
597
input.x = touchPoint.pos().x() * g_display.dpi_scale_x * xscale;
598
input.y = touchPoint.pos().y() * g_display.dpi_scale_y * yscale;
599
input.flags = (touchPoint.state() == Qt::TouchPointPressed) ? TOUCH_DOWN : TOUCH_UP;
600
input.id = touchPoint.id();
601
NativeTouch(input);
602
break;
603
case Qt::TouchPointMoved:
604
input.x = touchPoint.pos().x() * g_display.dpi_scale_x * xscale;
605
input.y = touchPoint.pos().y() * g_display.dpi_scale_y * yscale;
606
input.flags = TOUCH_MOVE;
607
input.id = touchPoint.id();
608
NativeTouch(input);
609
break;
610
default:
611
break;
612
}
613
}
614
break;
615
case QEvent::MouseButtonDblClick:
616
if (!g_Config.bShowTouchControls || GetUIState() != UISTATE_INGAME)
617
emit doubleClick();
618
break;
619
case QEvent::MouseButtonPress:
620
case QEvent::MouseButtonRelease:
621
switch(((QMouseEvent*)e)->button()) {
622
case Qt::LeftButton:
623
input.x = ((QMouseEvent*)e)->pos().x() * g_display.dpi_scale_x * xscale;
624
input.y = ((QMouseEvent*)e)->pos().y() * g_display.dpi_scale_y * yscale;
625
input.flags = ((e->type() == QEvent::MouseButtonPress) ? TOUCH_DOWN : TOUCH_UP) | TOUCH_MOUSE;
626
input.id = 0;
627
NativeTouch(input);
628
break;
629
case Qt::RightButton:
630
NativeKey(KeyInput(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, (e->type() == QEvent::MouseButtonPress) ? KEY_DOWN : KEY_UP));
631
break;
632
case Qt::MiddleButton:
633
NativeKey(KeyInput(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_3, (e->type() == QEvent::MouseButtonPress) ? KEY_DOWN : KEY_UP));
634
break;
635
case Qt::ExtraButton1:
636
NativeKey(KeyInput(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_4, (e->type() == QEvent::MouseButtonPress) ? KEY_DOWN : KEY_UP));
637
break;
638
case Qt::ExtraButton2:
639
NativeKey(KeyInput(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_5, (e->type() == QEvent::MouseButtonPress) ? KEY_DOWN : KEY_UP));
640
break;
641
default:
642
break;
643
}
644
break;
645
case QEvent::MouseMove:
646
input.x = ((QMouseEvent*)e)->pos().x() * g_display.dpi_scale_x * xscale;
647
input.y = ((QMouseEvent*)e)->pos().y() * g_display.dpi_scale_y * yscale;
648
input.flags = TOUCH_MOVE | TOUCH_MOUSE;
649
input.id = 0;
650
NativeTouch(input);
651
break;
652
case QEvent::Wheel:
653
NativeKey(KeyInput(DEVICE_ID_MOUSE, ((QWheelEvent*)e)->delta()<0 ? NKCODE_EXT_MOUSEWHEEL_DOWN : NKCODE_EXT_MOUSEWHEEL_UP, KEY_DOWN));
654
break;
655
case QEvent::KeyPress:
656
{
657
auto qtKeycode = ((QKeyEvent*)e)->key();
658
auto iter = KeyMapRawQttoNative.find(qtKeycode);
659
InputKeyCode nativeKeycode = NKCODE_UNKNOWN;
660
if (iter != KeyMapRawQttoNative.end()) {
661
nativeKeycode = iter->second;
662
NativeKey(KeyInput(DEVICE_ID_KEYBOARD, nativeKeycode, KEY_DOWN));
663
}
664
665
// Also get the unicode value.
666
QString text = ((QKeyEvent*)e)->text();
667
std::string str = text.toStdString();
668
// Now, we don't want CHAR events for non-printable characters. Not quite sure how we'll best
669
// do that, but here's one attempt....
670
switch (nativeKeycode) {
671
case NKCODE_DEL:
672
case NKCODE_FORWARD_DEL:
673
case NKCODE_TAB:
674
break;
675
default:
676
if (str.size()) {
677
int pos = 0;
678
int unicode = u8_nextchar(str.c_str(), &pos, str.size());
679
NativeKey(KeyInput(DEVICE_ID_KEYBOARD, unicode));
680
}
681
break;
682
}
683
}
684
break;
685
case QEvent::KeyRelease:
686
NativeKey(KeyInput(DEVICE_ID_KEYBOARD, KeyMapRawQttoNative.find(((QKeyEvent*)e)->key())->second, KEY_UP));
687
break;
688
689
default:
690
// Can't switch on dynamic event types.
691
if (!HandleCustomEvent(e)) {
692
return QWidget::event(e);
693
}
694
}
695
e->accept();
696
return true;
697
}
698
699
void MainUI::initializeGL() {
700
if (g_Config.iGPUBackend != (int)GPUBackend::OPENGL) {
701
INFO_LOG(Log::System, "Only GL supported under Qt - switching.");
702
g_Config.iGPUBackend = (int)GPUBackend::OPENGL;
703
}
704
705
bool useCoreContext = format().profile() == QGLFormat::CoreProfile;
706
707
SetGLCoreContext(useCoreContext);
708
709
#ifndef USING_GLES2
710
// Some core profile drivers elide certain extensions from GL_EXTENSIONS/etc.
711
// glewExperimental allows us to force GLEW to search for the pointers anyway.
712
if (useCoreContext) {
713
glewExperimental = true;
714
}
715
glewInit();
716
// Unfortunately, glew will generate an invalid enum error, ignore.
717
if (useCoreContext) {
718
glGetError();
719
}
720
#endif
721
if (g_Config.iGPUBackend == (int)GPUBackend::OPENGL) {
722
// OpenGL uses a background thread to do the main processing and only renders on the gl thread.
723
INFO_LOG(Log::System, "Initializing GL graphics context");
724
graphicsContext = new QtGLGraphicsContext();
725
INFO_LOG(Log::System, "Using thread, starting emu thread");
726
EmuThreadStart();
727
} else {
728
INFO_LOG(Log::System, "Not using thread, backend=%d", (int)g_Config.iGPUBackend);
729
}
730
graphicsContext->ThreadStart();
731
}
732
733
void MainUI::paintGL() {
734
#ifdef SDL
735
SDL_PumpEvents();
736
#endif
737
updateAccelerometer();
738
if (emuThreadState == (int)EmuThreadState::DISABLED) {
739
NativeFrame(graphicsContext);
740
} else {
741
graphicsContext->ThreadFrame();
742
// Do the rest in EmuThreadFunc
743
}
744
}
745
746
void MainUI::updateAccelerometer() {
747
#if defined(MOBILE_DEVICE)
748
// TODO: Toggle it depending on whether it is enabled
749
QAccelerometerReading *reading = acc->reading();
750
if (reading) {
751
NativeAccelerometer(reading->x(), reading->y(), reading->z());
752
}
753
#endif
754
}
755
756
#ifndef SDL
757
758
MainAudio::~MainAudio() {
759
if (feed != nullptr) {
760
killTimer(timer);
761
feed->close();
762
}
763
if (output) {
764
output->stop();
765
delete output;
766
}
767
if (mixbuf)
768
free(mixbuf);
769
}
770
771
void MainAudio::run() {
772
QAudioFormat fmt;
773
fmt.setSampleRate(AUDIO_FREQ);
774
fmt.setCodec("audio/pcm");
775
fmt.setChannelCount(AUDIO_CHANNELS);
776
fmt.setSampleSize(AUDIO_SAMPLESIZE);
777
fmt.setByteOrder(QAudioFormat::LittleEndian);
778
fmt.setSampleType(QAudioFormat::SignedInt);
779
mixlen = sizeof(short)*AUDIO_BUFFERS*AUDIO_CHANNELS*AUDIO_SAMPLES;
780
mixbuf = (char*)malloc(mixlen);
781
output = new QAudioOutput(fmt);
782
output->setBufferSize(mixlen);
783
feed = output->start();
784
if (feed != nullptr) {
785
// buffering has already done in the internal mixed buffer
786
// use a small interval to copy mixed audio stream from
787
// internal buffer to audio output buffer as soon as possible
788
// use 1 instead of 0 to prevent CPU exhausting
789
timer = startTimer(1);
790
}
791
}
792
793
void MainAudio::timerEvent(QTimerEvent *) {
794
memset(mixbuf, 0, mixlen);
795
NativeMix((short *)mixbuf, AUDIO_BUFFERS * AUDIO_SAMPLES, AUDIO_FREQ);
796
feed->write(mixbuf, sizeof(short) * AUDIO_CHANNELS * frames);
797
}
798
799
#endif
800
801
802
void QTCamera::startCamera(int width, int height) {
803
__qt_startCapture(width, height);
804
}
805
806
void QTCamera::stopCamera() {
807
__qt_stopCapture();
808
}
809
810
#ifndef SDL
811
Q_DECL_EXPORT
812
#endif
813
int main(int argc, char *argv[])
814
{
815
TimeInit();
816
817
g_logManager.EnableOutput(LogOutput::Stdio);
818
819
for (int i = 1; i < argc; i++) {
820
if (!strcmp(argv[i], "--version")) {
821
printf("%s\n", PPSSPP_GIT_VERSION);
822
return 0;
823
}
824
}
825
826
// Ignore sigpipe.
827
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
828
perror("Unable to ignore SIGPIPE");
829
}
830
831
PROFILE_INIT();
832
glslang::InitializeProcess();
833
#if defined(Q_OS_LINUX)
834
QApplication::setAttribute(Qt::AA_X11InitThreads, true);
835
#endif
836
837
// Qt would otherwise default to a 3.0 compatibility profile
838
// except on Nvidia, where Nvidia gives us the highest supported anyway
839
QGLFormat format;
840
format.setVersion(4, 6);
841
format.setProfile(QGLFormat::CoreProfile);
842
QGLFormat::setDefaultFormat(format);
843
844
QApplication a(argc, argv);
845
QScreen* screen = a.primaryScreen();
846
QSizeF res = screen->physicalSize();
847
848
if (res.width() < res.height())
849
res.transpose();
850
851
// We assume physicalDotsPerInchY is the same as PerInchX.
852
float dpi_scale_x = screen->logicalDotsPerInchX() / screen->physicalDotsPerInchX();
853
float dpi_scale_y = screen->logicalDotsPerInchY() / screen->physicalDotsPerInchY();
854
g_display.Recalculate(res.width(), res.height(), dpi_scale_x, dpi_scale_y, UIScaleFactorToMultiplier(g_Config.iUIScaleFactor));
855
856
refreshRate = screen->refreshRate();
857
858
qtcamera = new QTCamera;
859
QObject::connect(qtcamera, SIGNAL(onStartCamera(int, int)), qtcamera, SLOT(startCamera(int, int)));
860
QObject::connect(qtcamera, SIGNAL(onStopCamera()), qtcamera, SLOT(stopCamera()));
861
862
std::string savegame_dir = ".";
863
std::string external_dir = ".";
864
#if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
865
savegame_dir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation).toStdString();
866
external_dir = QStandardPaths::writableLocation(QStandardPaths::DataLocation).toStdString();
867
#endif
868
savegame_dir += "/";
869
external_dir += "/";
870
871
NativeInit(argc, (const char **)argv, savegame_dir.c_str(), external_dir.c_str(), nullptr);
872
873
g_mainWindow = new MainWindow(nullptr, g_Config.UseFullScreen());
874
g_mainWindow->show();
875
876
// TODO: Support other backends than GL, like Vulkan, in the Qt backend.
877
g_Config.iGPUBackend = (int)GPUBackend::OPENGL;
878
879
int ret = mainInternal(a);
880
INFO_LOG(Log::System, "Left mainInternal here.");
881
882
#ifdef SDL
883
if (audioDev > 0) {
884
SDL_PauseAudioDevice(audioDev, 1);
885
SDL_CloseAudioDevice(audioDev);
886
}
887
#endif
888
NativeShutdown();
889
glslang::FinalizeProcess();
890
return ret;
891
}
892
893