Compare commits

..
1 Commits
Author SHA1 Message Date
Cameron Gutman b23a36908c Add EGLFS GBM and Wayland support to AppImage 2022-04-09 18:23:09 -05:00
178 changed files with 10024 additions and 19769 deletions

No files matched your search

+14 -12
View File
@@ -1,6 +1,6 @@
# Moonlight PC # Moonlight PC
[Moonlight PC](https://moonlight-stream.org) is an open source PC client for NVIDIA GameStream and [Sunshine](https://github.com/LizardByte/Sunshine). [Moonlight PC](https://moonlight-stream.org) is an open source PC client for NVIDIA GameStream, as used by the NVIDIA Shield.
Moonlight also has mobile versions for [Android](https://github.com/moonlight-stream/moonlight-android) and [iOS](https://github.com/moonlight-stream/moonlight-ios). Moonlight also has mobile versions for [Android](https://github.com/moonlight-stream/moonlight-android) and [iOS](https://github.com/moonlight-stream/moonlight-ios).
@@ -12,13 +12,15 @@ You can follow development on our [Discord server](https://moonlight-stream.org/
## Features ## Features
- Hardware accelerated video decoding on Windows, Mac, and Linux - Hardware accelerated video decoding on Windows, Mac, and Linux
- H.264, HEVC, and AV1 codec support (AV1 requires Sunshine and a supported host GPU) - Supports streaming at up to 120 FPS (high refresh rate monitor recommended)
- Supports streaming at 720p, 1080p, 1440p, 4K, and the client PC's native screen resolution
- HDR streaming support - HDR streaming support
- 7.1 surround sound audio support - 7.1 surround sound audio support
- 10-point multitouch support (Sunshine only)
- Gamepad support with force feedback and motion controls for up to 16 players
- Support for both pointer capture (for games) and direct mouse control (for remote desktop) - Support for both pointer capture (for games) and direct mouse control (for remote desktop)
- Support for passing system-wide keyboard shortcuts like Alt+Tab to the host - Support for passing system-wide keyboard shortcuts like Alt+Tab to the host
- Direct touchscreen mouse control
- HEVC support for better image quality at reduced bandwidth
- Gamepad support with force feedback for up to 4 players
## Downloads ## Downloads
- [Windows, macOS, and Steam Link](https://github.com/moonlight-stream/moonlight-qt/releases) - [Windows, macOS, and Steam Link](https://github.com/moonlight-stream/moonlight-qt/releases)
@@ -39,23 +41,24 @@ Hosting for Moonlight's Raspberry Pi and L4T package repositories is graciously
### Windows Build Requirements ### Windows Build Requirements
* Qt 5.15 SDK or later * Qt 5.15 SDK or later
* Windows 7 or later * Windows 7 or later
* [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/) (Community edition is fine) * [Visual Studio 2019](https://visualstudio.microsoft.com/downloads/) (Community edition is fine)
* Select **MSVC** option during Qt installation. MinGW is not supported. * Select **MSVC 2019** option during Qt installation. MinGW is not supported.
* [7-Zip](https://www.7-zip.org/) (only if building installers for non-development PCs) * [7-Zip](https://www.7-zip.org/) (only if building installers for non-development PCs)
* [WiX Toolset](https://wixtoolset.org/releases/v3-14-0-5722/) v3.14.0.5722 or later (only if building installers for non-development PCs)
### macOS Build Requirements ### macOS Build Requirements
* Qt 6.2 SDK or later * Qt 6.2 SDK or later
* macOS Mojave (10.14) or later * macOS Mojave (10.14) or later
* Xcode 13 or later * Xcode 13
* [create-dmg](https://github.com/sindresorhus/create-dmg) (only if building DMGs for use on non-development Macs) * [create-dmg](https://github.com/sindresorhus/create-dmg) (only if building DMGs for use on non-development Macs)
### Linux/Unix Build Requirements ### Linux/Unix Build Requirements
* Qt 5.9 SDK or later * Qt 5.9 SDK or later
* GCC or Clang * GCC or Clang
* Install the required packages: * Install the required packages:
* Debian/Ubuntu: `libegl1-mesa-dev libgl1-mesa-dev libopus-dev libqt5svg5-dev libsdl2-dev libsdl2-ttf-dev libssl-dev libavcodec-dev libva-dev libvdpau-dev libxkbcommon-dev qtwayland5 qt5-qmake qtbase5-dev qtdeclarative5-dev qtquickcontrols2-5-dev wayland-protocols qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtquick-window2 qml-module-qtquick2` * Debian/Ubuntu: `libegl1-mesa-dev libgl1-mesa-dev libopus-dev libqt5svg5-dev libsdl2-dev libsdl2-ttf-dev libssl-dev libavcodec-dev libva-dev libvdpau-dev libxkbcommon-dev qt5-default qt5-qmake qtbase5-dev qtdeclarative5-dev qtquickcontrols2-5-dev wayland-protocols qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtquick-window2 qml-module-qtquick2`
* RedHat/Fedora: `openssl-devel SDL2-devel SDL2_ttf-devel ffmpeg-devel qt5-qtsvg-devel qt5-qtquickcontrols2-devel libva-devel libvdpau-devel opus-devel pulseaudio-libs-devel alsa-lib-devel` * RedHat/Fedora: `openssl-devel SDL2-devel SDL2_ttf-devel ffmpeg-devel qt5-qtsvg-devel qt5-qtquickcontrols2-devel libva-devel libvdpau-devel opus-devel pulseaudio-libs-devel alsa-lib-devel`
* FFmpeg 4.0 or later is required to build. If your distro doesn't package FFmpeg 4.0 or later, you can build and install it from source on https://ffmpeg.org/ * FFmpeg 4.0+ is required to build. If your distro doesn't package FFmpeg 4.0 or later, you can build and install it from source on https://ffmpeg.org/
### Steam Link Build Requirements ### Steam Link Build Requirements
* [Steam Link SDK](https://github.com/ValveSoftware/steamlink-sdk) cloned on your build system * [Steam Link SDK](https://github.com/ValveSoftware/steamlink-sdk) cloned on your build system
@@ -69,13 +72,12 @@ Hosting for Moonlight's Raspberry Pi and L4T package repositories is graciously
2. Run `git submodule update --init --recursive` from within `moonlight-qt/` 2. Run `git submodule update --init --recursive` from within `moonlight-qt/`
3. Open the project in Qt Creator or build from qmake on the command line. 3. Open the project in Qt Creator or build from qmake on the command line.
* To build a binary for use on non-development machines, use the scripts in the `scripts` folder. * To build a binary for use on non-development machines, use the scripts in the `scripts` folder.
* For Windows builds, use `scripts\build-arch.bat` and `scripts\generate-bundle.bat`. Execute these scripts from the root of the repository within a Qt command prompt. Ensure 7-Zip binary directory is on your `%PATH%`. * For Windows builds, use `scripts\build-arch.bat` and `scripts\generate-bundle.bat`. Execute these scripts from the root of the repository within a Qt command prompt. Ensure WiX and 7-Zip binary directories are in your `%PATH%`.
* For macOS builds, use `scripts/generate-dmg.sh`. Execute this script from the root of the repository and ensure Qt's `bin` folder is in your `$PATH`. * For macOS builds, use `scripts/generate-dmg.sh`. Execute this script from the root of the repository and ensure Qt's `bin` folder is in your `$PATH`.
* For Steam Link builds, run `scripts/build-steamlink-app.sh` from the root of the repository. * For Steam Link builds, run `scripts/build-steamlink-app.sh` from the root of the repository.
* To build from the command line for development use on macOS or Linux, run `qmake moonlight-qt.pro` then `make debug` or `make release` * To build from the command line for development use, run `qmake moonlight-qt.pro` then `make debug` or `make release`
* To create an embedded build for a single-purpose device, use `qmake "CONFIG+=embedded" moonlight-qt.pro` and build normally. * To create an embedded build for a single-purpose device, use `qmake "CONFIG+=embedded" moonlight-qt.pro` and build normally.
* This build will lack windowed mode, Discord/Help links, and other features that don't make sense on an embedded device. * This build will lack windowed mode, Discord/Help links, and other features that don't make sense on an embedded device.
* For platforms with poor GL performance, add `"CONFIG+=glslow"` to prefer direct KMSDRM rendering over EGL/GLES renderers. Direct KMSDRM rendering can use dedicated YUV/RGB conversion and scaling hardware rather than slower GPU shaders for these operations.
## Contribute ## Contribute
1. Fork us 1. Fork us
+1 -17
View File
@@ -5,7 +5,7 @@
<key>CFBundleExecutable</key> <key>CFBundleExecutable</key>
<string>Moonlight</string> <string>Moonlight</string>
<key>CFBundleGetInfoString</key> <key>CFBundleGetInfoString</key>
<string>Stream games and other applications from another PC</string> <string>Stream games from your NVIDIA GameStream-enabled PC</string>
<key>CFBundleIconFile</key> <key>CFBundleIconFile</key>
<string>moonlight</string> <string>moonlight</string>
<key>CFBundleIdentifier</key> <key>CFBundleIdentifier</key>
@@ -22,22 +22,6 @@
<string>NSApplication</string> <string>NSApplication</string>
<key>NSSupportsAutomaticGraphicsSwitching</key> <key>NSSupportsAutomaticGraphicsSwitching</key>
<true/> <true/>
<key>GCSupportedGameControllers</key>
<array>
<dict>
<key>ProfileName</key>
<string>ExtendedGamepad</string>
</dict>
</array>
<key>GCSupportsControllerUserInteraction</key>
<true/>
<key>LSApplicationCategoryType</key>
<string>public.app-category.games</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>VERSION</string> <string>VERSION</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
+48 -115
View File
@@ -48,93 +48,63 @@ win32 {
INCLUDEPATH += $$PWD/../libs/windows/include INCLUDEPATH += $$PWD/../libs/windows/include
LIBS += ws2_32.lib winmm.lib dxva2.lib ole32.lib gdi32.lib user32.lib d3d9.lib dwmapi.lib dbghelp.lib LIBS += ws2_32.lib winmm.lib dxva2.lib ole32.lib gdi32.lib user32.lib d3d9.lib dwmapi.lib dbghelp.lib
# Work around a conflict with math.h inclusion between SDL and Qt 6
DEFINES += _USE_MATH_DEFINES
} }
macx { macx {
INCLUDEPATH += $$PWD/../libs/mac/include INCLUDEPATH += $$PWD/../libs/mac/include
INCLUDEPATH += $$PWD/../libs/mac/Frameworks/SDL2.framework/Versions/A/Headers INCLUDEPATH += $$PWD/../libs/mac/Frameworks/SDL2.framework/Versions/A/Headers
INCLUDEPATH += $$PWD/../libs/mac/Frameworks/SDL2_ttf.framework/Versions/A/Headers INCLUDEPATH += $$PWD/../libs/mac/Frameworks/SDL2_ttf.framework/Versions/A/Headers
LIBS += -L$$PWD/../libs/mac/lib -F$$PWD/../libs/mac/Frameworks LIBS += -L$$PWD/../libs/mac/lib -F$$PWD/../libs/mac/Frameworks
# QMake doesn't handle framework-style includes correctly on its own
QMAKE_CFLAGS += -F$$PWD/../libs/mac/Frameworks
QMAKE_CXXFLAGS += -F$$PWD/../libs/mac/Frameworks
QMAKE_OBJECTIVE_CFLAGS += -F$$PWD/../libs/mac/Frameworks
} }
unix:!macx { unix:!macx {
CONFIG += link_pkgconfig CONFIG += link_pkgconfig
PKGCONFIG += openssl sdl2 SDL2_ttf opus PKGCONFIG += openssl sdl2 SDL2_ttf opus
!disable-ffmpeg { packagesExist(libavcodec) {
packagesExist(libavcodec) { PKGCONFIG += libavcodec libavutil
PKGCONFIG += libavcodec libavutil CONFIG += ffmpeg
CONFIG += ffmpeg
!disable-libva { packagesExist(libva) {
packagesExist(libva) { packagesExist(libva-x11) {
!disable-x11 { CONFIG += libva-x11
packagesExist(libva-x11) {
CONFIG += libva-x11
}
}
!disable-wayland {
packagesExist(libva-wayland) {
CONFIG += libva-wayland
}
}
!disable-libdrm {
packagesExist(libva-drm) {
CONFIG += libva-drm
}
}
CONFIG += libva
}
} }
packagesExist(libva-wayland) {
!disable-libvdpau { CONFIG += libva-wayland
packagesExist(vdpau) {
CONFIG += libvdpau
}
} }
packagesExist(libva-drm) {
!disable-mmal { CONFIG += libva-drm
packagesExist(mmal) {
PKGCONFIG += mmal
CONFIG += mmal
}
}
!disable-libdrm {
packagesExist(libdrm) {
PKGCONFIG += libdrm
CONFIG += libdrm
}
}
!disable-cuda {
packagesExist(ffnvcodec) {
PKGCONFIG += ffnvcodec
CONFIG += cuda
}
} }
CONFIG += libva
} }
!disable-wayland { packagesExist(vdpau) {
packagesExist(wayland-client) { CONFIG += libvdpau
CONFIG += wayland
PKGCONFIG += wayland-client
}
} }
!disable-x11 { packagesExist(mmal) {
packagesExist(x11) { PKGCONFIG += mmal
DEFINES += HAS_X11 CONFIG += mmal
PKGCONFIG += x11
}
} }
packagesExist(libdrm) {
PKGCONFIG += libdrm
CONFIG += libdrm
}
packagesExist(ffnvcodec) {
PKGCONFIG += ffnvcodec
CONFIG += cuda
}
}
packagesExist(wayland-client) {
DEFINES += HAS_WAYLAND
PKGCONFIG += wayland-client
}
packagesExist(x11) {
DEFINES += HAS_X11
PKGCONFIG += x11
} }
} }
win32 { win32 {
@@ -145,7 +115,7 @@ win32:!winrt {
CONFIG += soundio discord-rpc CONFIG += soundio discord-rpc
} }
macx { macx {
LIBS += -lssl -lcrypto -lavcodec.60 -lavutil.58 -lopus -framework SDL2 -framework SDL2_ttf LIBS += -lssl -lcrypto -lavcodec.59 -lavutil.57 -lopus -framework SDL2 -framework SDL2_ttf
LIBS += -lobjc -framework VideoToolbox -framework AVFoundation -framework CoreVideo -framework CoreGraphics -framework CoreMedia -framework AppKit -framework Metal LIBS += -lobjc -framework VideoToolbox -framework AVFoundation -framework CoreVideo -framework CoreGraphics -framework CoreMedia -framework AppKit -framework Metal
# For libsoundio # For libsoundio
@@ -157,7 +127,6 @@ macx {
SOURCES += \ SOURCES += \
backend/nvaddress.cpp \ backend/nvaddress.cpp \
backend/nvapp.cpp \ backend/nvapp.cpp \
cli/pair.cpp \
main.cpp \ main.cpp \
backend/computerseeker.cpp \ backend/computerseeker.cpp \
backend/identitymanager.cpp \ backend/identitymanager.cpp \
@@ -168,7 +137,6 @@ SOURCES += \
backend/boxartmanager.cpp \ backend/boxartmanager.cpp \
backend/richpresencemanager.cpp \ backend/richpresencemanager.cpp \
cli/commandlineparser.cpp \ cli/commandlineparser.cpp \
cli/listapps.cpp \
cli/quitstream.cpp \ cli/quitstream.cpp \
cli/startstream.cpp \ cli/startstream.cpp \
settings/compatfetcher.cpp \ settings/compatfetcher.cpp \
@@ -197,7 +165,6 @@ SOURCES += \
HEADERS += \ HEADERS += \
backend/nvaddress.h \ backend/nvaddress.h \
backend/nvapp.h \ backend/nvapp.h \
cli/pair.h \
settings/compatfetcher.h \ settings/compatfetcher.h \
settings/mappingfetcher.h \ settings/mappingfetcher.h \
utils.h \ utils.h \
@@ -210,7 +177,6 @@ HEADERS += \
backend/boxartmanager.h \ backend/boxartmanager.h \
backend/richpresencemanager.h \ backend/richpresencemanager.h \
cli/commandlineparser.h \ cli/commandlineparser.h \
cli/listapps.h \
cli/quitstream.h \ cli/quitstream.h \
cli/startstream.h \ cli/startstream.h \
settings/streamingpreferences.h \ settings/streamingpreferences.h \
@@ -237,15 +203,15 @@ ffmpeg {
SOURCES += \ SOURCES += \
streaming/video/ffmpeg.cpp \ streaming/video/ffmpeg.cpp \
streaming/video/ffmpeg-renderers/sdlvid.cpp \ streaming/video/ffmpeg-renderers/sdlvid.cpp \
streaming/video/ffmpeg-renderers/swframemapper.cpp \ streaming/video/ffmpeg-renderers/pacer/pacer.cpp \
streaming/video/ffmpeg-renderers/pacer/pacer.cpp streaming/video/ffmpeg-renderers/pacer/nullthreadedvsyncsource.cpp
HEADERS += \ HEADERS += \
streaming/video/ffmpeg.h \ streaming/video/ffmpeg.h \
streaming/video/ffmpeg-renderers/renderer.h \ streaming/video/ffmpeg-renderers/renderer.h \
streaming/video/ffmpeg-renderers/sdlvid.h \ streaming/video/ffmpeg-renderers/sdlvid.h \
streaming/video/ffmpeg-renderers/swframemapper.h \ streaming/video/ffmpeg-renderers/pacer/pacer.h \
streaming/video/ffmpeg-renderers/pacer/pacer.h streaming/video/ffmpeg-renderers/pacer/nullthreadedvsyncsource.h
} }
libva { libva {
message(VAAPI renderer selected) message(VAAPI renderer selected)
@@ -267,7 +233,7 @@ libva-wayland {
PKGCONFIG += libva-wayland PKGCONFIG += libva-wayland
DEFINES += HAVE_LIBVA_WAYLAND DEFINES += HAVE_LIBVA_WAYLAND
} }
libva-drm { libva-wayland {
message(VAAPI DRM support enabled) message(VAAPI DRM support enabled)
PKGCONFIG += libva-drm PKGCONFIG += libva-drm
@@ -286,18 +252,6 @@ mmal {
DEFINES += HAVE_MMAL DEFINES += HAVE_MMAL
SOURCES += streaming/video/ffmpeg-renderers/mmal.cpp SOURCES += streaming/video/ffmpeg-renderers/mmal.cpp
HEADERS += streaming/video/ffmpeg-renderers/mmal.h HEADERS += streaming/video/ffmpeg-renderers/mmal.h
# We suppress EGL usage when MMAL is available because MMAL has
# significantly better performance than EGL on the Pi. Setting
# this option allows EGL usage even if built with MMAL support.
#
# It is highly recommended to also build with 'glslow' to avoid
# EGL being preferred if direct DRM rendering is available.
allow-egl-with-mmal {
message(Allowing EGL usage with MMAL enabled)
DEFINES += ALLOW_EGL_WITH_MMAL
}
} }
libdrm { libdrm {
message(DRM renderer selected) message(DRM renderer selected)
@@ -308,7 +262,7 @@ libdrm {
linux { linux {
message(Master hooks enabled) message(Master hooks enabled)
SOURCES += masterhook.c masterhook_internal.c SOURCES += masterhook.c
LIBS += -ldl LIBS += -ldl
} }
} }
@@ -318,9 +272,6 @@ cuda {
DEFINES += HAVE_CUDA DEFINES += HAVE_CUDA
SOURCES += streaming/video/ffmpeg-renderers/cuda.cpp SOURCES += streaming/video/ffmpeg-renderers/cuda.cpp
HEADERS += streaming/video/ffmpeg-renderers/cuda.h HEADERS += streaming/video/ffmpeg-renderers/cuda.h
# ffnvcodec uses libdl in cuda_load_functions()/cuda_free_functions()
LIBS += -ldl
} }
config_EGL { config_EGL {
message(EGL renderer selected) message(EGL renderer selected)
@@ -329,11 +280,8 @@ config_EGL {
DEFINES += HAVE_EGL DEFINES += HAVE_EGL
SOURCES += \ SOURCES += \
streaming/video/ffmpeg-renderers/eglvid.cpp \ streaming/video/ffmpeg-renderers/eglvid.cpp \
streaming/video/ffmpeg-renderers/egl_extensions.cpp \ streaming/video/ffmpeg-renderers/egl_extensions.cpp
streaming/video/ffmpeg-renderers/eglimagefactory.cpp HEADERS += streaming/video/ffmpeg-renderers/eglvid.h
HEADERS += \
streaming/video/ffmpeg-renderers/eglvid.h \
streaming/video/ffmpeg-renderers/eglimagefactory.h
} }
config_SL { config_SL {
message(Steam Link build configuration selected) message(Steam Link build configuration selected)
@@ -391,25 +339,13 @@ embedded {
DEFINES += EMBEDDED_BUILD DEFINES += EMBEDDED_BUILD
} }
glslow {
message(GL slow build)
DEFINES += GL_IS_SLOW
}
wayland {
message(Wayland extensions enabled)
DEFINES += HAS_WAYLAND
SOURCES += streaming/video/ffmpeg-renderers/pacer/waylandvsyncsource.cpp
HEADERS += streaming/video/ffmpeg-renderers/pacer/waylandvsyncsource.h
}
RESOURCES += \ RESOURCES += \
resources.qrc \ resources.qrc \
qml.qrc qml.qrc
TRANSLATIONS += \ TRANSLATIONS += \
languages/qml_zh_CN.ts \ languages/qml_zh_cn.ts \
languages/qml_de.ts \ languages/qml_de.ts \
languages/qml_fr.ts \ languages/qml_fr.ts \
languages/qml_nb_NO.ts \ languages/qml_nb_NO.ts \
@@ -424,15 +360,12 @@ TRANSLATIONS += \
languages/qml_sv.ts \ languages/qml_sv.ts \
languages/qml_tr.ts \ languages/qml_tr.ts \
languages/qml_uk.ts \ languages/qml_uk.ts \
languages/qml_zh_TW.ts \ languages/qml_zh_Hant.ts \
languages/qml_el.ts \ languages/qml_el.ts \
languages/qml_hi.ts \ languages/qml_hi.ts \
languages/qml_it.ts \ languages/qml_it.ts \
languages/qml_pt.ts \ languages/qml_pt.ts \
languages/qml_pt_BR.ts \ languages/qml_pt_BR.ts
languages/qml_pl.ts \
languages/qml_cs.ts \
languages/qml_he.ts
# Additional import path used to resolve QML modules in Qt Creator's code model # Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH = QML_IMPORT_PATH =
+8 -19
View File
@@ -6,17 +6,16 @@
#include <QJsonObject> #include <QJsonObject>
AutoUpdateChecker::AutoUpdateChecker(QObject *parent) : AutoUpdateChecker::AutoUpdateChecker(QObject *parent) :
QObject(parent) QObject(parent),
m_Nam(this)
{ {
m_Nam = new QNetworkAccessManager(this);
// Never communicate over HTTP // Never communicate over HTTP
m_Nam->setStrictTransportSecurityEnabled(true); m_Nam.setStrictTransportSecurityEnabled(true);
// Allow HTTP redirects // Allow HTTP redirects
m_Nam->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy); m_Nam.setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy);
connect(m_Nam, &QNetworkAccessManager::finished, connect(&m_Nam, &QNetworkAccessManager::finished,
this, &AutoUpdateChecker::handleUpdateCheckRequestFinished); this, &AutoUpdateChecker::handleUpdateCheckRequestFinished);
QString currentVersion(VERSION_STR); QString currentVersion(VERSION_STR);
@@ -29,17 +28,12 @@ AutoUpdateChecker::AutoUpdateChecker(QObject *parent) :
void AutoUpdateChecker::start() void AutoUpdateChecker::start()
{ {
if (!m_Nam) {
Q_ASSERT(m_Nam);
return;
}
#if defined(Q_OS_WIN32) || defined(Q_OS_DARWIN) || defined(STEAM_LINK) || defined(APP_IMAGE) // Only run update checker on platforms without auto-update #if defined(Q_OS_WIN32) || defined(Q_OS_DARWIN) || defined(STEAM_LINK) || defined(APP_IMAGE) // Only run update checker on platforms without auto-update
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) && QT_VERSION < QT_VERSION_CHECK(5, 15, 1) && !defined(QT_NO_BEARERMANAGEMENT) #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) && QT_VERSION < QT_VERSION_CHECK(5, 15, 1) && !defined(QT_NO_BEARERMANAGEMENT)
// HACK: Set network accessibility to work around QTBUG-80947 (introduced in Qt 5.14.0 and fixed in Qt 5.15.1) // HACK: Set network accessibility to work around QTBUG-80947 (introduced in Qt 5.14.0 and fixed in Qt 5.15.1)
QT_WARNING_PUSH QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED QT_WARNING_DISABLE_DEPRECATED
m_Nam->setNetworkAccessible(QNetworkAccessManager::Accessible); m_Nam.setNetworkAccessible(QNetworkAccessManager::Accessible);
QT_WARNING_POP QT_WARNING_POP
#endif #endif
@@ -51,7 +45,7 @@ void AutoUpdateChecker::start()
#else #else
request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true);
#endif #endif
m_Nam->get(request); m_Nam.get(request);
#endif #endif
} }
@@ -108,11 +102,6 @@ void AutoUpdateChecker::handleUpdateCheckRequestFinished(QNetworkReply* reply)
{ {
Q_ASSERT(reply->isFinished()); Q_ASSERT(reply->isFinished());
// Delete the QNetworkAccessManager to free resources and
// prevent the bearer plugin from polling in the background.
m_Nam->deleteLater();
m_Nam = nullptr;
if (reply->error() == QNetworkReply::NoError) { if (reply->error() == QNetworkReply::NoError) {
QTextStream stream(reply); QTextStream stream(reply);
@@ -212,7 +201,7 @@ void AutoUpdateChecker::handleUpdateCheckRequestFinished(QNetworkReply* reply)
<< QSysInfo::buildCpuArchitecture() << getPlatform() << QSysInfo::kernelVersion(); << QSysInfo::buildCpuArchitecture() << getPlatform() << QSysInfo::kernelVersion();
} }
else { else {
qWarning() << "Update checking failed with error:" << reply->error(); qWarning() << "Update checking failed with error: " << reply->error();
reply->deleteLater(); reply->deleteLater();
} }
} }
+1 -1
View File
@@ -25,5 +25,5 @@ private:
QString getPlatform(); QString getPlatform();
QVector<int> m_CurrentVersionQuad; QVector<int> m_CurrentVersionQuad;
QNetworkAccessManager* m_Nam; QNetworkAccessManager m_Nam;
}; };
+41 -199
View File
@@ -10,10 +10,7 @@
#include <QThreadPool> #include <QThreadPool>
#include <QCoreApplication> #include <QCoreApplication>
#include <random>
#define SER_HOSTS "hosts" #define SER_HOSTS "hosts"
#define SER_HOSTS_BACKUP "hostsbackup"
class PcMonitorThread : public QThread class PcMonitorThread : public QThread
{ {
@@ -45,7 +42,7 @@ private:
// Ensure the machine that responded is the one we intended to contact // Ensure the machine that responded is the one we intended to contact
if (m_Computer->uuid != newState.uuid) { if (m_Computer->uuid != newState.uuid) {
qInfo() << "Found unexpected PC" << newState.name << "looking for" << m_Computer->name; qInfo() << "Found unexpected PC " << newState.name << " looking for " << m_Computer->name;
return false; return false;
} }
@@ -148,39 +145,25 @@ ComputerManager::ComputerManager(QObject *parent)
: QObject(parent), : QObject(parent),
m_PollingRef(0), m_PollingRef(0),
m_MdnsBrowser(nullptr), m_MdnsBrowser(nullptr),
m_CompatFetcher(nullptr), m_CompatFetcher(nullptr)
m_NeedsDelayedFlush(false)
{ {
QSettings settings; QSettings settings;
// If there's a hosts backup copy, we must have failed to commit
// a previous update before exiting. Restore the backup now.
int hosts = settings.beginReadArray(SER_HOSTS_BACKUP);
if (hosts == 0) {
// If there's no host backup, read from the primary location.
settings.endArray();
hosts = settings.beginReadArray(SER_HOSTS);
}
// Inflate our hosts from QSettings // Inflate our hosts from QSettings
int hosts = settings.beginReadArray(SER_HOSTS);
for (int i = 0; i < hosts; i++) { for (int i = 0; i < hosts; i++) {
settings.setArrayIndex(i); settings.setArrayIndex(i);
NvComputer* computer = new NvComputer(settings); NvComputer* computer = new NvComputer(settings);
m_KnownHosts[computer->uuid] = computer; m_KnownHosts[computer->uuid] = computer;
m_LastSerializedHosts[computer->uuid] = *computer;
} }
settings.endArray(); settings.endArray();
// Fetch latest compatibility data asynchronously // Fetch latest compatibility data asynchronously
m_CompatFetcher.start(); m_CompatFetcher.start();
// Start the delayed flush thread to handle saveHosts() calls
m_DelayedFlushThread = new DelayedFlushThread(this);
m_DelayedFlushThread->start();
// To quit in a timely manner, we must block additional requests // To quit in a timely manner, we must block additional requests
// after we receive the aboutToQuit() signal. This is necessary // after we receive the aboutToQuit() signal. This is neccessary
// because NvHTTP uses aboutToQuit() to abort requests in progress // because NvHTTP uses aboutToQuit() to abort requests in progres
// while quitting, however this is a one time signal - additional // while quitting, however this is a one time signal - additional
// requests would not be aborted and block termination. // requests would not be aborted and block termination.
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &ComputerManager::handleAboutToQuit); connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &ComputerManager::handleAboutToQuit);
@@ -188,21 +171,6 @@ ComputerManager::ComputerManager(QObject *parent)
ComputerManager::~ComputerManager() ComputerManager::~ComputerManager()
{ {
// Stop the delayed flush thread before acquiring the lock in write mode
// to avoid deadlocking with a flush that needs the lock in read mode.
{
// Wake the delayed flush thread
m_DelayedFlushThread->requestInterruption();
m_DelayedFlushCondition.wakeOne();
// Wait for it to terminate (and finish any pending flush)
m_DelayedFlushThread->wait();
delete m_DelayedFlushThread;
// Delayed flushes should have completed by now
Q_ASSERT(!m_NeedsDelayedFlush);
}
QWriteLocker lock(&m_Lock); QWriteLocker lock(&m_Lock);
// Delete machines that haven't been resolved yet // Delete machines that haven't been resolved yet
@@ -232,80 +200,19 @@ ComputerManager::~ComputerManager()
} }
} }
void DelayedFlushThread::run() {
for (;;) {
// Wait for a delayed flush request or an interruption
{
QMutexLocker locker(&m_ComputerManager->m_DelayedFlushMutex);
while (!QThread::currentThread()->isInterruptionRequested() && !m_ComputerManager->m_NeedsDelayedFlush) {
m_ComputerManager->m_DelayedFlushCondition.wait(&m_ComputerManager->m_DelayedFlushMutex);
}
// Bail without flushing if we woke up for an interruption alone.
// If we have both an interruption and a flush request, do the flush.
if (!m_ComputerManager->m_NeedsDelayedFlush) {
Q_ASSERT(QThread::currentThread()->isInterruptionRequested());
break;
}
// Reset the delayed flush flag to ensure any racing saveHosts() call will set it again
m_ComputerManager->m_NeedsDelayedFlush = false;
// Update the last serialized hosts map under the delayed flush mutex
m_ComputerManager->m_LastSerializedHosts.clear();
for (const NvComputer* computer : m_ComputerManager->m_KnownHosts) {
// Copy the current state of the NvComputer to allow us to check later if we need
// to serialize it again when attribute updates occur.
QReadLocker computerLock(&computer->lock);
m_ComputerManager->m_LastSerializedHosts[computer->uuid] = *computer;
}
}
// Perform the flush
{
QSettings settings;
// First, write to the backup location
settings.beginWriteArray(SER_HOSTS_BACKUP);
{
QReadLocker lock(&m_ComputerManager->m_Lock);
int i = 0;
for (const NvComputer* computer : m_ComputerManager->m_KnownHosts) {
settings.setArrayIndex(i++);
computer->serialize(settings, false);
}
}
settings.endArray();
// Next, write to the primary location
settings.remove(SER_HOSTS);
settings.beginWriteArray(SER_HOSTS);
{
QReadLocker lock(&m_ComputerManager->m_Lock);
int i = 0;
for (const NvComputer* computer : m_ComputerManager->m_KnownHosts) {
settings.setArrayIndex(i++);
computer->serialize(settings, true);
}
}
settings.endArray();
// Finally, delete the backup copy
settings.remove(SER_HOSTS_BACKUP);
}
}
}
void ComputerManager::saveHosts() void ComputerManager::saveHosts()
{ {
Q_ASSERT(m_DelayedFlushThread != nullptr && m_DelayedFlushThread->isRunning()); QSettings settings;
QReadLocker lock(&m_Lock);
// Punt to a worker thread because QSettings on macOS can take ages (> 500 ms) settings.remove(SER_HOSTS);
// to persist our host list to disk (especially when a host has a bunch of apps). settings.beginWriteArray(SER_HOSTS);
QMutexLocker locker(&m_DelayedFlushMutex); int i = 0;
m_NeedsDelayedFlush = true; for (const NvComputer* computer : m_KnownHosts) {
m_DelayedFlushCondition.wakeOne(); settings.setArrayIndex(i++);
computer->serialize(settings);
}
settings.endArray();
} }
QHostAddress ComputerManager::getBestGlobalAddressV6(QVector<QHostAddress> &addresses) QHostAddress ComputerManager::getBestGlobalAddressV6(QVector<QHostAddress> &addresses)
@@ -356,13 +263,12 @@ void ComputerManager::startPolling()
if (prefs.enableMdns) { if (prefs.enableMdns) {
// Start an MDNS query for GameStream hosts // Start an MDNS query for GameStream hosts
m_MdnsServer.reset(new QMdnsEngine::Server()); m_MdnsBrowser = new QMdnsEngine::Browser(&m_MdnsServer, "_nvstream._tcp.local.", &m_MdnsCache);
m_MdnsBrowser = new QMdnsEngine::Browser(m_MdnsServer.data(), "_nvstream._tcp.local.");
connect(m_MdnsBrowser, &QMdnsEngine::Browser::serviceAdded, connect(m_MdnsBrowser, &QMdnsEngine::Browser::serviceAdded,
this, [this](const QMdnsEngine::Service& service) { this, [this](const QMdnsEngine::Service& service) {
qInfo() << "Discovered mDNS host:" << service.hostname(); qInfo() << "Discovered mDNS host:" << service.hostname();
MdnsPendingComputer* pendingComputer = new MdnsPendingComputer(m_MdnsServer, service); MdnsPendingComputer* pendingComputer = new MdnsPendingComputer(&m_MdnsServer, service);
connect(pendingComputer, &MdnsPendingComputer::resolvedHost, connect(pendingComputer, &MdnsPendingComputer::resolvedHost,
this, &ComputerManager::handleMdnsServiceResolved); this, &ComputerManager::handleMdnsServiceResolved);
m_PendingResolution.append(pendingComputer); m_PendingResolution.append(pendingComputer);
@@ -443,19 +349,6 @@ void ComputerManager::handleMdnsServiceResolved(MdnsPendingComputer* computer,
computer->deleteLater(); computer->deleteLater();
} }
void ComputerManager::saveHost(NvComputer *computer)
{
// If no serializable properties changed, don't bother saving hosts
QMutexLocker lock(&m_DelayedFlushMutex);
QReadLocker computerLock(&computer->lock);
if (!m_LastSerializedHosts.value(computer->uuid).isEqualSerialized(*computer)) {
// Queue a request for a delayed flush to QSettings outside of the lock
computerLock.unlock();
lock.unlock();
saveHosts();
}
}
void ComputerManager::handleComputerStateChanged(NvComputer* computer) void ComputerManager::handleComputerStateChanged(NvComputer* computer)
{ {
emit computerStateChanged(computer); emit computerStateChanged(computer);
@@ -465,20 +358,15 @@ void ComputerManager::handleComputerStateChanged(NvComputer* computer)
emit quitAppCompleted(QVariant()); emit quitAppCompleted(QVariant());
} }
// Save updates to this host // Save updated hosts to QSettings
saveHost(computer); saveHosts();
} }
QVector<NvComputer*> ComputerManager::getComputers() QVector<NvComputer*> ComputerManager::getComputers()
{ {
QReadLocker lock(&m_Lock); QReadLocker lock(&m_Lock);
// Return a sorted host list return QVector<NvComputer*>::fromList(m_KnownHosts.values());
auto hosts = QVector<NvComputer*>::fromList(m_KnownHosts.values());
std::stable_sort(hosts.begin(), hosts.end(), [](const NvComputer* host1, const NvComputer* host2) {
return host1->name.toLower() < host2->name.toLower();
});
return hosts;
} }
class DeferredHostDeletionTask : public QRunnable class DeferredHostDeletionTask : public QRunnable
@@ -502,7 +390,7 @@ public:
m_ComputerManager->m_KnownHosts.remove(m_Computer->uuid); m_ComputerManager->m_KnownHosts.remove(m_Computer->uuid);
} }
// Persist the new host list with this computer deleted // Persist the new host list
m_ComputerManager->saveHosts(); m_ComputerManager->saveHosts();
// Delete the polling entry first. This will stop all polling threads too. // Delete the polling entry first. This will stop all polling threads too.
@@ -543,13 +431,16 @@ void ComputerManager::renameHost(NvComputer* computer, QString name)
void ComputerManager::clientSideAttributeUpdated(NvComputer* computer) void ComputerManager::clientSideAttributeUpdated(NvComputer* computer)
{ {
// Persist the change
saveHosts();
// Notify the UI of the state change // Notify the UI of the state change
handleComputerStateChanged(computer); handleComputerStateChanged(computer);
} }
void ComputerManager::handleAboutToQuit() void ComputerManager::handleAboutToQuit()
{ {
QReadLocker lock(&m_Lock); QWriteLocker lock(&m_Lock);
// Interrupt polling threads immediately, so they // Interrupt polling threads immediately, so they
// avoid making additional requests while quitting // avoid making additional requests while quitting
@@ -564,8 +455,7 @@ class PendingPairingTask : public QObject, public QRunnable
public: public:
PendingPairingTask(ComputerManager* computerManager, NvComputer* computer, QString pin) PendingPairingTask(ComputerManager* computerManager, NvComputer* computer, QString pin)
: m_ComputerManager(computerManager), : m_Computer(computer),
m_Computer(computer),
m_Pin(pin) m_Pin(pin)
{ {
connect(this, &PendingPairingTask::pairingCompleted, connect(this, &PendingPairingTask::pairingCompleted,
@@ -585,34 +475,25 @@ private:
switch (result) switch (result)
{ {
case NvPairingManager::PairState::PIN_WRONG: case NvPairingManager::PairState::PIN_WRONG:
emit pairingCompleted(m_Computer, tr("The PIN from the PC didn't match. Please try again.")); emit pairingCompleted(m_Computer, "The PIN from the PC didn't match. Please try again.");
break; break;
case NvPairingManager::PairState::FAILED: case NvPairingManager::PairState::FAILED:
if (m_Computer->currentGameId != 0) { emit pairingCompleted(m_Computer, "Pairing failed. Please try again.");
emit pairingCompleted(m_Computer, tr("You cannot pair while a previous session is still running on the host PC. Quit any running games or reboot the host PC, then try pairing again."));
}
else {
emit pairingCompleted(m_Computer, tr("Pairing failed. Please try again."));
}
break; break;
case NvPairingManager::PairState::ALREADY_IN_PROGRESS: case NvPairingManager::PairState::ALREADY_IN_PROGRESS:
emit pairingCompleted(m_Computer, tr("Another pairing attempt is already in progress.")); emit pairingCompleted(m_Computer, "Another pairing attempt is already in progress.");
break; break;
case NvPairingManager::PairState::PAIRED: case NvPairingManager::PairState::PAIRED:
// Persist the newly pinned server certificate for this host
m_ComputerManager->saveHost(m_Computer);
emit pairingCompleted(m_Computer, nullptr); emit pairingCompleted(m_Computer, nullptr);
break; break;
} }
} catch (const GfeHttpResponseException& e) { } catch (const GfeHttpResponseException& e) {
emit pairingCompleted(m_Computer, tr("GeForce Experience returned error: %1").arg(e.toQString())); emit pairingCompleted(m_Computer, "GeForce Experience returned error: " + e.toQString());
} catch (const QtNetworkReplyException& e) { } catch (const QtNetworkReplyException& e) {
emit pairingCompleted(m_Computer, e.toQString()); emit pairingCompleted(m_Computer, e.toQString());
} }
} }
ComputerManager* m_ComputerManager;
NvComputer* m_Computer; NvComputer* m_Computer;
QString m_Pin; QString m_Pin;
}; };
@@ -699,10 +580,9 @@ void ComputerManager::stopPollingAsync()
m_PendingResolution.removeFirst(); m_PendingResolution.removeFirst();
} }
// Delete the browser and server to stop discovery and refresh polling // Delete the browser to stop discovery
delete m_MdnsBrowser; delete m_MdnsBrowser;
m_MdnsBrowser = nullptr; m_MdnsBrowser = nullptr;
m_MdnsServer.reset();
// Interrupt all threads, but don't wait for them to terminate // Interrupt all threads, but don't wait for them to terminate
for (ComputerPollingEntry* entry : m_PollEntries) { for (ComputerPollingEntry* entry : m_PollEntries) {
@@ -712,8 +592,8 @@ void ComputerManager::stopPollingAsync()
void ComputerManager::addNewHostManually(QString address) void ComputerManager::addNewHostManually(QString address)
{ {
QUrl url = QUrl::fromUserInput("moonlight://" + address); QUrl url = QUrl::fromUserInput(address);
if (url.isValid() && !url.host().isEmpty() && url.scheme() == "moonlight") { if (url.isValid() && !url.host().isEmpty()) {
// If there wasn't a port specified, use the default // If there wasn't a port specified, use the default
addNewHost(NvAddress(url.host(), url.port(DEFAULT_HTTP_PORT)), false); addNewHost(NvAddress(url.host(), url.port(DEFAULT_HTTP_PORT)), false);
} }
@@ -731,15 +611,12 @@ public:
: m_ComputerManager(computerManager), : m_ComputerManager(computerManager),
m_Address(address), m_Address(address),
m_MdnsIpv6Address(mdnsIpv6Address), m_MdnsIpv6Address(mdnsIpv6Address),
m_Mdns(mdns), m_Mdns(mdns)
m_AboutToQuit(false)
{ {
connect(this, &PendingAddTask::computerAddCompleted, connect(this, &PendingAddTask::computerAddCompleted,
computerManager, &ComputerManager::computerAddCompleted); computerManager, &ComputerManager::computerAddCompleted);
connect(this, &PendingAddTask::computerStateChanged, connect(this, &PendingAddTask::computerStateChanged,
computerManager, &ComputerManager::handleComputerStateChanged); computerManager, &ComputerManager::handleComputerStateChanged);
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit,
this, &PendingAddTask::handleAboutToQuit);
} }
signals: signals:
@@ -748,20 +625,9 @@ signals:
void computerStateChanged(NvComputer* computer); void computerStateChanged(NvComputer* computer);
private: private:
void handleAboutToQuit()
{
m_AboutToQuit = true;
}
QString fetchServerInfo(NvHTTP& http) QString fetchServerInfo(NvHTTP& http)
{ {
QString serverInfo; QString serverInfo;
// Do nothing if we're quitting
if (m_AboutToQuit) {
return QString();
}
try { try {
// There's a race condition between GameStream servers reporting presence over // There's a race condition between GameStream servers reporting presence over
// mDNS and the HTTPS server being ready to respond to our queries. To work // mDNS and the HTTPS server being ready to respond to our queries. To work
@@ -883,31 +749,16 @@ private:
hostAddress.isInSubnet(QHostAddress("192.168.0.0"), 16); hostAddress.isInSubnet(QHostAddress("192.168.0.0"), 16);
{ {
// Check if this PC already exists using opportunistic read lock // Check if this PC already exists
m_ComputerManager->m_Lock.lockForRead(); QWriteLocker lock(&m_ComputerManager->m_Lock);
NvComputer* existingComputer = m_ComputerManager->m_KnownHosts.value(newComputer->uuid); NvComputer* existingComputer = m_ComputerManager->m_KnownHosts.value(newComputer->uuid);
// If it doesn't already exist, convert to a write lock in preparation for updating.
//
// NB: ComputerManager's lock protects the host map itself, not the elements inside.
// Those are protected by their individual locks. Since we only mutate the map itself
// when the PC doesn't exist, we need the lock in write-mode for that case only.
if (existingComputer == nullptr) {
m_ComputerManager->m_Lock.unlock();
m_ComputerManager->m_Lock.lockForWrite();
// Since we had to unlock to lock for write, someone could have raced and added
// this PC before us. We have to check again whether it already exists.
existingComputer = m_ComputerManager->m_KnownHosts.value(newComputer->uuid);
}
if (existingComputer != nullptr) { if (existingComputer != nullptr) {
// Fold it into the existing PC // Fold it into the existing PC
bool changed = existingComputer->update(*newComputer); bool changed = existingComputer->update(*newComputer);
delete newComputer; delete newComputer;
// Drop the lock before notifying // Drop the lock before notifying
m_ComputerManager->m_Lock.unlock(); lock.unlock();
// For non-mDNS clients, let them know it succeeded // For non-mDNS clients, let them know it succeeded
if (!m_Mdns) { if (!m_Mdns) {
@@ -928,15 +779,17 @@ private:
m_ComputerManager->startPollingComputer(newComputer); m_ComputerManager->startPollingComputer(newComputer);
// Drop the lock before notifying // Drop the lock before notifying
m_ComputerManager->m_Lock.unlock(); lock.unlock();
// If this wasn't added via mDNS but it is a RFC 1918 IPv4 address and not a VPN, // If this wasn't added via mDNS but it is a RFC 1918 IPv4 address and not a VPN,
// go ahead and do the STUN request now to populate an external address. // go ahead and do the STUN request now to populate an external address.
if (!m_Mdns && addressIsSiteLocalV4 && newComputer->getActiveAddressReachability() != NvComputer::RI_VPN) { if (!m_Mdns && addressIsSiteLocalV4 && !newComputer->isReachableOverVpn()) {
quint32 addr; quint32 addr;
int err = LiFindExternalAddressIP4("stun.moonlight-stream.org", 3478, &addr); int err = LiFindExternalAddressIP4("stun.moonlight-stream.org", 3478, &addr);
if (err == 0) { if (err == 0) {
lock.relock();
newComputer->setRemoteAddress(QHostAddress(qFromBigEndian(addr))); newComputer->setRemoteAddress(QHostAddress(qFromBigEndian(addr)));
lock.unlock();
} }
else { else {
qWarning() << "STUN failed to get WAN address:" << err; qWarning() << "STUN failed to get WAN address:" << err;
@@ -958,7 +811,6 @@ private:
NvAddress m_Address; NvAddress m_Address;
NvAddress m_MdnsIpv6Address; NvAddress m_MdnsIpv6Address;
bool m_Mdns; bool m_Mdns;
bool m_AboutToQuit;
}; };
void ComputerManager::addNewHost(NvAddress address, bool mdns, NvAddress mdnsIpv6Address) void ComputerManager::addNewHost(NvAddress address, bool mdns, NvAddress mdnsIpv6Address)
@@ -969,14 +821,4 @@ void ComputerManager::addNewHost(NvAddress address, bool mdns, NvAddress mdnsIpv
QThreadPool::globalInstance()->start(addTask); QThreadPool::globalInstance()->start(addTask);
} }
// TODO: Use QRandomGenerator when we drop Qt 5.9 support
QString ComputerManager::generatePinString()
{
std::uniform_int_distribution<int> dist(0, 9999);
std::random_device rd;
std::mt19937 engine(rd());
return QString::asprintf("%04u", dist(engine));
}
#include "computermanager.moc" #include "computermanager.moc"
+6 -51
View File
@@ -15,38 +15,17 @@
#include <QSettings> #include <QSettings>
#include <QRunnable> #include <QRunnable>
#include <QTimer> #include <QTimer>
#include <QMutex>
#include <QWaitCondition>
class ComputerManager;
class DelayedFlushThread : public QThread
{
Q_OBJECT
public:
DelayedFlushThread(ComputerManager* cm)
: m_ComputerManager(cm)
{
setObjectName("CM Delayed Flush Thread");
}
void run();
private:
ComputerManager* m_ComputerManager;
};
class MdnsPendingComputer : public QObject class MdnsPendingComputer : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit MdnsPendingComputer(const QSharedPointer<QMdnsEngine::Server> server, explicit MdnsPendingComputer(QMdnsEngine::Server* server,
const QMdnsEngine::Service& service) const QMdnsEngine::Service& service)
: m_Hostname(service.hostname()), : m_Hostname(service.hostname()),
m_Port(service.port()), m_Port(service.port()),
m_ServerWeak(server), m_Server(server),
m_Resolver(nullptr) m_Resolver(nullptr)
{ {
// Start resolving // Start resolving
@@ -94,21 +73,8 @@ signals:
private: private:
void resolve() void resolve()
{ {
// Delete our resolver, so we're guaranteed that nothing is referencing m_Server.
delete m_Resolver; delete m_Resolver;
m_Resolver = nullptr; m_Resolver = new QMdnsEngine::Resolver(m_Server, m_Hostname);
// Now delete our strong reference that we held on behalf of m_Resolver.
// The server may be destroyed after we make this call.
m_Server.reset();
// Re-acquire a strong reference if the server still exists.
m_Server = m_ServerWeak.toStrongRef();
if (!m_Server) {
return;
}
m_Resolver = new QMdnsEngine::Resolver(m_Server.data(), m_Hostname);
connect(m_Resolver, &QMdnsEngine::Resolver::resolved, connect(m_Resolver, &QMdnsEngine::Resolver::resolved,
this, &MdnsPendingComputer::handleResolvedAddress); this, &MdnsPendingComputer::handleResolvedAddress);
QTimer::singleShot(2000, this, &MdnsPendingComputer::handleResolvedTimeout); QTimer::singleShot(2000, this, &MdnsPendingComputer::handleResolvedTimeout);
@@ -116,8 +82,7 @@ private:
QByteArray m_Hostname; QByteArray m_Hostname;
uint16_t m_Port; uint16_t m_Port;
QWeakPointer<QMdnsEngine::Server> m_ServerWeak; QMdnsEngine::Server* m_Server;
QSharedPointer<QMdnsEngine::Server> m_Server;
QMdnsEngine::Resolver* m_Resolver; QMdnsEngine::Resolver* m_Resolver;
QVector<QHostAddress> m_Addresses; QVector<QHostAddress> m_Addresses;
}; };
@@ -201,8 +166,6 @@ class ComputerManager : public QObject
friend class DeferredHostDeletionTask; friend class DeferredHostDeletionTask;
friend class PendingAddTask; friend class PendingAddTask;
friend class PendingPairingTask;
friend class DelayedFlushThread;
public: public:
explicit ComputerManager(QObject *parent = nullptr); explicit ComputerManager(QObject *parent = nullptr);
@@ -217,8 +180,6 @@ public:
void addNewHost(NvAddress address, bool mdns, NvAddress mdnsIpv6Address = NvAddress()); void addNewHost(NvAddress address, bool mdns, NvAddress mdnsIpv6Address = NvAddress());
QString generatePinString();
void pairHost(NvComputer* computer, QString pin); void pairHost(NvComputer* computer, QString pin);
void quitRunningApp(NvComputer* computer); void quitRunningApp(NvComputer* computer);
@@ -251,8 +212,6 @@ private slots:
private: private:
void saveHosts(); void saveHosts();
void saveHost(NvComputer* computer);
QHostAddress getBestGlobalAddressV6(QVector<QHostAddress>& addresses); QHostAddress getBestGlobalAddressV6(QVector<QHostAddress>& addresses);
void startPollingComputer(NvComputer* computer); void startPollingComputer(NvComputer* computer);
@@ -261,13 +220,9 @@ private:
QReadWriteLock m_Lock; QReadWriteLock m_Lock;
QMap<QString, NvComputer*> m_KnownHosts; QMap<QString, NvComputer*> m_KnownHosts;
QMap<QString, ComputerPollingEntry*> m_PollEntries; QMap<QString, ComputerPollingEntry*> m_PollEntries;
QHash<QString, NvComputer> m_LastSerializedHosts; // Protected by m_DelayedFlushMutex QMdnsEngine::Server m_MdnsServer;
QSharedPointer<QMdnsEngine::Server> m_MdnsServer;
QMdnsEngine::Browser* m_MdnsBrowser; QMdnsEngine::Browser* m_MdnsBrowser;
QMdnsEngine::Cache m_MdnsCache;
QVector<MdnsPendingComputer*> m_PendingResolution; QVector<MdnsPendingComputer*> m_PendingResolution;
CompatFetcher m_CompatFetcher; CompatFetcher m_CompatFetcher;
DelayedFlushThread* m_DelayedFlushThread;
QMutex m_DelayedFlushMutex; // Lock ordering: Must never be acquired while holding NvComputer lock
QWaitCondition m_DelayedFlushCondition;
bool m_NeedsDelayedFlush;
}; };
+54 -146
View File
@@ -21,7 +21,6 @@
#define SER_APPLIST "apps" #define SER_APPLIST "apps"
#define SER_SRVCERT "srvcert" #define SER_SRVCERT "srvcert"
#define SER_CUSTOMNAME "customname" #define SER_CUSTOMNAME "customname"
#define SER_NVIDIASOFTWARE "nvidiasw"
NvComputer::NvComputer(QSettings& settings) NvComputer::NvComputer(QSettings& settings)
{ {
@@ -38,7 +37,6 @@ NvComputer::NvComputer(QSettings& settings)
this->manualAddress = NvAddress(settings.value(SER_MANUALADDR).toString(), this->manualAddress = NvAddress(settings.value(SER_MANUALADDR).toString(),
settings.value(SER_MANUALPORT, QVariant(DEFAULT_HTTP_PORT)).toUInt()); settings.value(SER_MANUALPORT, QVariant(DEFAULT_HTTP_PORT)).toUInt());
this->serverCert = QSslCertificate(settings.value(SER_SRVCERT).toByteArray()); this->serverCert = QSslCertificate(settings.value(SER_SRVCERT).toByteArray());
this->isNvidiaServerSoftware = settings.value(SER_NVIDIASOFTWARE).toBool();
int appCount = settings.beginReadArray(SER_APPLIST); int appCount = settings.beginReadArray(SER_APPLIST);
this->appList.reserve(appCount); this->appList.reserve(appCount);
@@ -67,14 +65,12 @@ NvComputer::NvComputer(QSettings& settings)
void NvComputer::setRemoteAddress(QHostAddress address) void NvComputer::setRemoteAddress(QHostAddress address)
{ {
QWriteLocker lock(&this->lock);
Q_ASSERT(this->externalPort != 0); Q_ASSERT(this->externalPort != 0);
this->remoteAddress = NvAddress(address, this->externalPort); this->remoteAddress = NvAddress(address, this->externalPort);
} }
void NvComputer::serialize(QSettings& settings, bool serializeApps) const void NvComputer::serialize(QSettings& settings) const
{ {
QReadLocker lock(&this->lock); QReadLocker lock(&this->lock);
@@ -91,10 +87,9 @@ void NvComputer::serialize(QSettings& settings, bool serializeApps) const
settings.setValue(SER_MANUALADDR, manualAddress.address()); settings.setValue(SER_MANUALADDR, manualAddress.address());
settings.setValue(SER_MANUALPORT, manualAddress.port()); settings.setValue(SER_MANUALPORT, manualAddress.port());
settings.setValue(SER_SRVCERT, serverCert.toPem()); settings.setValue(SER_SRVCERT, serverCert.toPem());
settings.setValue(SER_NVIDIASOFTWARE, isNvidiaServerSoftware);
// Avoid deleting an existing applist if we couldn't get one // Avoid deleting an existing applist if we couldn't get one
if (!appList.isEmpty() && serializeApps) { if (!appList.isEmpty()) {
settings.remove(SER_APPLIST); settings.remove(SER_APPLIST);
settings.beginWriteArray(SER_APPLIST); settings.beginWriteArray(SER_APPLIST);
for (int i = 0; i < appList.count(); i++) { for (int i = 0; i < appList.count(); i++) {
@@ -105,21 +100,6 @@ void NvComputer::serialize(QSettings& settings, bool serializeApps) const
} }
} }
bool NvComputer::isEqualSerialized(const NvComputer &that) const
{
return this->name == that.name &&
this->hasCustomName == that.hasCustomName &&
this->uuid == that.uuid &&
this->macAddress == that.macAddress &&
this->localAddress == that.localAddress &&
this->remoteAddress == that.remoteAddress &&
this->ipv6Address == that.ipv6Address &&
this->manualAddress == that.manualAddress &&
this->serverCert == that.serverCert &&
this->isNvidiaServerSoftware == that.isNvidiaServerSoftware &&
this->appList == that.appList;
}
void NvComputer::sortAppList() void NvComputer::sortAppList()
{ {
std::stable_sort(appList.begin(), appList.end(), [](const NvApp& app1, const NvApp& app2) { std::stable_sort(appList.begin(), appList.end(), [](const NvApp& app1, const NvApp& app2) {
@@ -151,8 +131,7 @@ NvComputer::NvComputer(NvHTTP& http, QString serverInfo)
this->serverCodecModeSupport = codecSupport.toInt(); this->serverCodecModeSupport = codecSupport.toInt();
} }
else { else {
// Assume H.264 is always supported this->serverCodecModeSupport = 0;
this->serverCodecModeSupport = SCM_H264;
} }
QString maxLumaPixelsHEVC = NvHTTP::getXmlString(serverInfo, "MaxLumaPixelsHEVC"); QString maxLumaPixelsHEVC = NvHTTP::getXmlString(serverInfo, "MaxLumaPixelsHEVC");
@@ -166,8 +145,8 @@ NvComputer::NvComputer(NvHTTP& http, QString serverInfo)
this->displayModes = NvHTTP::getDisplayModeList(serverInfo); this->displayModes = NvHTTP::getDisplayModeList(serverInfo);
std::stable_sort(this->displayModes.begin(), this->displayModes.end(), std::stable_sort(this->displayModes.begin(), this->displayModes.end(),
[](const NvDisplayMode& mode1, const NvDisplayMode& mode2) { [](const NvDisplayMode& mode1, const NvDisplayMode& mode2) {
return (uint64_t)mode1.width * mode1.height * mode1.refreshRate < return mode1.width * mode1.height * mode1.refreshRate <
(uint64_t)mode2.width * mode2.height * mode2.refreshRate; mode2.width * mode2.height * mode2.refreshRate;
}); });
// We can get an IPv4 loopback address if we're using the GS IPv6 Forwarder // We can get an IPv4 loopback address if we're using the GS IPv6 Forwarder
@@ -185,7 +164,7 @@ NvComputer::NvComputer(NvHTTP& http, QString serverInfo)
// to support dynamic HTTP WAN ports without requiring the user to manually enter the port. // to support dynamic HTTP WAN ports without requiring the user to manually enter the port.
QString remotePortStr = NvHTTP::getXmlString(serverInfo, "ExternalPort"); QString remotePortStr = NvHTTP::getXmlString(serverInfo, "ExternalPort");
if (remotePortStr.isEmpty() || (this->externalPort = remotePortStr.toUShort()) == 0) { if (remotePortStr.isEmpty() || (this->externalPort = remotePortStr.toUShort()) == 0) {
this->externalPort = http.httpPort(); this->externalPort = DEFAULT_HTTP_PORT;
} }
QString remoteAddress = NvHTTP::getXmlString(serverInfo, "ExternalIP"); QString remoteAddress = NvHTTP::getXmlString(serverInfo, "ExternalIP");
@@ -196,11 +175,6 @@ NvComputer::NvComputer(NvHTTP& http, QString serverInfo)
this->remoteAddress = NvAddress(); this->remoteAddress = NvAddress();
} }
// Real Nvidia host software (GeForce Experience and RTX Experience) both use the 'Mjolnir'
// codename in the state field and no version of Sunshine does. We can use this to bypass
// some assumptions about Nvidia hardware that don't apply to Sunshine hosts.
this->isNvidiaServerSoftware = NvHTTP::getXmlString(serverInfo, "state").contains("MJOLNIR");
this->pairState = NvHTTP::getXmlString(serverInfo, "PairStatus") == "1" ? this->pairState = NvHTTP::getXmlString(serverInfo, "PairStatus") == "1" ?
PS_PAIRED : PS_NOT_PAIRED; PS_PAIRED : PS_NOT_PAIRED;
this->currentGameId = NvHTTP::getCurrentGame(serverInfo); this->currentGameId = NvHTTP::getCurrentGame(serverInfo);
@@ -213,52 +187,40 @@ NvComputer::NvComputer(NvHTTP& http, QString serverInfo)
this->isSupportedServerVersion = CompatFetcher::isGfeVersionSupported(this->gfeVersion); this->isSupportedServerVersion = CompatFetcher::isGfeVersionSupported(this->gfeVersion);
} }
bool NvComputer::wake() const bool NvComputer::wake()
{ {
QByteArray wolPayload; if (state == NvComputer::CS_ONLINE) {
qWarning() << name << "is already online";
{ return true;
QReadLocker readLocker(&lock);
if (state == NvComputer::CS_ONLINE) {
qWarning() << name << "is already online";
return true;
}
if (macAddress.isEmpty()) {
qWarning() << name << "has no MAC address stored";
return false;
}
// Create the WoL payload
wolPayload.append(QByteArray::fromHex("FFFFFFFFFFFF"));
for (int i = 0; i < 16; i++) {
wolPayload.append(macAddress);
}
Q_ASSERT(wolPayload.size() == 102);
} }
// Ports used as-is if (macAddress.isEmpty()) {
const quint16 STATIC_WOL_PORTS[] = { qWarning() << name << "has no MAC address stored";
return false;
}
const quint16 WOL_PORTS[] = {
9, // Standard WOL port (privileged port) 9, // Standard WOL port (privileged port)
47998, 47999, 48000, 48002, 48010, // Ports opened by GFE
47009, // Port opened by Moonlight Internet Hosting Tool for WoL (non-privileged port) 47009, // Port opened by Moonlight Internet Hosting Tool for WoL (non-privileged port)
}; };
// Ports offset by the HTTP base port for hosts using alternate ports // Create the WoL payload
const quint16 DYNAMIC_WOL_PORTS[] = { QByteArray wolPayload;
47998, 47999, 48000, 48002, 48010, // Ports opened by GFE wolPayload.append(QByteArray::fromHex("FFFFFFFFFFFF"));
}; for (int i = 0; i < 16; i++) {
wolPayload.append(macAddress);
}
Q_ASSERT(wolPayload.count() == 102);
// Add the addresses that we know this host to be // Add the addresses that we know this host to be
// and broadcast addresses for this link just in // and broadcast addresses for this link just in
// case the host has timed out in ARP entries. // case the host has timed out in ARP entries.
QMap<QString, quint16> addressMap; QVector<QString> addressList;
QSet<quint16> basePortSet;
for (const NvAddress& addr : uniqueAddresses()) { for (const NvAddress& addr : uniqueAddresses()) {
addressMap.insert(addr.address(), addr.port()); addressList.append(addr.address());
basePortSet.insert(addr.port());
} }
addressMap.insert("255.255.255.255", 0); addressList.append("255.255.255.255");
// Try to broadcast on all available NICs // Try to broadcast on all available NICs
for (const QNetworkInterface& nic : QNetworkInterface::allInterfaces()) { for (const QNetworkInterface& nic : QNetworkInterface::allInterfaces()) {
@@ -277,42 +239,31 @@ bool NvComputer::wake() const
// Skip IPv6 which doesn't support broadcast // Skip IPv6 which doesn't support broadcast
if (!addr.broadcast().isNull()) { if (!addr.broadcast().isNull()) {
addressMap.insert(addr.broadcast().toString(), 0); addressList.append(addr.broadcast().toString());
} }
} }
if (!allNodesMulticast.scopeId().isEmpty()) { if (!allNodesMulticast.scopeId().isEmpty()) {
addressMap.insert(allNodesMulticast.toString(), 0); addressList.append(allNodesMulticast.toString());
} }
} }
// Try all unique address strings or host names // Try all unique address strings or host names
bool success = false; bool success = false;
for (auto i = addressMap.constBegin(); i != addressMap.constEnd(); i++) { for (QString& addressString : addressList) {
QHostAddress literalAddress; QHostInfo hostInfo = QHostInfo::fromName(addressString);
QList<QHostAddress> addressList;
// If this is an IPv4/IPv6 literal, don't use QHostInfo::fromName() because that will if (hostInfo.error() != QHostInfo::NoError) {
// try to perform a reverse DNS lookup that leads to delays sending WoL packets. qWarning() << "Error resolving" << addressString << ":" << hostInfo.errorString();
if (literalAddress.setAddress(i.key())) { continue;
addressList.append(literalAddress);
}
else {
QHostInfo hostInfo = QHostInfo::fromName(i.key());
if (hostInfo.error() != QHostInfo::NoError) {
qWarning() << "Error resolving" << i.key() << ":" << hostInfo.errorString();
continue;
}
addressList.append(hostInfo.addresses());
} }
// Try all IP addresses that this string resolves to // Try all IP addresses that this string resolves to
for (QHostAddress& address : addressList) { for (QHostAddress& address : hostInfo.addresses()) {
QUdpSocket sock; QUdpSocket sock;
// Send to all static ports // Send to all ports
for (quint16 port : STATIC_WOL_PORTS) { for (quint16 port : WOL_PORTS) {
if (sock.writeDatagram(wolPayload, address, port)) { if (sock.writeDatagram(wolPayload, address, port)) {
qInfo().nospace().noquote() << "Sent WoL packet to " << name << " via " << address.toString() << ":" << port; qInfo().nospace().noquote() << "Sent WoL packet to " << name << " via " << address.toString() << ":" << port;
success = true; success = true;
@@ -321,56 +272,22 @@ bool NvComputer::wake() const
qWarning() << "Send failed:" << sock.error(); qWarning() << "Send failed:" << sock.error();
} }
} }
QList<quint16> basePorts;
if (i.value() != 0) {
// If we have a known base port for this address, use only that port
basePorts.append(i.value());
}
else {
// If this is a broadcast address without a known HTTP port, try all of them
basePorts.append(basePortSet.values());
}
// Send to all dynamic ports using the HTTP port offset(s) for this address
for (quint16 basePort : basePorts) {
for (quint16 port : DYNAMIC_WOL_PORTS) {
port = (port - 47989) + basePort;
if (sock.writeDatagram(wolPayload, address, port)) {
qInfo().nospace().noquote() << "Sent WoL packet to " << name << " via " << address.toString() << ":" << port;
success = true;
}
else {
qWarning() << "Send failed:" << sock.error();
}
}
}
} }
} }
return success; return success;
} }
NvComputer::ReachabilityType NvComputer::getActiveAddressReachability() const bool NvComputer::isReachableOverVpn()
{ {
NvAddress copyOfActiveAddress; if (activeAddress.isNull()) {
return false;
{
QReadLocker readLocker(&lock);
if (activeAddress.isNull()) {
return ReachabilityType::RI_UNKNOWN;
}
// Grab a copy of the active address to avoid having to hold
// the computer lock while doing socket operations
copyOfActiveAddress = activeAddress;
} }
QTcpSocket s; QTcpSocket s;
s.setProxy(QNetworkProxy::NoProxy); s.setProxy(QNetworkProxy::NoProxy);
s.connectToHost(copyOfActiveAddress.address(), copyOfActiveAddress.port()); s.connectToHost(activeAddress.address(), activeAddress.port());
if (s.waitForConnected(3000)) { if (s.waitForConnected(3000)) {
Q_ASSERT(!s.localAddress().isNull()); Q_ASSERT(!s.localAddress().isNull());
@@ -391,55 +308,48 @@ NvComputer::ReachabilityType NvComputer::getActiveAddressReachability() const
if (nic.type() == QNetworkInterface::Virtual || if (nic.type() == QNetworkInterface::Virtual ||
nic.type() == QNetworkInterface::Ppp) { nic.type() == QNetworkInterface::Ppp) {
// Treat PPP and virtual interfaces as likely VPNs // Treat PPP and virtual interfaces as likely VPNs
return ReachabilityType::RI_VPN; return true;
} }
if (nic.maximumTransmissionUnit() != 0 && nic.maximumTransmissionUnit() < 1500) { if (nic.maximumTransmissionUnit() != 0 && nic.maximumTransmissionUnit() < 1500) {
// Treat MTUs under 1500 as likely VPNs // Treat MTUs under 1500 as likely VPNs
return ReachabilityType::RI_VPN; return true;
} }
#endif #endif
if (nic.flags() & QNetworkInterface::IsPointToPoint) { if (nic.flags() & QNetworkInterface::IsPointToPoint) {
// Treat point-to-point links as likely VPNs. // Treat point-to-point links as likely VPNs.
// This check detects OpenVPN on Unix-like OSes. // This check detects OpenVPN on Unix-like OSes.
return ReachabilityType::RI_VPN; return true;
} }
if (nic.hardwareAddress().startsWith("00:FF", Qt::CaseInsensitive)) { if (nic.hardwareAddress().startsWith("00:FF", Qt::CaseInsensitive)) {
// OpenVPN TAP interfaces have a MAC address starting with 00:FF on Windows // OpenVPN TAP interfaces have a MAC address starting with 00:FF on Windows
return ReachabilityType::RI_VPN; return true;
} }
if (nic.humanReadableName().startsWith("ZeroTier")) { if (nic.humanReadableName().startsWith("ZeroTier")) {
// ZeroTier interfaces always start with "ZeroTier" // ZeroTier interfaces always start with "ZeroTier"
return ReachabilityType::RI_VPN; return true;
} }
if (nic.humanReadableName().contains("VPN")) { if (nic.humanReadableName().contains("VPN")) {
// This one is just a final VPN heuristic if all else fails // This one is just a final heuristic if all else fails
return ReachabilityType::RI_VPN; return true;
} }
// Didn't meet any of our VPN heuristics. Let's see if it's on-link. // Didn't meet any of our VPN heuristics
Q_ASSERT(addr.prefixLength() >= 0); return false;
if (addr.prefixLength() >= 0 && s.localAddress().isInSubnet(addr.ip(), addr.prefixLength())) {
return ReachabilityType::RI_LAN;
}
// Default to unknown if nothing else matched
return ReachabilityType::RI_UNKNOWN;
} }
} }
} }
qWarning() << "No match found for address:" << s.localAddress(); qWarning() << "No match found for address:" << s.localAddress();
return ReachabilityType::RI_UNKNOWN; return false;
} }
else { else {
// If we fail to connect, just pretend that it's not a VPN // If we fail to connect, just pretend that it's not a VPN
qWarning() << "Unable to check for reachability within 3 seconds"; return false;
return ReachabilityType::RI_UNKNOWN;
} }
} }
@@ -465,7 +375,6 @@ bool NvComputer::updateAppList(QVector<NvApp> newAppList) {
QVector<NvAddress> NvComputer::uniqueAddresses() const QVector<NvAddress> NvComputer::uniqueAddresses() const
{ {
QReadLocker readLocker(&lock);
QVector<NvAddress> uniqueAddressList; QVector<NvAddress> uniqueAddressList;
// Start with addresses correctly ordered // Start with addresses correctly ordered
@@ -497,7 +406,7 @@ QVector<NvAddress> NvComputer::uniqueAddresses() const
return uniqueAddressList; return uniqueAddressList;
} }
bool NvComputer::update(const NvComputer& that) bool NvComputer::update(NvComputer& that)
{ {
bool changed = false; bool changed = false;
@@ -547,7 +456,6 @@ bool NvComputer::update(const NvComputer& that)
ASSIGN_IF_CHANGED(gfeVersion); ASSIGN_IF_CHANGED(gfeVersion);
ASSIGN_IF_CHANGED(appVersion); ASSIGN_IF_CHANGED(appVersion);
ASSIGN_IF_CHANGED(isSupportedServerVersion); ASSIGN_IF_CHANGED(isSupportedServerVersion);
ASSIGN_IF_CHANGED(isNvidiaServerSoftware);
ASSIGN_IF_CHANGED(maxLumaPixelsHEVC); ASSIGN_IF_CHANGED(maxLumaPixelsHEVC);
ASSIGN_IF_CHANGED(gpuModel); ASSIGN_IF_CHANGED(gpuModel);
ASSIGN_IF_CHANGED_AND_NONNULL(serverCert); ASSIGN_IF_CHANGED_AND_NONNULL(serverCert);
+6 -37
View File
@@ -8,16 +8,6 @@
#include <QSettings> #include <QSettings>
#include <QRunnable> #include <QRunnable>
class CopySafeReadWriteLock : public QReadWriteLock
{
public:
CopySafeReadWriteLock() = default;
// Don't actually copy the QReadWriteLock
CopySafeReadWriteLock(const CopySafeReadWriteLock&) : QReadWriteLock() {}
CopySafeReadWriteLock& operator=(const CopySafeReadWriteLock &) { return *this; }
};
class NvComputer class NvComputer
{ {
friend class PcMonitorThread; friend class PcMonitorThread;
@@ -32,14 +22,6 @@ private:
bool pendingQuit; bool pendingQuit;
public: public:
NvComputer() = default;
// Caller is responsible for synchronizing read access to the other host
NvComputer(const NvComputer&) = default;
// Caller is responsible for synchronizing read access to the other host
NvComputer& operator=(const NvComputer &) = default;
explicit NvComputer(NvHTTP& http, QString serverInfo); explicit NvComputer(NvHTTP& http, QString serverInfo);
explicit NvComputer(QSettings& settings); explicit NvComputer(QSettings& settings);
@@ -48,30 +30,19 @@ public:
setRemoteAddress(QHostAddress); setRemoteAddress(QHostAddress);
bool bool
update(const NvComputer& that); update(NvComputer& that);
bool bool
wake() const; wake();
enum ReachabilityType bool
{ isReachableOverVpn();
RI_UNKNOWN,
RI_LAN,
RI_VPN,
};
ReachabilityType
getActiveAddressReachability() const;
QVector<NvAddress> QVector<NvAddress>
uniqueAddresses() const; uniqueAddresses() const;
void void
serialize(QSettings& settings, bool serializeApps) const; serialize(QSettings& settings) const;
// Caller is responsible for synchronizing read access to both hosts
bool
isEqualSerialized(const NvComputer& that) const;
enum PairState enum PairState
{ {
@@ -112,11 +83,9 @@ public:
QString uuid; QString uuid;
QSslCertificate serverCert; QSslCertificate serverCert;
QVector<NvApp> appList; QVector<NvApp> appList;
bool isNvidiaServerSoftware;
// Remember to update isEqualSerialized() when adding fields here!
// Synchronization // Synchronization
mutable CopySafeReadWriteLock lock; mutable QReadWriteLock lock;
private: private:
uint16_t externalPort; uint16_t externalPort;
+38 -18
View File
@@ -187,15 +187,12 @@ NvHTTP::getServerInfo(NvLogLevel logLevel, bool fastFail)
} }
void void
NvHTTP::startApp(QString verb, NvHTTP::launchApp(int appId,
bool isGfe, PSTREAM_CONFIGURATION streamConfig,
int appId, bool sops,
PSTREAM_CONFIGURATION streamConfig, bool localAudio,
bool sops, int gamepadMask,
bool localAudio, QString& rtspSessionUrl)
int gamepadMask,
bool persistGameControllersOnDisconnect,
QString& rtspSessionUrl)
{ {
int riKeyId; int riKeyId;
@@ -204,26 +201,25 @@ NvHTTP::startApp(QString verb,
QString response = QString response =
openConnectionToString(m_BaseUrlHttps, openConnectionToString(m_BaseUrlHttps,
verb, "launch",
"appid="+QString::number(appId)+ "appid="+QString::number(appId)+
"&mode="+QString::number(streamConfig->width)+"x"+ "&mode="+QString::number(streamConfig->width)+"x"+
QString::number(streamConfig->height)+"x"+ QString::number(streamConfig->height)+"x"+
// Using an FPS value over 60 causes SOPS to default to 720p60, // Using an FPS value over 60 causes SOPS to default to 720p60,
// so force it to 0 to ensure the correct resolution is set. We // so force it to 0 to ensure the correct resolution is set. We
// used to use 60 here but that locked the frame rate to 60 FPS // used to use 60 here but that locked the frame rate to 60 FPS
// on GFE 3.20.3. We don't need this hack for Sunshine. // on GFE 3.20.3.
QString::number((streamConfig->fps > 60 && isGfe) ? 0 : streamConfig->fps)+ QString::number(streamConfig->fps > 60 ? 0 : streamConfig->fps)+
"&additionalStates=1&sops="+QString::number(sops ? 1 : 0)+ "&additionalStates=1&sops="+QString::number(sops ? 1 : 0)+
"&rikey="+QByteArray(streamConfig->remoteInputAesKey, sizeof(streamConfig->remoteInputAesKey)).toHex()+ "&rikey="+QByteArray(streamConfig->remoteInputAesKey, sizeof(streamConfig->remoteInputAesKey)).toHex()+
"&rikeyid="+QString::number(riKeyId)+ "&rikeyid="+QString::number(riKeyId)+
((streamConfig->supportedVideoFormats & VIDEO_FORMAT_MASK_10BIT) ? (streamConfig->enableHdr ?
"&hdrMode=1&clientHdrCapVersion=0&clientHdrCapSupportedFlagsInUint32=0&clientHdrCapMetaDataId=NV_STATIC_METADATA_TYPE_1&clientHdrCapDisplayData=0x0x0x0x0x0x0x0x0x0x0" : "&hdrMode=1&clientHdrCapVersion=0&clientHdrCapSupportedFlagsInUint32=0&clientHdrCapMetaDataId=NV_STATIC_METADATA_TYPE_1&clientHdrCapDisplayData=0x0x0x0x0x0x0x0x0x0x0" :
"")+ "")+
"&localAudioPlayMode="+QString::number(localAudio ? 1 : 0)+ "&localAudioPlayMode="+QString::number(localAudio ? 1 : 0)+
"&surroundAudioInfo="+QString::number(SURROUNDAUDIOINFO_FROM_AUDIO_CONFIGURATION(streamConfig->audioConfiguration))+ "&surroundAudioInfo="+QString::number(SURROUNDAUDIOINFO_FROM_AUDIO_CONFIGURATION(streamConfig->audioConfiguration))+
"&remoteControllersBitmap="+QString::number(gamepadMask)+ "&remoteControllersBitmap="+QString::number(gamepadMask)+
"&gcmap="+QString::number(gamepadMask)+ "&gcmap="+QString::number(gamepadMask),
"&gcpersist="+QString::number(persistGameControllersOnDisconnect ? 1 : 0),
LAUNCH_TIMEOUT_MS); LAUNCH_TIMEOUT_MS);
qInfo() << "Launch response:" << response; qInfo() << "Launch response:" << response;
@@ -234,6 +230,30 @@ NvHTTP::startApp(QString verb,
rtspSessionUrl = getXmlString(response, "sessionUrl0"); rtspSessionUrl = getXmlString(response, "sessionUrl0");
} }
void
NvHTTP::resumeApp(PSTREAM_CONFIGURATION streamConfig, QString& rtspSessionUrl)
{
int riKeyId;
memcpy(&riKeyId, streamConfig->remoteInputAesIv, sizeof(riKeyId));
riKeyId = qFromBigEndian(riKeyId);
QString response =
openConnectionToString(m_BaseUrlHttps,
"resume",
"rikey="+QString(QByteArray(streamConfig->remoteInputAesKey, sizeof(streamConfig->remoteInputAesKey)).toHex())+
"&rikeyid="+QString::number(riKeyId)+
"&surroundAudioInfo="+QString::number(SURROUNDAUDIOINFO_FROM_AUDIO_CONFIGURATION(streamConfig->audioConfiguration)),
RESUME_TIMEOUT_MS);
qInfo() << "Resume response:" << response;
// Throws if the request failed
verifyResponseStatus(response);
rtspSessionUrl = getXmlString(response, "sessionUrl0");
}
void void
NvHTTP::quitApp() NvHTTP::quitApp()
{ {
@@ -249,7 +269,7 @@ NvHTTP::quitApp()
verifyResponseStatus(response); verifyResponseStatus(response);
// Newer GFE versions will just return success even if quitting fails // Newer GFE versions will just return success even if quitting fails
// if we're not the original requester. // if we're not the original requestor.
if (getCurrentGame(getServerInfo(NvHTTP::NVLL_ERROR)) != 0) { if (getCurrentGame(getServerInfo(NvHTTP::NVLL_ERROR)) != 0) {
// Generate a synthetic GfeResponseException letting the caller know // Generate a synthetic GfeResponseException letting the caller know
// that they can't kill someone else's stream. // that they can't kill someone else's stream.
@@ -362,7 +382,7 @@ NvHTTP::verifyResponseStatus(QString xml)
} }
} }
throw GfeHttpResponseException(-1, "Malformed XML (missing root element)"); throw GfeHttpResponseException(-1, "Malformed GFE XML (missing root element)");
} }
QImage QImage
@@ -531,7 +551,7 @@ NvHTTP::openConnection(QUrl baseUrl,
if (reply->error() != QNetworkReply::NoError) if (reply->error() != QNetworkReply::NoError)
{ {
if (logLevel >= NvLogLevel::NVLL_ERROR) { if (logLevel >= NvLogLevel::NVLL_ERROR) {
qWarning() << command << "request failed with error:" << reply->error(); qWarning() << command << " request failed with error " << reply->error();
} }
if (reply->error() == QNetworkReply::SslHandshakeFailedError) { if (reply->error() == QNetworkReply::SslHandshakeFailedError) {
+10 -9
View File
@@ -162,15 +162,16 @@ public:
quitApp(); quitApp();
void void
startApp(QString verb, resumeApp(PSTREAM_CONFIGURATION streamConfig,
bool isGfe, QString& rtspSessionUrl);
int appId,
PSTREAM_CONFIGURATION streamConfig, void
bool sops, launchApp(int appId,
bool localAudio, PSTREAM_CONFIGURATION streamConfig,
int gamepadMask, bool sops,
bool persistGameControllersOnDisconnect, bool localAudio,
QString& rtspSessionUrl); int gamepadMask,
QString& rtspSessionUrl);
QVector<NvApp> QVector<NvApp>
getAppList(); getAppList();
+32 -21
View File
@@ -2,7 +2,6 @@
#include "utils.h" #include "utils.h"
#include <QGuiApplication> #include <QGuiApplication>
#include <QLibraryInfo>
#include "streaming/session.h" #include "streaming/session.h"
#include "streaming/streamutils.h" #include "streaming/streamutils.h"
@@ -18,7 +17,6 @@ SystemProperties::SystemProperties()
hasDesktopEnvironment = WMUtils::isRunningDesktopEnvironment(); hasDesktopEnvironment = WMUtils::isRunningDesktopEnvironment();
isRunningWayland = WMUtils::isRunningWayland(); isRunningWayland = WMUtils::isRunningWayland();
isRunningXWayland = isRunningWayland && QGuiApplication::platformName() == "xcb"; isRunningXWayland = isRunningWayland && QGuiApplication::platformName() == "xcb";
usesMaterial3Theme = QLibraryInfo::version() >= QVersionNumber(6, 5, 0);
QString nativeArch = QSysInfo::currentCpuArchitecture(); QString nativeArch = QSysInfo::currentCpuArchitecture();
#ifdef Q_OS_WIN32 #ifdef Q_OS_WIN32
@@ -72,22 +70,23 @@ SystemProperties::SystemProperties()
// and cache the results to speed up future queries on this data. // and cache the results to speed up future queries on this data.
querySdlVideoInfo(); querySdlVideoInfo();
Q_ASSERT(!monitorRefreshRates.isEmpty()); Q_ASSERT(maximumStreamingFrameRate >= 60);
Q_ASSERT(!monitorDesktopResolutions.isEmpty());
Q_ASSERT(!monitorNativeResolutions.isEmpty()); Q_ASSERT(!monitorNativeResolutions.isEmpty());
} }
QRect SystemProperties::getDesktopResolution(int displayIndex)
{
// Returns default constructed QRect if out of bounds
return monitorDesktopResolutions.value(displayIndex);
}
QRect SystemProperties::getNativeResolution(int displayIndex) QRect SystemProperties::getNativeResolution(int displayIndex)
{ {
// Returns default constructed QRect if out of bounds // Returns default constructed QRect if out of bounds
return monitorNativeResolutions.value(displayIndex); return monitorNativeResolutions.value(displayIndex);
} }
int SystemProperties::getRefreshRate(int displayIndex)
{
// Returns 0 if out of bounds
return monitorRefreshRates.value(displayIndex);
}
class QuerySdlVideoThread : public QThread class QuerySdlVideoThread : public QThread
{ {
public: public:
@@ -194,13 +193,35 @@ void SystemProperties::refreshDisplaysInternal()
return; return;
} }
monitorDesktopResolutions.clear();
monitorNativeResolutions.clear(); monitorNativeResolutions.clear();
// Never let the maximum drop below 60 FPS
maximumStreamingFrameRate = 60;
SDL_DisplayMode bestMode; SDL_DisplayMode bestMode;
for (int displayIndex = 0; displayIndex < SDL_GetNumVideoDisplays(); displayIndex++) { for (int displayIndex = 0; displayIndex < SDL_GetNumVideoDisplays(); displayIndex++) {
SDL_DisplayMode desktopMode; SDL_DisplayMode desktopMode;
int err;
if (StreamUtils::getNativeDesktopMode(displayIndex, &desktopMode)) { err = SDL_GetDesktopDisplayMode(displayIndex, &desktopMode);
if (err == 0) {
if (desktopMode.w <= 8192 && desktopMode.h <= 8192) {
monitorDesktopResolutions.insert(displayIndex, QRect(0, 0, desktopMode.w, desktopMode.h));
}
else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
"Skipping resolution over 8K: %dx%d",
desktopMode.w, desktopMode.h);
}
}
else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_GetDesktopDisplayMode() failed: %s",
SDL_GetError());
}
if (StreamUtils::getRealDesktopMode(displayIndex, &desktopMode)) {
if (desktopMode.w <= 8192 && desktopMode.h <= 8192) { if (desktopMode.w <= 8192 && desktopMode.h <= 8192) {
monitorNativeResolutions.insert(displayIndex, QRect(0, 0, desktopMode.w, desktopMode.h)); monitorNativeResolutions.insert(displayIndex, QRect(0, 0, desktopMode.w, desktopMode.h));
} }
@@ -223,17 +244,7 @@ void SystemProperties::refreshDisplaysInternal()
} }
} }
// Try to normalize values around our our standard refresh rates. maximumStreamingFrameRate = qMax(maximumStreamingFrameRate, bestMode.refresh_rate);
// Some displays/OSes report values that are slightly off.
if (bestMode.refresh_rate >= 58 && bestMode.refresh_rate <= 62) {
monitorRefreshRates.append(60);
}
else if (bestMode.refresh_rate >= 28 && bestMode.refresh_rate <= 32) {
monitorRefreshRates.append(30);
}
else {
monitorRefreshRates.append(bestMode.refresh_rate);
}
} }
} }
+4 -4
View File
@@ -23,14 +23,14 @@ public:
Q_PROPERTY(bool hasBrowser MEMBER hasBrowser CONSTANT) Q_PROPERTY(bool hasBrowser MEMBER hasBrowser CONSTANT)
Q_PROPERTY(bool hasDiscordIntegration MEMBER hasDiscordIntegration CONSTANT) Q_PROPERTY(bool hasDiscordIntegration MEMBER hasDiscordIntegration CONSTANT)
Q_PROPERTY(QString unmappedGamepads MEMBER unmappedGamepads NOTIFY unmappedGamepadsChanged) Q_PROPERTY(QString unmappedGamepads MEMBER unmappedGamepads NOTIFY unmappedGamepadsChanged)
Q_PROPERTY(int maximumStreamingFrameRate MEMBER maximumStreamingFrameRate CONSTANT)
Q_PROPERTY(QSize maximumResolution MEMBER maximumResolution CONSTANT) Q_PROPERTY(QSize maximumResolution MEMBER maximumResolution CONSTANT)
Q_PROPERTY(QString versionString MEMBER versionString CONSTANT) Q_PROPERTY(QString versionString MEMBER versionString CONSTANT)
Q_PROPERTY(bool supportsHdr MEMBER supportsHdr CONSTANT) Q_PROPERTY(bool supportsHdr MEMBER supportsHdr CONSTANT)
Q_PROPERTY(bool usesMaterial3Theme MEMBER usesMaterial3Theme CONSTANT)
Q_INVOKABLE void refreshDisplays(); Q_INVOKABLE void refreshDisplays();
Q_INVOKABLE QRect getDesktopResolution(int displayIndex);
Q_INVOKABLE QRect getNativeResolution(int displayIndex); Q_INVOKABLE QRect getNativeResolution(int displayIndex);
Q_INVOKABLE int getRefreshRate(int displayIndex);
signals: signals:
void unmappedGamepadsChanged(); void unmappedGamepadsChanged();
@@ -50,11 +50,11 @@ private:
bool hasBrowser; bool hasBrowser;
bool hasDiscordIntegration; bool hasDiscordIntegration;
QString unmappedGamepads; QString unmappedGamepads;
int maximumStreamingFrameRate;
QSize maximumResolution; QSize maximumResolution;
QList<QRect> monitorDesktopResolutions;
QList<QRect> monitorNativeResolutions; QList<QRect> monitorNativeResolutions;
QList<int> monitorRefreshRates;
QString versionString; QString versionString;
bool supportsHdr; bool supportsHdr;
bool usesMaterial3Theme;
}; };
-117
View File
@@ -164,10 +164,8 @@ GlobalCommandLineParser::ParseResult GlobalCommandLineParser::parse(const QStrin
"Starts Moonlight normally if no arguments are given.\n" "Starts Moonlight normally if no arguments are given.\n"
"\n" "\n"
"Available actions:\n" "Available actions:\n"
" list List the available apps on a host\n"
" quit Quit the currently running app\n" " quit Quit the currently running app\n"
" stream Start streaming an app\n" " stream Start streaming an app\n"
" pair Pair a new host\n"
"\n" "\n"
"See 'moonlight <action> --help' for help of specific action." "See 'moonlight <action> --help' for help of specific action."
); );
@@ -195,10 +193,6 @@ GlobalCommandLineParser::ParseResult GlobalCommandLineParser::parse(const QStrin
return QuitRequested; return QuitRequested;
} else if (action == "stream") { } else if (action == "stream") {
return StreamRequested; return StreamRequested;
} else if (action == "pair") {
return PairRequested;
} else if (action == "list") {
return ListRequested;
} }
} }
@@ -248,58 +242,6 @@ QString QuitCommandLineParser::getHost() const
return m_Host; return m_Host;
} }
PairCommandLineParser::PairCommandLineParser()
{
}
PairCommandLineParser::~PairCommandLineParser()
{
}
void PairCommandLineParser::parse(const QStringList &args)
{
CommandLineParser parser;
parser.setupCommonOptions();
parser.setApplicationDescription(
"\n"
"Pair with the specified host."
);
parser.addPositionalArgument("pair", "pair host");
parser.addPositionalArgument("host", "Host computer name, UUID, or IP address", "<host>");
parser.addValueOption("pin", "4 digit pairing PIN");
if (!parser.parse(args)) {
parser.showError(parser.errorText());
}
parser.handleUnknownOptions();
// This method will not return and terminates the process if --version or
// --help is specified
parser.handleHelpAndVersionOptions();
// Verify that host has been provided
auto posArgs = parser.positionalArguments();
if (posArgs.length() < 2) {
parser.showError("Host not provided");
}
m_Host = parser.positionalArguments().at(1);
m_PredefinedPin = parser.value("pin");
if (!m_PredefinedPin.isEmpty() && m_PredefinedPin.length() != 4) {
parser.showError("PIN must be 4 digits");
}
}
QString PairCommandLineParser::getHost() const
{
return m_Host;
}
QString PairCommandLineParser::getPredefinedPin() const
{
return m_PredefinedPin;
}
StreamCommandLineParser::StreamCommandLineParser() StreamCommandLineParser::StreamCommandLineParser()
{ {
m_WindowModeMap = { m_WindowModeMap = {
@@ -526,62 +468,3 @@ QString StreamCommandLineParser::getAppName() const
{ {
return m_AppName; return m_AppName;
} }
ListCommandLineParser::ListCommandLineParser()
{
}
ListCommandLineParser::~ListCommandLineParser()
{
}
void ListCommandLineParser::parse(const QStringList &args)
{
CommandLineParser parser;
parser.setupCommonOptions();
parser.setApplicationDescription(
"\n"
"List the available apps on the given host."
);
parser.addPositionalArgument("list", "list available apps");
parser.addPositionalArgument("host", "Host computer name, UUID, or IP address", "<host>");
parser.addFlagOption("csv", "Print as CSV with additional information");
parser.addFlagOption("verbose", "Displays additional information");
if (!parser.parse(args)) {
parser.showError(parser.errorText());
}
parser.handleUnknownOptions();
m_PrintCSV = parser.isSet("csv");
m_Verbose = parser.isSet("verbose");
// This method will not return and terminates the process if --version or
// --help is specified
parser.handleHelpAndVersionOptions();
// Verify that host has been provided
auto posArgs = parser.positionalArguments();
if (posArgs.length() < 2) {
parser.showError("Host not provided");
}
m_Host = parser.positionalArguments().at(1);
}
QString ListCommandLineParser::getHost() const
{
return m_Host;
}
bool ListCommandLineParser::isPrintCSV() const
{
return m_PrintCSV;
}
bool ListCommandLineParser::isVerbose() const
{
return m_Verbose;
}
-36
View File
@@ -12,8 +12,6 @@ public:
NormalStartRequested, NormalStartRequested,
StreamRequested, StreamRequested,
QuitRequested, QuitRequested,
PairRequested,
ListRequested,
}; };
GlobalCommandLineParser(); GlobalCommandLineParser();
@@ -37,22 +35,6 @@ private:
QString m_Host; QString m_Host;
}; };
class PairCommandLineParser
{
public:
PairCommandLineParser();
virtual ~PairCommandLineParser();
void parse(const QStringList &args);
QString getHost() const;
QString getPredefinedPin() const;
private:
QString m_Host;
QString m_PredefinedPin;
};
class StreamCommandLineParser class StreamCommandLineParser
{ {
public: public:
@@ -73,21 +55,3 @@ private:
QMap<QString, StreamingPreferences::VideoDecoderSelection> m_VideoDecoderMap; QMap<QString, StreamingPreferences::VideoDecoderSelection> m_VideoDecoderMap;
QMap<QString, StreamingPreferences::CaptureSysKeysMode> m_CaptureSysKeysModeMap; QMap<QString, StreamingPreferences::CaptureSysKeysMode> m_CaptureSysKeysModeMap;
}; };
class ListCommandLineParser
{
public:
ListCommandLineParser();
virtual ~ListCommandLineParser();
void parse(const QStringList &args);
QString getHost() const;
bool isPrintCSV() const;
bool isVerbose() const;
private:
QString m_Host;
bool m_PrintCSV;
bool m_Verbose;
};
-208
View File
@@ -1,208 +0,0 @@
#include "listapps.h"
#include "backend/boxartmanager.h"
#include "backend/computermanager.h"
#include "backend/computerseeker.h"
#include <QCoreApplication>
#include <QTimer>
#define COMPUTER_SEEK_TIMEOUT 10000
#define APP_SEEK_TIMEOUT 10000
namespace CliListApps
{
enum State {
StateInit,
StateSeekComputer,
StateListApp,
StateSeekApp,
StateFailure,
};
class Event
{
public:
enum Type {
ComputerFound,
ComputerUpdated,
ComputerSeekTimedout,
Executed,
};
Event(Type type)
: type(type), computerManager(nullptr), computer(nullptr) {}
Type type;
ComputerManager *computerManager;
NvComputer *computer;
QString errorMessage;
};
class LauncherPrivate
{
Q_DECLARE_PUBLIC(Launcher)
public:
LauncherPrivate(Launcher *q) : q_ptr(q) {}
void handleEvent(Event event)
{
Q_Q(Launcher);
NvApp app;
switch (event.type) {
// Occurs when CLI main calls execute
case Event::Executed:
if (m_State == StateInit) {
m_State = StateSeekComputer;
m_ComputerManager = event.computerManager;
m_ComputerSeeker = new ComputerSeeker(m_ComputerManager, m_ComputerName, q);
q->connect(m_ComputerSeeker, &ComputerSeeker::computerFound,
q, &Launcher::onComputerFound);
q->connect(m_ComputerSeeker, &ComputerSeeker::errorTimeout,
q, &Launcher::onComputerSeekTimeout);
m_ComputerSeeker->start(COMPUTER_SEEK_TIMEOUT);
q->connect(m_ComputerManager, &ComputerManager::computerStateChanged,
q, &Launcher::onComputerUpdated);
m_BoxArtManager = new BoxArtManager(q);
if (m_Arguments.isVerbose()) {
fprintf(stdout, "Establishing connection to PC...\n");
}
}
break;
// Occurs when computer search timed out
case Event::ComputerSeekTimedout:
if (m_State == StateSeekComputer) {
fprintf(stderr, "%s\n", qPrintable(QString("Failed to connect to %1").arg(m_ComputerName)));
QCoreApplication::exit(-1);
}
break;
// Occurs when searched computer is found
case Event::ComputerFound:
if (m_State == StateSeekComputer) {
if (event.computer->pairState == NvComputer::PS_PAIRED) {
m_State = StateSeekApp;
m_Computer = event.computer;
m_TimeoutTimer->start(APP_SEEK_TIMEOUT);
if (m_Arguments.isVerbose()) {
fprintf(stdout, "Loading app list...\n");
}
} else {
m_State = StateFailure;
fprintf(stderr, "%s\n", qPrintable(QObject::tr("Computer %1 has not been paired. "
"Please open Moonlight to pair before retrieving games list.")
.arg(event.computer->name)));
QCoreApplication::exit(-1);
}
}
break;
// Occurs when a computer is updated
case Event::ComputerUpdated:
if (m_State == StateSeekApp) {
m_Arguments.isPrintCSV() ? printAppsCSV(m_Computer->appList) : printApps(m_Computer->appList);
QCoreApplication::exit(0);
}
break;
}
}
void printApps(QVector<NvApp> apps) {
for (int i = 0; i < apps.length(); i++) {
fprintf(stdout, "%s\n", qPrintable(apps[i].name));
}
}
void printAppsCSV(QVector<NvApp> apps) {
fprintf(stdout, "Name, ID, HDR Support, App Collection Game, Hidden, Direct Launch, Boxart URL\n");
for (int i = 0; i < apps.length(); i++) {
printAppCSV(apps[i]);
}
}
void printAppCSV(NvApp app) const
{
fprintf(stdout, "\"%s\",%d,%s,%s,%s,%s,\"%s\"\n", qPrintable(app.name),
app.id,
app.hdrSupported ? "true" : "false",
app.isAppCollectorGame ? "true" : "false",
app.hidden ? "true" : "false",
app.directLaunch ? "true" : "false",
qPrintable(m_BoxArtManager->loadBoxArt(m_Computer, app).toDisplayString()));
}
Launcher *q_ptr;
ComputerManager *m_ComputerManager;
QString m_ComputerName;
ComputerSeeker *m_ComputerSeeker;
BoxArtManager *m_BoxArtManager;
NvComputer *m_Computer;
State m_State;
QTimer *m_TimeoutTimer;
ListCommandLineParser m_Arguments;
};
Launcher::Launcher(QString computer, ListCommandLineParser arguments, QObject *parent)
: QObject(parent),
m_DPtr(new LauncherPrivate(this))
{
Q_D(Launcher);
d->m_ComputerName = computer;
d->m_State = StateInit;
d->m_TimeoutTimer = new QTimer(this);
d->m_TimeoutTimer->setSingleShot(true);
d->m_Arguments = arguments;
connect(d->m_TimeoutTimer, &QTimer::timeout,
this, &Launcher::onComputerSeekTimeout);
}
Launcher::~Launcher()
{
}
void Launcher::execute(ComputerManager *manager)
{
Q_D(Launcher);
Event event(Event::Executed);
event.computerManager = manager;
d->handleEvent(event);
}
bool Launcher::isExecuted() const
{
Q_D(const Launcher);
return d->m_State != StateInit;
}
void Launcher::onComputerFound(NvComputer *computer)
{
Q_D(Launcher);
Event event(Event::ComputerFound);
event.computer = computer;
d->handleEvent(event);
}
void Launcher::onComputerSeekTimeout()
{
Q_D(Launcher);
Event event(Event::ComputerSeekTimedout);
d->handleEvent(event);
}
void Launcher::onComputerUpdated(NvComputer *computer)
{
Q_D(Launcher);
Event event(Event::ComputerUpdated);
event.computer = computer;
d->handleEvent(event);
}
}
-38
View File
@@ -1,38 +0,0 @@
#pragma once
#include "commandlineparser.h"
#include <QObject>
#include <QVariant>
class ComputerManager;
class NvComputer;
namespace CliListApps
{
class LauncherPrivate;
class Launcher : public QObject
{
Q_OBJECT
Q_DECLARE_PRIVATE_D(m_DPtr, Launcher)
public:
explicit Launcher(QString computer, ListCommandLineParser arguments, QObject *parent = nullptr);
~Launcher();
Q_INVOKABLE void execute(ComputerManager *manager);
Q_INVOKABLE bool isExecuted() const;
private slots:
void onComputerFound(NvComputer *computer);
void onComputerUpdated(NvComputer *computer);
void onComputerSeekTimeout();
private:
QScopedPointer<LauncherPrivate> m_DPtr;
ListCommandLineParser m_Arguments;
};
}
-181
View File
@@ -1,181 +0,0 @@
#include "pair.h"
#include "backend/computermanager.h"
#include "backend/computerseeker.h"
#include <QCoreApplication>
#include <QTimer>
#define COMPUTER_SEEK_TIMEOUT 10000
namespace CliPair
{
enum State {
StateInit,
StateSeekComputer,
StatePairing,
StateFailure,
StateComplete,
};
class Event
{
public:
enum Type {
ComputerFound,
Executed,
PairingCompleted,
Timedout,
};
Event(Type type)
: type(type), computerManager(nullptr), computer(nullptr) {}
Type type;
ComputerManager *computerManager;
NvComputer *computer;
QString errorMessage;
};
class LauncherPrivate
{
Q_DECLARE_PUBLIC(Launcher)
public:
LauncherPrivate(Launcher *q) : q_ptr(q) {}
void handleEvent(Event event)
{
Q_Q(Launcher);
switch (event.type) {
// Occurs when CliPair becomes visible and the UI calls launcher's execute()
case Event::Executed:
if (m_State == StateInit) {
m_State = StateSeekComputer;
m_ComputerManager = event.computerManager;
q->connect(m_ComputerManager, &ComputerManager::pairingCompleted,
q, &Launcher::onPairingCompleted);
// If we weren't provided a predefined PIN, generate one now
if (m_PredefinedPin.isEmpty()) {
m_PredefinedPin = m_ComputerManager->generatePinString();
}
m_ComputerSeeker = new ComputerSeeker(m_ComputerManager, m_ComputerName, q);
q->connect(m_ComputerSeeker, &ComputerSeeker::computerFound,
q, &Launcher::onComputerFound);
q->connect(m_ComputerSeeker, &ComputerSeeker::errorTimeout,
q, &Launcher::onTimeout);
m_ComputerSeeker->start(COMPUTER_SEEK_TIMEOUT);
emit q->searchingComputer();
}
break;
// Occurs when searched computer is found
case Event::ComputerFound:
if (m_State == StateSeekComputer) {
if (event.computer->pairState == NvComputer::PS_PAIRED) {
m_State = StateFailure;
QString msg = QObject::tr("%1 is already paired").arg(event.computer->name);
emit q->failed(msg);
}
else {
Q_ASSERT(!m_PredefinedPin.isEmpty());
m_State = StatePairing;
m_ComputerManager->pairHost(event.computer, m_PredefinedPin);
emit q->pairing(event.computer->name, m_PredefinedPin);
}
}
break;
// Occurs when pairing operation completes
case Event::PairingCompleted:
if (m_State == StatePairing) {
if (event.errorMessage.isEmpty()) {
m_State = StateComplete;
emit q->success();
}
else {
m_State = StateFailure;
emit q->failed(event.errorMessage);
}
}
break;
// Occurs when computer search timed out
case Event::Timedout:
if (m_State == StateSeekComputer) {
m_State = StateFailure;
emit q->failed(QObject::tr("Failed to connect to %1").arg(m_ComputerName));
}
break;
}
}
Launcher *q_ptr;
QString m_ComputerName;
QString m_PredefinedPin;
ComputerManager *m_ComputerManager;
ComputerSeeker *m_ComputerSeeker;
NvComputer *m_Computer;
State m_State;
QTimer *m_TimeoutTimer;
};
Launcher::Launcher(QString computer, QString predefinedPin, QObject *parent)
: QObject(parent),
m_DPtr(new LauncherPrivate(this))
{
Q_D(Launcher);
d->m_ComputerName = computer;
d->m_PredefinedPin = predefinedPin;
d->m_State = StateInit;
d->m_TimeoutTimer = new QTimer(this);
d->m_TimeoutTimer->setSingleShot(true);
connect(d->m_TimeoutTimer, &QTimer::timeout,
this, &Launcher::onTimeout);
}
Launcher::~Launcher()
{
}
void Launcher::execute(ComputerManager *manager)
{
Q_D(Launcher);
Event event(Event::Executed);
event.computerManager = manager;
d->handleEvent(event);
}
bool Launcher::isExecuted() const
{
Q_D(const Launcher);
return d->m_State != StateInit;
}
void Launcher::onComputerFound(NvComputer *computer)
{
Q_D(Launcher);
Event event(Event::ComputerFound);
event.computer = computer;
d->handleEvent(event);
}
void Launcher::onTimeout()
{
Q_D(Launcher);
Event event(Event::Timedout);
d->handleEvent(event);
}
void Launcher::onPairingCompleted(NvComputer* computer, QString error)
{
Q_D(Launcher);
Event event(Event::PairingCompleted);
event.computer = computer;
event.errorMessage = error;
d->handleEvent(event);
}
}
-44
View File
@@ -1,44 +0,0 @@
#pragma once
#include <QObject>
#include <QVariant>
class ComputerManager;
class NvComputer;
class Session;
class StreamingPreferences;
namespace CliPair
{
class Event;
class LauncherPrivate;
class Launcher : public QObject
{
Q_OBJECT
Q_DECLARE_PRIVATE_D(m_DPtr, Launcher)
public:
explicit Launcher(QString computer, QString predefinedPin,
QObject *parent = nullptr);
~Launcher();
Q_INVOKABLE void execute(ComputerManager *manager);
Q_INVOKABLE bool isExecuted() const;
signals:
void searchingComputer();
void pairing(QString pcName, QString pin);
void failed(QString text);
void success();
private slots:
void onComputerFound(NvComputer *computer);
void onPairingCompleted(NvComputer *computer, QString error);
void onTimeout();
private:
QScopedPointer<LauncherPrivate> m_DPtr;
};
}
+2 -2
View File
@@ -118,7 +118,7 @@ public:
} }
break; break;
// Occurs when the previous app quit has been completed, handles quitting errors if any // Occurs when the previous app quit has been completed, handles quitting errors if any
// happened. ComputerUpdated event's handler handles session start when previous app has // happended. ComputerUpdated event's handler handles session start when previous app has
// quit. // quit.
case Event::AppQuitCompleted: case Event::AppQuitCompleted:
if (m_State == StateSeekApp && !event.errorMessage.isEmpty()) { if (m_State == StateSeekApp && !event.errorMessage.isEmpty()) {
@@ -162,7 +162,7 @@ public:
QString getCurrentAppName() const QString getCurrentAppName() const
{ {
for (const NvApp& app : m_Computer->appList) { for (NvApp app : m_Computer->appList) {
if (m_Computer->currentGameId == app.id) { if (m_Computer->currentGameId == app.id) {
return app.name; return app.name;
} }
@@ -4,19 +4,21 @@
<metadata_license>CC0-1.0</metadata_license> <metadata_license>CC0-1.0</metadata_license>
<project_license>GPL-3.0+</project_license> <project_license>GPL-3.0+</project_license>
<name>Moonlight</name> <name>Moonlight</name>
<summary>Stream games and other applications from another PC running Sunshine or GeForce Experience</summary> <summary>Play games remotely from your NVIDIA GameStream-enabled PC</summary>
<description> <description>
<p>Moonlight can stream games and other applications from another PC with Sunshine or GeForce Experience software installed.</p> <p>Moonlight can stream games and other applications from a PC with an NVIDIA GeForce GTX/RTX or NVIDIA Quadro GPU and GeForce/Quadro Experience installed.</p>
<p>Features include:</p> <p>Features include:</p>
<ul> <ul>
<li>Streaming at up to 4K resolution</li>
<li>Support for up to 120 FPS streaming (high refresh rate monitor recommended)</li>
<li>Hardware accelerated video decoding with VAAPI, VDPAU, and NVDEC support</li> <li>Hardware accelerated video decoding with VAAPI, VDPAU, and NVDEC support</li>
<li>H.264, HEVC, and AV1 codec support</li>
<li>7.1 surround sound audio support</li> <li>7.1 surround sound audio support</li>
<li>10-point multitouch support</li>
<li>Gamepad support with force feedback for up to 16 players</li>
<li>Support for both pointer capture (for games) and direct mouse control (for remote desktop)</li> <li>Support for both pointer capture (for games) and direct mouse control (for remote desktop)</li>
<li>Support for passing system-wide keyboard shortcuts like Alt+Tab to the host</li> <li>Support for passing system-wide keyboard shortcuts like Alt+Tab to the host</li>
<li>Direct touchscreen mouse control</li>
<li>HEVC support for better video compression efficiency</li>
<li>Gamepad support with force feedback for up to 4 players</li>
</ul> </ul>
</description> </description>
@@ -34,150 +36,6 @@
</screenshots> </screenshots>
<releases> <releases>
<release version="5.0.1" date="2023-11-02">
<description>
<p>Bugfixes:</p>
<ul>
<li>Fixed connection issue streaming from some hosts running GeForce Experience or Sunshine v0.20 and earlier</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="5.0.0" date="2023-10-18">
<description>
<p>New features:</p>
<ul>
<li>Custom FPS values</li>
<li>Streaming using the AV1 codec from Sunshine hosts</li>
<li>Horizontal scrolling with Sunshine hosts</li>
<li>Native multi-touch input with Sunshine hosts</li>
<li>Controller type information is passed to Sunshine for controller type autoselection</li>
<li>Extended features of PS4/PS5 controllers (touchpad, battery state, gyro/accelerometer motion, and RGB LED) are natively passed to Sunshine hosts</li>
<li>Support for up to 16 gamepads with Sunshine hosts</li>
<li>Frame pacing support on Wayland</li>
<li>Host-side processing latency is now displayed in the performance overlay with Sunshine hosts</li>
<li>Window title now includes the PC name when streaming</li>
<li>Alphabetical sorting of the PC list</li>
<li>Updated Play and Stop button design to improve contrast with app box art</li>
<li>The settings page automatically scrolls to the selected element when using keyboard or gamepad navigation</li>
<li>Pressing Share+PS buttons on PS4/PS5 controllers can be used to emulate a clickpad press</li>
<li>Improved audio quality when streaming with a high bitrate from remote hosts</li>
<li>Increased mouse polling rate</li>
</ul>
<p>Behavior Changes:</p>
<ul>
<li>IPv6 addresses must be provided in URL-escaped form. Example: [2001:db8::1234:5678] or [2001:db8::1234:5678]:47989</li>
<li>Default bitrate logic has been adjusted to behave better with custom resolutions and frame rates</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Reduced the frequency of audio underruns (clicks and pops) by increasing audio buffer size</li>
<li>Fixed "Quitting App" message never dismissing in some cases</li>
<li>Fixed parsing IPv6 literals with port numbers</li>
<li>Fixed unnecessary WiFi activity causing stream disruptions</li>
<li>Fixed paired hosts being forgotten if Moonlight terminates while writing hosts to disk</li>
<li>Fixed freeze when closing the stream on Windows with some software that uses DX11 hooks</li>
<li>Fixed delayed PC wake when activating Wake-On-LAN feature</li>
<li>Fixed Wake-on-LAN when Sunshine is running on alternate ports</li>
<li>Fixed leak of /dev/dri fds when trying to initialize VAAPI decoder</li>
<li>Fixed support for the Applications/Menu key</li>
<li>Fixed automatic language detection for Simplified Chinese and Traditional Chinese</li>
<li>Fixed streaming from Sunshine when the client PC has multiple network interfaces or IPv6 privacy extensions enabled</li>
<li>Fixed small receive buffer causing video packet loss on some systems</li>
<li>Fixed theme overrides causing the UI to be unusable on some systems</li>
<li>Fixed tearing with V-Sync enabled on macOS and Linux when using the SDL renderer (software decoding and some hardware decoders)</li>
<li>Fixed stateful V4L2 hardware decoding using h264_v4l2m2m and hevc_v4l2m2m decoders</li>
<li>Fixed CVE-2023-42801</li>
<li>Updated included gamepad mappings</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.3.1" date="2022-11-03">
<description>
<p>Changes:</p>
<ul>
<li>Fixed crash during specific patterns of audio packet loss</li>
<li>Fixed detection of local streaming when using IPv6 addresses</li>
<li>Windowed mode streaming now starts maximized if the GUI window was maximized</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.3.0" date="2022-10-28">
<description>
<p>New features:</p>
<ul>
<li>Improved support for GeForce Experience 3.26</li>
<li>Improved image quality and performance when recovering from video packet loss using HEVC</li>
<li>Improved error concealment after audio packet loss</li>
<li>Improved UI performance when paired with many hosts or hosts with large numbers of apps</li>
<li>Pairing with Sunshine hosts is now supported even if the host is in a streaming session</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed streaming at resolutions below 720x480 with GeForce Experience 3.26</li>
<li>Fixed window position and size being lost when toggling between full-screen and windowed mode</li>
<li>Fixed initial window size not always respecting the stream aspect ratio</li>
<li>Fixed unexpected error when streaming at resolutions above 4096x4096 using Sunshine</li>
<li>Updated included gamepad mappings</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.2.1" date="2022-09-12">
<description>
<p>Bugfixes:</p>
<ul>
<li>Fixed streaming from hosts running Sunshine</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.2.0" date="2022-09-10">
<description>
<p>New features:</p>
<ul>
<li>Added support for pairing via the terminal</li>
<li>Added support for listing installed apps on a host via the terminal</li>
<li>Improved handling of V-Sync on Wayland systems to reduce latency</li>
<li>Improved performance using the legacy non-EGL VAAPI rendering code</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed native resolution detection on high DPI Wayland systems</li>
<li>Fixed audio crackling with SDL 2.24.0 on systems using PulseAudio</li>
<li>Updated included gamepad mappings</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.1.0" date="2022-05-23">
<description>
<p>New features:</p>
<ul>
<li>Overlays are now supported on the non-EGL X11 VAAPI renderer (requires RGBA subpicture support in the VAAPI driver)</li>
<li>Cursor lock can now be disabled when in full-screen mode</li>
</ul>
<p>Behavior Changes:</p>
<ul>
<li>Moonlight can now reduce the client display resolution in full-screen mode if the current display mode doesn't have a high enough refresh rate for the selected stream frame rate</li>
<li>When choosing a new client display resolution in full-screen mode, Moonlight will pick a display mode with the closest aspect ratio to the selected stream resolution</li>
<li>Moonlight now defaults to borderless windowed mode on Wayland systems</li>
</ul>
<p>Bugfixes:</p>
<ul>
<li>Fixed missing toolbar buttons in certain languages</li>
<li>Fixed some text on the settings page not updating when the language is changed</li>
<li>Fixed a frame pacing bug that could cause excessive frame drops</li>
<li>Fixed the "keep display awake" setting not being saved when Moonlight restarts</li>
<li>Fixed black screen after unmaximizing the Moonlight window on some Linux systems</li>
<li>Updated included gamepad mappings</li>
<li>Updated community-contributed translations from Weblate</li>
</ul>
</description>
</release>
<release version="4.0.0" date="2022-04-02"> <release version="4.0.0" date="2022-04-02">
<description> <description>
<p>New features:</p> <p>New features:</p>
@@ -1,9 +1,9 @@
[Desktop Entry] [Desktop Entry]
Name=Moonlight Name=Moonlight
Comment=Stream games and other applications from another PC running Sunshine or GeForce Experience Comment=Stream games from your NVIDIA GameStream-enabled PC
Exec=moonlight Exec=moonlight
Icon=moonlight Icon=moonlight
Terminal=false Terminal=false
Type=Application Type=Application
Categories=Qt;Game; Categories=Qt;Game;
Keywords=nvidia;gamestream;stream;sunshine;remote play; Keywords=nvidia;gamestream;stream;
+13 -15
View File
@@ -1,6 +1,5 @@
import QtQuick 2.9 import QtQuick 2.9
import QtQuick.Controls 2.2 import QtQuick.Controls 2.2
import QtQuick.Controls.Material 2.2
import AppModel 1.0 import AppModel 1.0
import ComputerManager 1.0 import ComputerManager 1.0
@@ -90,7 +89,7 @@ CenteredGridView {
onSourceSizeChanged: { onSourceSizeChanged: {
// Nearly all of Nvidia's official box art does not match the dimensions of placeholder // Nearly all of Nvidia's official box art does not match the dimensions of placeholder
// images, however the one known exception is Overcooked. Therefore, we only execute // images, however the one known exeception is Overcooked. Therefore, we only execute
// the image size checks if this is not an app collector game. We know the officially // the image size checks if this is not an app collector game. We know the officially
// supported games all have box art, so this check is not required. // supported games all have box art, so this check is not required.
if (!model.isAppCollectorGame && if (!model.isAppCollectorGame &&
@@ -122,15 +121,15 @@ CenteredGridView {
anchors.fill: appIcon anchors.fill: appIcon
sourceComponent: Item { sourceComponent: Item {
RoundButton { ToolButton {
anchors.horizontalCenterOffset: appIcon.isPlaceholder ? -47 : 0 anchors.horizontalCenterOffset: appIcon.isPlaceholder ? -47 : 0
anchors.verticalCenterOffset: appIcon.isPlaceholder ? -75 : -60 anchors.verticalCenterOffset: appIcon.isPlaceholder ? -75 : -60
anchors.centerIn: parent anchors.centerIn: parent
implicitWidth: 85 implicitWidth: 125
implicitHeight: 85 implicitHeight: 125
Image { Image {
source: "qrc:/res/play_arrow_FILL1_wght700_GRAD200_opsz48.svg" source: "qrc:/res/baseline-play_circle_filled_white-48px.svg"
anchors.centerIn: parent anchors.centerIn: parent
sourceSize { sourceSize {
width: 75 width: 75
@@ -146,19 +145,17 @@ CenteredGridView {
ToolTip.delay: 1000 ToolTip.delay: 1000
ToolTip.timeout: 3000 ToolTip.timeout: 3000
ToolTip.visible: hovered ToolTip.visible: hovered
Material.background: "#D0808080"
} }
RoundButton { ToolButton {
anchors.horizontalCenterOffset: appIcon.isPlaceholder ? 47 : 0 anchors.horizontalCenterOffset: appIcon.isPlaceholder ? 47 : 0
anchors.verticalCenterOffset: appIcon.isPlaceholder ? -75 : 60 anchors.verticalCenterOffset: appIcon.isPlaceholder ? -75 : 60
anchors.centerIn: parent anchors.centerIn: parent
implicitWidth: 85 implicitWidth: 125
implicitHeight: 85 implicitHeight: 125
Image { Image {
source: "qrc:/res/stop_FILL1_wght700_GRAD200_opsz48.svg" source: "qrc:/res/baseline-cancel-24px.svg"
anchors.centerIn: parent anchors.centerIn: parent
sourceSize { sourceSize {
width: 75 width: 75
@@ -174,8 +171,6 @@ CenteredGridView {
ToolTip.delay: 1000 ToolTip.delay: 1000
ToolTip.timeout: 3000 ToolTip.timeout: 3000
ToolTip.visible: hovered ToolTip.visible: hovered
Material.background: "#D0808080"
} }
} }
} }
@@ -350,7 +345,7 @@ CenteredGridView {
function quitApp() { function quitApp() {
var component = Qt.createComponent("QuitSegue.qml") var component = Qt.createComponent("QuitSegue.qml")
var params = {"appName": appName, "quitRunningAppFn": appModel.quitRunningApp} var params = {"appName": appName}
if (segueToStream) { if (segueToStream) {
// Store the session and app name if we're going to stream after // Store the session and app name if we're going to stream after
// successfully quitting the old app. // successfully quitting the old app.
@@ -363,6 +358,9 @@ CenteredGridView {
} }
stackView.push(component.createObject(stackView, params)) stackView.push(component.createObject(stackView, params))
// Trigger the quit after pushing the quit segue on screen
appModel.quitRunningApp()
} }
onAccepted: quitApp() onAccepted: quitApp()
-7
View File
@@ -2,7 +2,6 @@ import QtQuick 2.9
import QtQuick.Controls 2.2 import QtQuick.Controls 2.2
import SdlGamepadKeyNavigation 1.0 import SdlGamepadKeyNavigation 1.0
import SystemProperties 1.0
// https://stackoverflow.com/questions/45029968/how-do-i-set-the-combobox-width-to-fit-the-largest-item // https://stackoverflow.com/questions/45029968/how-do-i-set-the-combobox-width-to-fit-the-largest-item
ComboBox { ComboBox {
@@ -39,12 +38,6 @@ ComboBox {
popup.onAboutToShow: { popup.onAboutToShow: {
// Switch to normal navigation for combo boxes // Switch to normal navigation for combo boxes
SdlGamepadKeyNavigation.setUiNavMode(false) SdlGamepadKeyNavigation.setUiNavMode(false)
// Override the popup color to improve contrast with the overridden
// Material 2 background color set in main.qml.
if (SystemProperties.usesMaterial3Theme) {
popup.background.color = "#424242"
}
} }
popup.onAboutToHide: { popup.onAboutToHide: {
-91
View File
@@ -1,91 +0,0 @@
import QtQuick 2.0
import QtQuick.Controls 2.2
import ComputerManager 1.0
import SdlGamepadKeyNavigation 1.0
Item {
function onSearchingComputer() {
stageLabel.text = qsTr("Establishing connection to PC...")
}
function onPairing(pcName, pin) {
stageLabel.text = qsTr("Pairing... Please enter '%1' on %2.").arg(pin).arg(pcName)
}
function onFailed(message) {
stageIndicator.visible = false
errorDialog.text = message
errorDialog.open()
}
function onSuccess(appName) {
stageIndicator.visible = false
pairCompleteDialog.open()
}
// Allow user to back out of pairing
Keys.onEscapePressed: {
Qt.quit()
}
Keys.onBackPressed: {
Qt.quit()
}
Keys.onCancelPressed: {
Qt.quit()
}
StackView.onActivated: {
if (!launcher.isExecuted()) {
toolBar.visible = false
// Normally this is enabled by PcView, but we will won't
// load PcView when streaming from the command-line.
SdlGamepadKeyNavigation.enable()
launcher.searchingComputer.connect(onSearchingComputer)
launcher.pairing.connect(onPairing)
launcher.failed.connect(onFailed)
launcher.success.connect(onSuccess)
launcher.execute(ComputerManager)
}
}
Row {
anchors.centerIn: parent
spacing: 5
id: stageIndicator
BusyIndicator {
id: stageSpinner
}
Label {
id: stageLabel
height: stageSpinner.height
font.pointSize: 20
verticalAlignment: Text.AlignVCenter
wrapMode: Text.Wrap
}
}
ErrorMessageDialog {
id: errorDialog
onClosed: {
Qt.quit();
}
}
NavigableMessageDialog {
id: pairCompleteDialog
closePolicy: Popup.CloseOnEscape
text:qsTr("Pairing completed successfully")
standardButtons: Dialog.Ok
onClosed: {
Qt.quit()
}
}
}
+3 -2
View File
@@ -26,7 +26,6 @@ Item {
function onLaunchFailed(message) { function onLaunchFailed(message) {
errorDialog.text = message errorDialog.text = message
errorDialog.open() errorDialog.open()
console.error(message)
} }
function onAppQuitRequired(appName) { function onAppQuitRequired(appName) {
@@ -85,8 +84,10 @@ Item {
function quitApp() { function quitApp() {
var component = Qt.createComponent("QuitSegue.qml") var component = Qt.createComponent("QuitSegue.qml")
var params = {"appName": appName, "quitRunningAppFn": launcher.quitRunningApp} var params = {"appName": appName}
stackView.push(component.createObject(stackView, params)) stackView.push(component.createObject(stackView, params))
// Trigger the quit after pushing the quit segue on screen
launcher.quitRunningApp()
} }
onAccepted: quitApp() onAccepted: quitApp()
+29 -26
View File
@@ -99,7 +99,7 @@ CenteredGridView {
Label { Label {
height: searchSpinner.height height: searchSpinner.height
elide: Label.ElideRight elide: Label.ElideRight
text: StreamingPreferences.enableMdns ? qsTr("Searching for compatible hosts on your local network...") text: StreamingPreferences.enableMdns ? qsTr("Searching for PCs on your local network with NVIDIA GameStream enabled...")
: qsTr("Automatic PC discovery is disabled. Add your PC manually.") : qsTr("Automatic PC discovery is disabled. Add your PC manually.")
font.pointSize: 20 font.pointSize: 20
verticalAlignment: Text.AlignVCenter verticalAlignment: Text.AlignVCenter
@@ -130,12 +130,12 @@ CenteredGridView {
id: stateIcon id: stateIcon
anchors.horizontalCenter: pcIcon.horizontalCenter anchors.horizontalCenter: pcIcon.horizontalCenter
anchors.verticalCenter: pcIcon.verticalCenter anchors.verticalCenter: pcIcon.verticalCenter
anchors.verticalCenterOffset: !model.online ? -18 : -16 anchors.verticalCenterOffset: -15
visible: !model.statusUnknown && (!model.online || !model.paired) visible: !model.statusUnknown && (!model.online || !model.paired)
source: !model.online ? "qrc:/res/warning_FILL1_wght300_GRAD200_opsz24.svg" : "qrc:/res/baseline-lock-24px.svg" source: !model.online ? "qrc:/res/baseline-warning-24px.svg" : "qrc:/res/baseline-lock-24px.svg"
sourceSize { sourceSize {
width: !model.online ? 75 : 70 width: 75
height: !model.online ? 75 : 70 height: 75
} }
} }
@@ -211,7 +211,7 @@ CenteredGridView {
text: qsTr("Delete PC") text: qsTr("Delete PC")
onTriggered: { onTriggered: {
deletePcDialog.pcIndex = index deletePcDialog.pcIndex = index
deletePcDialog.pcName = model.name // get confirmation first, actual closing is called from the dialog
deletePcDialog.open() deletePcDialog.open()
} }
} }
@@ -232,14 +232,22 @@ CenteredGridView {
stackView.push(appView) stackView.push(appView)
} }
else { else {
var pin = computerModel.generatePinString() if (!model.busy) {
var pin = computerModel.generatePinString()
// Kick off pairing in the background // Kick off pairing in the background
computerModel.pairComputer(index, pin) computerModel.pairComputer(index, pin)
// Display the pairing dialog // Display the pairing dialog
pairDialog.pin = pin pairDialog.pin = pin
pairDialog.open() pairDialog.open()
}
else {
// cannot pair while something is streaming or attempting to pair
errorDialog.text = qsTr("You cannot pair while a previous session is still running on the host PC. Quit any running games or reboot the host PC, then try pairing again.")
errorDialog.helpText = ""
errorDialog.open()
}
} }
} else if (!model.online) { } else if (!model.online) {
// Using open() here because it may be activated by keyboard // Using open() here because it may be activated by keyboard
@@ -271,12 +279,6 @@ CenteredGridView {
// the ItemDelegate and not where the mouse cursor is // the ItemDelegate and not where the mouse cursor is
pcContextMenu.open() pcContextMenu.open()
} }
Keys.onDeletePressed: {
deletePcDialog.pcIndex = index
deletePcDialog.pcName = model.name
deletePcDialog.open()
}
} }
ErrorMessageDialog { ErrorMessageDialog {
@@ -297,8 +299,7 @@ CenteredGridView {
// don't allow edits to the rest of the window while open // don't allow edits to the rest of the window while open
property string pin : "0000" property string pin : "0000"
text:qsTr("Please enter %1 on your host PC. This dialog will close when pairing is completed.").arg(pin)+"\n\n"+ text:qsTr("Please enter %1 on your GameStream PC. This dialog will close when pairing is completed.").arg(pin)
qsTr("If your host PC is running Sunshine, navigate to the Sunshine web UI to enter the PIN.")
standardButtons: Dialog.Cancel standardButtons: Dialog.Cancel
onRejected: { onRejected: {
// FIXME: We should interrupt pairing here // FIXME: We should interrupt pairing here
@@ -308,14 +309,16 @@ CenteredGridView {
NavigableMessageDialog { NavigableMessageDialog {
id: deletePcDialog id: deletePcDialog
// don't allow edits to the rest of the window while open // don't allow edits to the rest of the window while open
property int pcIndex : -1 property int pcIndex : -1;
property string pcName : "" text:qsTr("Are you sure you want to remove this PC?")
text: qsTr("Are you sure you want to remove '%1'?").arg(pcName)
standardButtons: Dialog.Yes | Dialog.No standardButtons: Dialog.Yes | Dialog.No
onAccepted: { function deletePc() {
computerModel.deleteComputer(pcIndex) console.log("deleting PC pairing for PC at index: " + pcIndex)
computerModel.deleteComputer(pcIndex);
} }
onAccepted: deletePc()
} }
NavigableMessageDialog { NavigableMessageDialog {
@@ -324,7 +327,7 @@ CenteredGridView {
standardButtons: Dialog.Ok standardButtons: Dialog.Ok
onAboutToShow: { onAboutToShow: {
testConnectionDialog.text = qsTr("Moonlight is testing your network connection to determine if any required ports are blocked.") + "\n\n" + qsTr("This may take a few seconds…") testConnectionDialog.text = qsTr("Moonlight is testing your network connection to determine if NVIDIA GameStream is blocked.") + "\n\n" + qsTr("This may take a few seconds…")
showSpinner = true showSpinner = true
} }
-7
View File
@@ -6,7 +6,6 @@ import Session 1.0
Item { Item {
property string appName property string appName
property var quitRunningAppFn
property Session nextSession : null property Session nextSession : null
property string nextAppName : "" property string nextAppName : ""
@@ -18,7 +17,6 @@ Item {
if (error !== undefined) { if (error !== undefined) {
errorDialog.text = error errorDialog.text = error
errorDialog.open() errorDialog.open()
console.error(error)
} }
// If we're supposed to launch another game after this, do so now // If we're supposed to launch another game after this, do so now
@@ -39,11 +37,6 @@ Item {
// Connect the quit completion signal // Connect the quit completion signal
ComputerManager.quitAppCompleted.connect(quitAppCompleted) ComputerManager.quitAppCompleted.connect(quitAppCompleted)
// Start the quit operation if requested
if (quitRunningAppFn) {
quitRunningAppFn()
}
} }
StackView.onDeactivating: { StackView.onDeactivating: {
+153 -328
View File
@@ -1,7 +1,6 @@
import QtQuick 2.9 import QtQuick 2.9
import QtQuick.Controls 2.2 import QtQuick.Controls 2.2
import QtQuick.Layouts 1.2 import QtQuick.Layouts 1.2
import QtQuick.Window 2.2
import StreamingPreferences 1.0 import StreamingPreferences 1.0
import ComputerManager 1.0 import ComputerManager 1.0
@@ -12,8 +11,6 @@ Flickable {
id: settingsPage id: settingsPage
objectName: qsTr("Settings") objectName: qsTr("Settings")
signal languageChanged()
boundsBehavior: Flickable.OvershootBounds boundsBehavior: Flickable.OvershootBounds
contentWidth: settingsColumn1.width > settingsColumn2.width ? settingsColumn1.width : settingsColumn2.width contentWidth: settingsColumn1.width > settingsColumn2.width ? settingsColumn1.width : settingsColumn2.width
@@ -26,49 +23,6 @@ Flickable {
} }
} }
function isChildOfFlickable(item) {
while (item) {
if (item.parent === contentItem) {
return true
}
item = item.parent
}
return false
}
NumberAnimation on contentY {
id: autoScrollAnimation
duration: 100
}
Window.onActiveFocusItemChanged: {
var item = Window.activeFocusItem
if (item) {
// Ignore non-child elements like the toolbar buttons
if (!isChildOfFlickable(item)) {
return
}
// Map the focus item's position into our content item's coordinate space
var pos = item.mapToItem(contentItem, 0, 0)
// Ensure some extra space is visible around the element we're scrolling to
var scrollMargin = height > 100 ? 50 : 0
if (pos.y - scrollMargin < contentY) {
autoScrollAnimation.from = contentY
autoScrollAnimation.to = Math.max(pos.y - scrollMargin, 0)
autoScrollAnimation.start()
}
else if (pos.y + item.height + scrollMargin > contentY + height) {
autoScrollAnimation.from = contentY
autoScrollAnimation.to = Math.min(pos.y + item.height + scrollMargin - height, contentHeight - height)
autoScrollAnimation.start()
}
}
}
StackView.onActivated: { StackView.onActivated: {
// This enables Tab and BackTab based navigation rather than arrow keys. // This enables Tab and BackTab based navigation rather than arrow keys.
// It is required to shift focus between controls on the settings page. // It is required to shift focus between controls on the settings page.
@@ -141,39 +95,50 @@ Flickable {
// Add native resolutions for all attached displays // Add native resolutions for all attached displays
var done = false var done = false
for (var displayIndex = 0; !done; displayIndex++) { for (var displayIndex = 0; !done; displayIndex++) {
var screenRect = SystemProperties.getNativeResolution(displayIndex); for (var displayResIndex = 0; displayResIndex < 2; displayResIndex++) {
var screenRect;
if (screenRect.width === 0) { // Some platforms have different desktop resolutions
// Exceeded max count of displays // and native resolutions (like macOS with Retina displays)
done = true if (displayResIndex === 0) {
break screenRect = SystemProperties.getDesktopResolution(displayIndex)
} }
else {
screenRect = SystemProperties.getNativeResolution(displayIndex)
}
var indexToAdd = 0 if (screenRect.width === 0) {
for (var j = 0; j < resolutionComboBox.count; j++) { // Exceeded max count of displays
var existing_width = parseInt(resolutionListModel.get(j).video_width); done = true
var existing_height = parseInt(resolutionListModel.get(j).video_height);
if (screenRect.width === existing_width && screenRect.height === existing_height) {
// Duplicate entry, skip
indexToAdd = -1
break break
} }
else if (screenRect.width * screenRect.height > existing_width * existing_height) {
// Candidate entrypoint after this entry
indexToAdd = j + 1
}
}
// Insert this display's resolution if it's not a duplicate var indexToAdd = 0
if (indexToAdd >= 0) { for (var j = 0; j < resolutionComboBox.count; j++) {
resolutionListModel.insert(indexToAdd, var existing_width = parseInt(resolutionListModel.get(j).video_width);
{ var existing_height = parseInt(resolutionListModel.get(j).video_height);
"text": "Native ("+screenRect.width+"x"+screenRect.height+")",
"video_width": ""+screenRect.width, if (screenRect.width === existing_width && screenRect.height === existing_height) {
"video_height": ""+screenRect.height, // Duplicate entry, skip
"is_custom": false indexToAdd = -1
}) break
}
else if (screenRect.width * screenRect.height > existing_width * existing_height) {
// Candidate entrypoint after this entry
indexToAdd = j + 1
}
}
// Insert this display's resolution if it's not a duplicate
if (indexToAdd >= 0) {
resolutionListModel.insert(indexToAdd,
{
"text": "Native ("+screenRect.width+"x"+screenRect.height+")",
"video_width": ""+screenRect.width,
"video_height": ""+screenRect.height,
"is_custom": false
})
}
} }
} }
@@ -432,211 +397,74 @@ Flickable {
} }
AutoResizingComboBox { AutoResizingComboBox {
property int lastIndexValue function createModel() {
var fpsListModel = Qt.createQmlObject('import QtQuick 2.0; ListModel {}', parent, '')
function updateBitrateForSelection() { var max_fps = SystemProperties.maximumStreamingFrameRate
// Only modify the bitrate if the values actually changed
var selectedFps = parseInt(model.get(fpsComboBox.currentIndex).video_fps)
if (StreamingPreferences.fps !== selectedFps) {
StreamingPreferences.fps = selectedFps
StreamingPreferences.bitrateKbps = StreamingPreferences.getDefaultBitrate(StreamingPreferences.width, // Default entries
StreamingPreferences.height, fpsListModel.append({"text": qsTr("%1 FPS").arg("30"), "video_fps": "30"})
StreamingPreferences.fps); fpsListModel.append({"text": qsTr("%1 FPS").arg("60"), "video_fps": "60"})
slider.value = StreamingPreferences.bitrateKbps
}
lastIndexValue = currentIndex // Add unsupported FPS values that come before the display max FPS
} if (StreamingPreferences.unsupportedFps) {
if (max_fps > 90) {
NavigableDialog { fpsListModel.append({"text": qsTr("%1 FPS (Unsupported)").arg("90"), "video_fps": "90"})
function isInputValid() {
// If we have text that isn't valid, reject the input.
if (!fpsField.acceptableInput && fpsField.text) {
return false
} }
if (max_fps > 120) {
// The textbox needs to have text or placeholder text fpsListModel.append({"text": qsTr("%1 FPS (Unsupported)").arg("120"), "video_fps": "120"})
if (!fpsField.text && !fpsField.placeholderText) {
return false
}
return true
}
id: customFpsDialog
standardButtons: Dialog.Ok | Dialog.Cancel
onOpened: {
// Force keyboard focus on the textbox so keyboard navigation works
fpsField.forceActiveFocus()
// standardButton() was added in Qt 5.10, so we must check for it first
if (customFpsDialog.standardButton) {
customFpsDialog.standardButton(Dialog.Ok).enabled = customFpsDialog.isInputValid()
} }
} }
onClosed: { // Use 64 as the cutoff for adding a separate option to
fpsField.clear() // handle wonky displays that report just over 60 Hz.
} if (max_fps > 64) {
// Mark any FPS value greater than 120 as unsupported
onRejected: { if (StreamingPreferences.unsupportedFps && max_fps > 120) {
fpsComboBox.currentIndex = fpsComboBox.lastIndexValue fpsListModel.append({"text": qsTr("%1 FPS (Unsupported)").arg(max_fps), "video_fps": ""+max_fps})
}
onAccepted: {
// Reject if there's invalid input
if (!isInputValid()) {
reject()
return
} }
else if (max_fps > 120) {
var fps = fpsField.text ? fpsField.text : fpsField.placeholderText fpsListModel.append({"text": qsTr("%1 FPS").arg("120"), "video_fps": "120"})
}
// Find and update the custom entry else {
for (var i = 0; i < fpsListModel.count; i++) { fpsListModel.append({"text": qsTr("%1 FPS").arg(max_fps), "video_fps": ""+max_fps})
if (fpsListModel.get(i).is_custom) {
fpsListModel.setProperty(i, "video_fps", fps)
fpsListModel.setProperty(i, "text", qsTr("Custom (%1 FPS)").arg(fps))
// Now update the bitrate using the custom resolution
fpsComboBox.currentIndex = i
fpsComboBox.updateBitrateForSelection()
// Update the combobox width too
fpsComboBox.recalculateWidth()
break
}
} }
} }
ColumnLayout { // Add unsupported FPS values that come after the display max FPS
Label { if (StreamingPreferences.unsupportedFps) {
text: qsTr("Enter a custom frame rate:") if (max_fps < 90) {
font.bold: true fpsListModel.append({"text":qsTr("%1 FPS (Unsupported)").arg("90"), "video_fps": "90"})
} }
if (max_fps < 120) {
RowLayout { fpsListModel.append({"text":qsTr("%1 FPS (Unsupported)").arg("120"), "video_fps": "120"})
TextField {
id: fpsField
maximumLength: 4
inputMethodHints: Qt.ImhDigitsOnly
placeholderText: fpsListModel.get(fpsComboBox.currentIndex).video_fps
validator: IntValidator{bottom:10; top:9999}
focus: true
onTextChanged: {
// standardButton() was added in Qt 5.10, so we must check for it first
if (customFpsDialog.standardButton) {
customFpsDialog.standardButton(Dialog.Ok).enabled = customFpsDialog.isInputValid()
}
}
Keys.onReturnPressed: {
customFpsDialog.accept()
}
Keys.onEnterPressed: {
customFpsDialog.accept()
}
}
}
}
}
function addRefreshRateOrdered(fpsListModel, refreshRate, description, custom) {
var indexToAdd = 0
for (var j = 0; j < fpsListModel.count; j++) {
var existing_fps = parseInt(fpsListModel.get(j).video_fps);
if (refreshRate === existing_fps || (custom && fpsListModel.get(j).is_custom)) {
// Duplicate entry, skip
indexToAdd = -1
break
}
else if (refreshRate > existing_fps) {
// Candidate entrypoint after this entry
indexToAdd = j + 1
} }
} }
// Insert this frame rate if it's not a duplicate return fpsListModel
if (indexToAdd >= 0) {
// Custom values always go at the end of the list
if (custom) {
indexToAdd = fpsListModel.count
}
fpsListModel.insert(indexToAdd,
{
"text": description,
"video_fps": ""+refreshRate,
"is_custom": custom
})
}
return indexToAdd
} }
function reinitialize() { function reinitialize() {
// Add native refresh rate for all attached displays model = createModel()
var done = false
for (var displayIndex = 0; !done; displayIndex++) {
var refreshRate = SystemProperties.getRefreshRate(displayIndex);
if (refreshRate === 0) {
// Exceeded max count of displays
done = true
break
}
addRefreshRateOrdered(fpsListModel, refreshRate, qsTr("%1 FPS").arg(refreshRate), false)
}
var saved_fps = StreamingPreferences.fps var saved_fps = StreamingPreferences.fps
var found = false currentIndex = 0
for (var i = 0; i < model.count; i++) { for (var i = 0; i < model.count; i++) {
var el_fps = parseInt(model.get(i).video_fps); var el_fps = parseInt(model.get(i).video_fps);
// Look for a matching frame rate // Pick the highest value lesser or equal to the saved FPS
if (saved_fps === el_fps) { if (saved_fps >= el_fps) {
currentIndex = i currentIndex = i
found = true
break
} }
} }
// If we didn't find one, add a custom frame rate for the current value // Persist the selected value
if (!found) { activated(currentIndex)
currentIndex = addRefreshRateOrdered(model, saved_fps, qsTr("Custom (%1 FPS)").arg(saved_fps), true)
}
else {
addRefreshRateOrdered(model, "", qsTr("Custom"), true)
}
recalculateWidth()
lastIndexValue = currentIndex
} }
// ignore setting the index at first, and actually set it when the component is loaded // ignore setting the index at first, and actually set it when the component is loaded
Component.onCompleted: { Component.onCompleted: {
reinitialize() reinitialize()
languageChanged.connect(reinitialize)
}
model: ListModel {
id: fpsListModel
// Other elements may be added at runtime
ListElement {
text: qsTr("30 FPS")
video_fps: "30"
is_custom: false
}
ListElement {
text: qsTr("60 FPS")
video_fps: "60"
is_custom: false
}
} }
id: fpsComboBox id: fpsComboBox
@@ -644,11 +472,16 @@ Flickable {
textRole: "text" textRole: "text"
// ::onActivated must be used, as it only listens for when the index is changed by a human // ::onActivated must be used, as it only listens for when the index is changed by a human
onActivated : { onActivated : {
if (model.get(currentIndex).is_custom) { var selectedFps = parseInt(model.get(currentIndex).video_fps)
customFpsDialog.open()
} // Only modify the bitrate if the values actually changed
else { if (StreamingPreferences.fps !== selectedFps) {
updateBitrateForSelection() StreamingPreferences.fps = selectedFps
StreamingPreferences.bitrateKbps = StreamingPreferences.getDefaultBitrate(StreamingPreferences.width,
StreamingPreferences.height,
StreamingPreferences.fps);
slider.value = StreamingPreferences.bitrateKbps
} }
} }
} }
@@ -686,11 +519,6 @@ Flickable {
bitrateTitle.text = qsTr("Video bitrate: %1 Mbps").arg(value / 1000.0) bitrateTitle.text = qsTr("Video bitrate: %1 Mbps").arg(value / 1000.0)
StreamingPreferences.bitrateKbps = value StreamingPreferences.bitrateKbps = value
} }
Component.onCompleted: {
// Refresh the text after translations change
languageChanged.connect(onValueChanged)
}
} }
Label { Label {
@@ -703,53 +531,28 @@ Flickable {
} }
AutoResizingComboBox { AutoResizingComboBox {
function createModel() { // ignore setting the index at first, and actually set it when the component is loaded
var model = Qt.createQmlObject('import QtQuick 2.0; ListModel {}', parent, '') Component.onCompleted: {
model.append({
text: qsTr("Fullscreen"),
val: StreamingPreferences.WM_FULLSCREEN
})
model.append({
text: qsTr("Borderless windowed"),
val: StreamingPreferences.WM_FULLSCREEN_DESKTOP
})
model.append({
text: qsTr("Windowed"),
val: StreamingPreferences.WM_WINDOWED
})
// Set the recommended option based on the OS
for (var i = 0; i < model.count; i++) {
var thisWm = model.get(i).val;
if (thisWm === StreamingPreferences.recommendedFullScreenMode) {
model.get(i).text += " " + qsTr("(Recommended)")
model.move(i, 0, 1)
break
}
}
return model
}
// This is used on initialization and upon retranslation
function reinitialize() {
if (!visible) { if (!visible) {
// Do nothing if the control won't even be visible // Do nothing if the control won't even be visible
return return
} }
model = createModel() // Set the recommended option based on the OS
for (var i = 0; i < windowModeListModel.count; i++) {
var thisWm = windowModeListModel.get(i).val;
if (thisWm === StreamingPreferences.recommendedFullScreenMode) {
windowModeListModel.get(i).text += qsTr(" (Recommended)")
windowModeListModel.move(i, 0, 1);
break
}
}
currentIndex = 0 currentIndex = 0
// Set the current value based on the saved preferences
var savedWm = StreamingPreferences.windowMode var savedWm = StreamingPreferences.windowMode
for (var i = 0; i < model.count; i++) { for (var i = 0; i < windowModeListModel.count; i++) {
var thisWm = model.get(i).val; var thisWm = windowModeListModel.get(i).val;
if (savedWm === thisWm) { if (savedWm === thisWm) {
currentIndex = i currentIndex = i
break break
@@ -759,18 +562,28 @@ Flickable {
activated(currentIndex) activated(currentIndex)
} }
Component.onCompleted: {
reinitialize()
languageChanged.connect(reinitialize)
}
id: windowModeComboBox id: windowModeComboBox
visible: SystemProperties.hasDesktopEnvironment visible: SystemProperties.hasDesktopEnvironment
enabled: !SystemProperties.rendererAlwaysFullScreen enabled: !SystemProperties.rendererAlwaysFullScreen
hoverEnabled: true hoverEnabled: true
textRole: "text" textRole: "text"
model: ListModel {
id: windowModeListModel
ListElement {
text: qsTr("Fullscreen")
val: StreamingPreferences.WM_FULLSCREEN
}
ListElement {
text: qsTr("Borderless windowed")
val: StreamingPreferences.WM_FULLSCREEN_DESKTOP
}
ListElement {
text: qsTr("Windowed")
val: StreamingPreferences.WM_WINDOWED
}
}
onActivated: { onActivated: {
StreamingPreferences.windowMode = model.get(currentIndex).val StreamingPreferences.windowMode = windowModeListModel.get(currentIndex).val
} }
ToolTip.delay: 1000 ToolTip.delay: 1000
@@ -1017,8 +830,8 @@ Flickable {
val: StreamingPreferences.LANG_UK val: StreamingPreferences.LANG_UK
} */ } */
ListElement { ListElement {
text: "繁體中文" // Traditional Chinese text: "繁体字" // Traditional Chinese
val: StreamingPreferences.LANG_ZH_TW val: StreamingPreferences.LANG_ZH_HANT
} }
ListElement { ListElement {
text: "Português" // Portuguese text: "Português" // Portuguese
@@ -1040,18 +853,6 @@ Flickable {
text: "हिन्दी, हिंदी" // Hindi text: "हिन्दी, हिंदी" // Hindi
val: StreamingPreferences.LANG_HI val: StreamingPreferences.LANG_HI
} */ } */
ListElement {
text: "Język polski" // Polish
val: StreamingPreferences.LANG_PL
}
ListElement {
text: "Čeština" // Czech
val: StreamingPreferences.LANG_CS
}
/* ListElement {
text: "עִבְרִית" // Hebrew
val: StreamingPreferences.LANG_HE
} */
} }
// ::onActivated must be used, as it only listens for when the index is changed by a human // ::onActivated must be used, as it only listens for when the index is changed by a human
onActivated : { onActivated : {
@@ -1066,9 +867,6 @@ Flickable {
// Force the back operation to pop any AppView pages that exist. // Force the back operation to pop any AppView pages that exist.
// The AppView stops working after retranslate() for some reason. // The AppView stops working after retranslate() for some reason.
window.clearOnBack = true window.clearOnBack = true
// Signal other controls to adjust their text
languageChanged()
} }
} }
} }
@@ -1559,6 +1357,7 @@ Flickable {
id: codecComboBox id: codecComboBox
textRole: "text" textRole: "text"
enabled: !enableHdr.checked
model: ListModel { model: ListModel {
id: codecListModel id: codecListModel
ListElement { ListElement {
@@ -1573,10 +1372,6 @@ Flickable {
text: qsTr("HEVC (H.265)") text: qsTr("HEVC (H.265)")
val: StreamingPreferences.VCC_FORCE_HEVC val: StreamingPreferences.VCC_FORCE_HEVC
} }
ListElement {
text: qsTr("AV1 (Experimental)")
val: StreamingPreferences.VCC_FORCE_AV1
}
} }
// ::onActivated must be used, as it only listens for when the index is changed by a human // ::onActivated must be used, as it only listens for when the index is changed by a human
onActivated : { onActivated : {
@@ -1584,6 +1379,21 @@ Flickable {
StreamingPreferences.videoCodecConfig = codecListModel.get(currentIndex).val StreamingPreferences.videoCodecConfig = codecListModel.get(currentIndex).val
} }
} }
// This handles the state of the enableHdr checkbox changing
onEnabledChanged: {
if (enabled) {
StreamingPreferences.videoCodecConfig = codecListModel.get(currentIndex).val
}
else {
StreamingPreferences.videoCodecConfig = StreamingPreferences.VCC_FORCE_HEVC_HDR
}
}
ToolTip.delay: 1000
ToolTip.timeout: 5000
ToolTip.visible: hovered && !enabled
ToolTip.text: qsTr("Enabling HDR overrides manual codec selections.")
} }
CheckBox { CheckBox {
@@ -1591,12 +1401,8 @@ Flickable {
width: parent.width width: parent.width
text: qsTr("Enable HDR (Experimental)") text: qsTr("Enable HDR (Experimental)")
font.pointSize: 12 font.pointSize: 12
enabled: SystemProperties.supportsHdr enabled: SystemProperties.supportsHdr
checked: enabled && StreamingPreferences.enableHdr checked: enabled && StreamingPreferences.videoCodecConfig == StreamingPreferences.VCC_FORCE_HEVC_HDR
onCheckedChanged: {
StreamingPreferences.enableHdr = checked
}
// Updating StreamingPreferences.videoCodecConfig is handled above // Updating StreamingPreferences.videoCodecConfig is handled above
@@ -1609,6 +1415,25 @@ Flickable {
qsTr("HDR streaming is not supported on this PC.") qsTr("HDR streaming is not supported on this PC.")
} }
CheckBox {
id: unlockUnsupportedFps
width: parent.width
text: qsTr("Unlock unsupported FPS options")
font.pointSize: 12
checked: StreamingPreferences.unsupportedFps
onCheckedChanged: {
// This is called on init, so only do the work if we've
// actually changed the value.
if (StreamingPreferences.unsupportedFps != checked) {
StreamingPreferences.unsupportedFps = checked
// The selectable FPS values depend on whether
// this option is enabled or not
fpsComboBox.reinitialize()
}
}
}
CheckBox { CheckBox {
id: enableMdns id: enableMdns
width: parent.width width: parent.width
-2
View File
@@ -45,7 +45,6 @@ Item {
{ {
// Display the error dialog after Session::exec() returns // Display the error dialog after Session::exec() returns
streamSegueErrorDialog.text = text streamSegueErrorDialog.text = text
console.error(text)
} }
function displayLaunchWarning(text) function displayLaunchWarning(text)
@@ -57,7 +56,6 @@ Item {
toast.text = text toast.text = text
toast.timeout = 3000 toast.timeout = 3000
toast.visible = true toast.visible = true
console.warn(text)
} }
function quitStarting() function quitStarting()
+19 -11
View File
@@ -2,6 +2,8 @@
#include <QThreadPool> #include <QThreadPool>
#include <random>
ComputerModel::ComputerModel(QObject* object) ComputerModel::ComputerModel(QObject* object)
: QAbstractListModel(object) {} : QAbstractListModel(object) {}
@@ -138,9 +140,14 @@ void ComputerModel::renameComputer(int computerIndex, QString name)
m_ComputerManager->renameHost(m_Computers[computerIndex], name); m_ComputerManager->renameHost(m_Computers[computerIndex], name);
} }
// TODO: Use QRandomGenerator when we drop Qt 5.9 support
QString ComputerModel::generatePinString() QString ComputerModel::generatePinString()
{ {
return m_ComputerManager->generatePinString(); std::uniform_int_distribution<int> dist(0, 9999);
std::random_device rd;
std::mt19937 engine(rd());
return QString::asprintf("%04u", dist(engine));
} }
class DeferredTestConnectionTask : public QObject, public QRunnable class DeferredTestConnectionTask : public QObject, public QRunnable
@@ -186,18 +193,19 @@ void ComputerModel::handlePairingCompleted(NvComputer*, QString error)
void ComputerModel::handleComputerStateChanged(NvComputer* computer) void ComputerModel::handleComputerStateChanged(NvComputer* computer)
{ {
QVector<NvComputer*> newComputerList = m_ComputerManager->getComputers(); // If this is an existing computer, we can report the data changed
int index = m_Computers.indexOf(computer);
// Reset the model if the structural layout of the list has changed if (index >= 0) {
if (m_Computers != newComputerList) { // Let the view know that this specific computer changed
beginResetModel(); emit dataChanged(createIndex(index, 0), createIndex(index, 0));
m_Computers = newComputerList;
endResetModel();
} }
else { else {
// Let the view know that this specific computer changed // This is a new PC which may be inserted at an arbitrary point
int index = m_Computers.indexOf(computer); // in our computer list (since it comes from CM's QMap). Reload
emit dataChanged(createIndex(index, 0), createIndex(index, 0)); // the whole model state to ensure it stays consistent.
beginResetModel();
m_Computers = m_ComputerManager->getComputers();
endResetModel();
} }
} }
+8 -28
View File
@@ -2,7 +2,6 @@ import QtQuick 2.9
import QtQuick.Controls 2.2 import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3 import QtQuick.Layouts 1.3
import QtQuick.Window 2.2 import QtQuick.Window 2.2
import QtQuick.Controls.Material 2.2
import ComputerManager 1.0 import ComputerManager 1.0
import AutoUpdateChecker 1.0 import AutoUpdateChecker 1.0
@@ -23,15 +22,6 @@ ApplicationWindow {
width: 1280 width: 1280
height: 600 height: 600
// Override the background color to Material 2 colors for Qt 6.5+
// in order to improve contrast between GFE's placeholder box art
// and the background of the app grid.
Component.onCompleted: {
if (SystemProperties.usesMaterial3Theme) {
Material.background = "#303030"
}
}
visibility: { visibility: {
if (SystemProperties.hasDesktopEnvironment) { if (SystemProperties.hasDesktopEnvironment) {
if (StreamingPreferences.uiDisplayMode == StreamingPreferences.UI_WINDOWED) return "Windowed" if (StreamingPreferences.uiDisplayMode == StreamingPreferences.UI_WINDOWED) return "Windowed"
@@ -191,20 +181,10 @@ ApplicationWindow {
} }
} }
// Workaround for lack of instanceof in Qt 5.9. function navigateTo(url, objectName)
//
// Based on https://stackoverflow.com/questions/13923794/how-to-do-a-is-a-typeof-or-instanceof-in-qml
function qmltypeof(obj, className) { // QtObject, string -> bool
// className plus "(" is the class instance without modification
// className plus "_QML" is the class instance with user-defined properties
var str = obj.toString();
return str.startsWith(className + "(") || str.startsWith(className + "_QML");
}
function navigateTo(url, objectType)
{ {
var existingItem = stackView.find(function(item, index) { var existingItem = stackView.find(function(item, index) {
return qmltypeof(item, objectType) return item.objectName === objectName
}) })
if (existingItem !== null) { if (existingItem !== null) {
@@ -271,7 +251,7 @@ ApplicationWindow {
Label { Label {
id: versionLabel id: versionLabel
visible: qmltypeof(stackView.currentItem, "SettingsView") visible: stackView.currentItem.objectName === qsTr("Settings")
text: qsTr("Version %1").arg(SystemProperties.versionString) text: qsTr("Version %1").arg(SystemProperties.versionString)
font.pointSize: 12 font.pointSize: 12
horizontalAlignment: Qt.AlignRight horizontalAlignment: Qt.AlignRight
@@ -281,7 +261,7 @@ ApplicationWindow {
NavigableToolButton { NavigableToolButton {
id: discordButton id: discordButton
visible: SystemProperties.hasBrowser && visible: SystemProperties.hasBrowser &&
qmltypeof(stackView.currentItem, "SettingsView") stackView.currentItem.objectName === qsTr("Settings")
iconSource: "qrc:/res/Discord-Logo-White.svg" iconSource: "qrc:/res/Discord-Logo-White.svg"
@@ -300,7 +280,7 @@ ApplicationWindow {
NavigableToolButton { NavigableToolButton {
id: addPcButton id: addPcButton
visible: qmltypeof(stackView.currentItem, "PcView") visible: stackView.currentItem.objectName === qsTr("Computers")
iconSource: "qrc:/res/ic_add_to_queue_white_48px.svg" iconSource: "qrc:/res/ic_add_to_queue_white_48px.svg"
@@ -398,7 +378,7 @@ ApplicationWindow {
iconSource: "qrc:/res/ic_videogame_asset_white_48px.svg" iconSource: "qrc:/res/ic_videogame_asset_white_48px.svg"
onClicked: navigateTo("qrc:/gui/GamepadMapper.qml", "GamepadMapper") onClicked: navigateTo("qrc:/gui/GamepadMapper.qml", qsTr("Gamepad Mapping"))
Keys.onDownPressed: { Keys.onDownPressed: {
stackView.currentItem.forceActiveFocus(Qt.TabFocus) stackView.currentItem.forceActiveFocus(Qt.TabFocus)
@@ -410,7 +390,7 @@ ApplicationWindow {
iconSource: "qrc:/res/settings.svg" iconSource: "qrc:/res/settings.svg"
onClicked: navigateTo("qrc:/gui/SettingsView.qml", "SettingsView") onClicked: navigateTo("qrc:/gui/SettingsView.qml", qsTr("Settings"))
Keys.onDownPressed: { Keys.onDownPressed: {
stackView.currentItem.forceActiveFocus(Qt.TabFocus) stackView.currentItem.forceActiveFocus(Qt.TabFocus)
@@ -498,7 +478,7 @@ ApplicationWindow {
NavigableDialog { NavigableDialog {
id: addPcDialog id: addPcDialog
property string label: qsTr("Enter the IP address of your host PC:") property string label: qsTr("Enter the IP address of your GameStream PC:")
standardButtons: Dialog.Ok | Dialog.Cancel standardButtons: Dialog.Ok | Dialog.Cancel
+42 -11
View File
@@ -191,17 +191,7 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
case SDL_CONTROLLERDEVICEADDED: case SDL_CONTROLLERDEVICEADDED:
SDL_GameController* gc = SDL_GameControllerOpen(event.cdevice.which); SDL_GameController* gc = SDL_GameControllerOpen(event.cdevice.which);
if (gc != nullptr) { if (gc != nullptr) {
// SDL_CONTROLLERDEVICEADDED can be reported multiple times for the same m_Gamepads.append(gc);
// gamepad in rare cases, because SDL doesn't fixup the device index in
// the SDL_CONTROLLERDEVICEADDED event if an unopened gamepad disappears
// before we've processed the add event.
if (!m_Gamepads.contains(gc)) {
m_Gamepads.append(gc);
}
else {
// We already have this game controller open
SDL_GameControllerClose(gc);
}
} }
break; break;
} }
@@ -249,6 +239,31 @@ void SdlGamepadKeyNavigation::onPollingTimerFired()
sendKey(QEvent::Type::KeyRelease, Qt::Key_Right); sendKey(QEvent::Type::KeyRelease, Qt::Key_Right);
m_LastAxisNavigationEventTime = SDL_GetTicks(); m_LastAxisNavigationEventTime = SDL_GetTicks();
} }
// In UI navigation mode (settings page), use the right stick to scroll
if (m_UiNavMode) {
short rightX = SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_RIGHTX);
short rightY = SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_RIGHTY);
QPoint wheelDelta;
if (rightX > 30000) {
wheelDelta.setX(30);
}
else if (rightX < -30000) {
wheelDelta.setX(-30);
}
if (rightY > 30000) {
wheelDelta.setY(-30);
}
else if (rightY < -30000) {
wheelDelta.setY(30);
}
if (!wheelDelta.isNull()) {
sendWheel(wheelDelta);
}
}
} }
} }
@@ -262,6 +277,22 @@ void SdlGamepadKeyNavigation::sendKey(QEvent::Type type, Qt::Key key, Qt::Keyboa
} }
} }
void SdlGamepadKeyNavigation::sendWheel(QPoint& angleDelta)
{
QGuiApplication* app = static_cast<QGuiApplication*>(QGuiApplication::instance());
QWindow* focusWindow = app->focusWindow();
if (focusWindow != nullptr) {
QPoint mousePos(focusWindow->width() / 2, focusWindow->height() / 2);
QPoint globalPos(focusWindow->mapToGlobal(mousePos));
#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
QWheelEvent wheelEvent(mousePos, globalPos, QPoint(), angleDelta, Qt::NoButton, Qt::NoModifier, Qt::NoScrollPhase, false, Qt::MouseEventSynthesizedByApplication);
#else
QWheelEvent wheelEvent(mousePos, globalPos, QPoint(), angleDelta, angleDelta.y(), Qt::Vertical, Qt::NoButton, Qt::NoModifier, Qt::NoScrollPhase, Qt::MouseEventSynthesizedByApplication, false);
#endif
app->sendEvent(focusWindow, &wheelEvent);
}
}
void SdlGamepadKeyNavigation::setUiNavMode(bool uiNavMode) void SdlGamepadKeyNavigation::setUiNavMode(bool uiNavMode)
{ {
m_UiNavMode = uiNavMode; m_UiNavMode = uiNavMode;
+1
View File
@@ -24,6 +24,7 @@ public:
private: private:
void sendKey(QEvent::Type type, Qt::Key key, Qt::KeyboardModifiers modifiers = Qt::NoModifier); void sendKey(QEvent::Type type, Qt::Key key, Qt::KeyboardModifiers modifiers = Qt::NoModifier);
void sendWheel(QPoint& angleDelta);
private slots: private slots:
void onPollingTimerFired(); void onPollingTimerFired();
Binary file not shown.
File diff suppressed because it is too large. Load diff
Binary file not shown.
+351 -421
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+285 -351
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+290 -356
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+346 -377
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
File diff suppressed because it is too large. Load diff
Binary file not shown.
+274 -348
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+605 -687
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+290 -356
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+279 -349
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+287 -357
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+285 -351
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+290 -356
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
File diff suppressed because it is too large. Load diff
Binary file not shown.
+298 -364
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+293 -367
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+298 -364
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+418 -496
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+275 -349
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+270 -352
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+358 -440
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+286 -352
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large. Load diff
+43 -137
View File
@@ -28,17 +28,14 @@
#include <openssl/ssl.h> #include <openssl/ssl.h>
#endif #endif
#include "cli/listapps.h"
#include "cli/quitstream.h" #include "cli/quitstream.h"
#include "cli/startstream.h" #include "cli/startstream.h"
#include "cli/pair.h"
#include "cli/commandlineparser.h" #include "cli/commandlineparser.h"
#include "path.h" #include "path.h"
#include "utils.h" #include "utils.h"
#include "gui/computermodel.h" #include "gui/computermodel.h"
#include "gui/appmodel.h" #include "gui/appmodel.h"
#include "backend/autoupdatechecker.h" #include "backend/autoupdatechecker.h"
#include "backend/computermanager.h"
#include "backend/systemproperties.h" #include "backend/systemproperties.h"
#include "streaming/session.h" #include "streaming/session.h"
#include "settings/streamingpreferences.h" #include "settings/streamingpreferences.h"
@@ -63,11 +60,9 @@
static QElapsedTimer s_LoggerTime; static QElapsedTimer s_LoggerTime;
static QTextStream s_LoggerStream(stdout); static QTextStream s_LoggerStream(stdout);
static QMutex s_LoggerLock; static QMutex s_LoggerLock;
static bool s_SuppressVerboseOutput;
#ifdef LOG_TO_FILE #ifdef LOG_TO_FILE
// Max log file size of 10 MB #define MAX_LOG_LINES 10000
#define MAX_LOG_SIZE_BYTES (10 * 1024 * 1024) static int s_LogLinesWritten = 0;
static int s_LogBytesWritten = 0;
static bool s_LogLimitReached = false; static bool s_LogLimitReached = false;
static QFile* s_LoggerFile; static QFile* s_LoggerFile;
#endif #endif
@@ -80,7 +75,7 @@ void logToLoggerStream(QString& message)
if (s_LogLimitReached) { if (s_LogLimitReached) {
return; return;
} }
else if (s_LogBytesWritten >= MAX_LOG_SIZE_BYTES) { else if (s_LogLinesWritten == MAX_LOG_LINES) {
s_LoggerStream << "Log size limit reached!"; s_LoggerStream << "Log size limit reached!";
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
s_LoggerStream << Qt::endl; s_LoggerStream << Qt::endl;
@@ -91,7 +86,7 @@ void logToLoggerStream(QString& message)
return; return;
} }
else { else {
s_LogBytesWritten += message.size(); s_LogLinesWritten++;
} }
#endif #endif
@@ -105,27 +100,15 @@ void sdlLogToDiskHandler(void*, int category, SDL_LogPriority priority, const ch
switch (priority) { switch (priority) {
case SDL_LOG_PRIORITY_VERBOSE: case SDL_LOG_PRIORITY_VERBOSE:
if (s_SuppressVerboseOutput) {
return;
}
priorityTxt = "Verbose"; priorityTxt = "Verbose";
break; break;
case SDL_LOG_PRIORITY_DEBUG: case SDL_LOG_PRIORITY_DEBUG:
if (s_SuppressVerboseOutput) {
return;
}
priorityTxt = "Debug"; priorityTxt = "Debug";
break; break;
case SDL_LOG_PRIORITY_INFO: case SDL_LOG_PRIORITY_INFO:
if (s_SuppressVerboseOutput) {
return;
}
priorityTxt = "Info"; priorityTxt = "Info";
break; break;
case SDL_LOG_PRIORITY_WARN: case SDL_LOG_PRIORITY_WARN:
if (s_SuppressVerboseOutput) {
return;
}
priorityTxt = "Warn"; priorityTxt = "Warn";
break; break;
case SDL_LOG_PRIORITY_ERROR: case SDL_LOG_PRIORITY_ERROR:
@@ -151,21 +134,12 @@ void qtLogToDiskHandler(QtMsgType type, const QMessageLogContext&, const QString
switch (type) { switch (type) {
case QtDebugMsg: case QtDebugMsg:
if (s_SuppressVerboseOutput) {
return;
}
typeTxt = "Debug"; typeTxt = "Debug";
break; break;
case QtInfoMsg: case QtInfoMsg:
if (s_SuppressVerboseOutput) {
return;
}
typeTxt = "Info"; typeTxt = "Info";
break; break;
case QtWarningMsg: case QtWarningMsg:
if (s_SuppressVerboseOutput) {
return;
}
typeTxt = "Warning"; typeTxt = "Warning";
break; break;
case QtCriticalMsg: case QtCriticalMsg:
@@ -192,9 +166,6 @@ void ffmpegLogToDiskHandler(void* ptr, int level, const char* fmt, va_list vl)
if ((level & 0xFF) > av_log_get_level()) { if ((level & 0xFF) > av_log_get_level()) {
return; return;
} }
else if ((level & 0xFF) > AV_LOG_WARNING && s_SuppressVerboseOutput) {
return;
}
// We need to use the *previous* printPrefix value to determine whether to // We need to use the *previous* printPrefix value to determine whether to
// print the prefix this time. av_log_format_line() will set the printPrefix // print the prefix this time. av_log_format_line() will set the printPrefix
@@ -289,6 +260,7 @@ int main(int argc, char *argv[])
QCoreApplication::setApplicationName("Moonlight"); QCoreApplication::setApplicationName("Moonlight");
if (QFile(QDir::currentPath() + "/portable.dat").exists()) { if (QFile(QDir::currentPath() + "/portable.dat").exists()) {
qInfo() << "Running in portable mode from:" << QDir::currentPath();
QSettings::setDefaultFormat(QSettings::IniFormat); QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, QDir::currentPath()); QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, QDir::currentPath());
QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, QDir::currentPath()); QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, QDir::currentPath());
@@ -301,17 +273,12 @@ int main(int argc, char *argv[])
Path::initialize(false); Path::initialize(false);
} }
// Override the default QML cache directory with the one we chose
if (qEnvironmentVariableIsEmpty("QML_DISK_CACHE_PATH")) {
qputenv("QML_DISK_CACHE_PATH", Path::getQmlCacheDir().toUtf8());
}
#ifdef USE_CUSTOM_LOGGER #ifdef USE_CUSTOM_LOGGER
#ifdef LOG_TO_FILE #ifdef LOG_TO_FILE
QDir tempDir(Path::getLogDir()); QDir tempDir(Path::getLogDir());
s_LoggerFile = new QFile(tempDir.filePath(QString("Moonlight-%1.log").arg(QDateTime::currentSecsSinceEpoch()))); s_LoggerFile = new QFile(tempDir.filePath(QString("Moonlight-%1.log").arg(QDateTime::currentSecsSinceEpoch())));
if (s_LoggerFile->open(QIODevice::WriteOnly | QIODevice::Text)) { if (s_LoggerFile->open(QIODevice::WriteOnly)) {
QTextStream(stderr) << "Redirecting log output to " << s_LoggerFile->fileName() << Qt::endl; qInfo() << "Redirecting log output to " << s_LoggerFile->fileName();
s_LoggerStream.setDevice(s_LoggerFile); s_LoggerStream.setDevice(s_LoggerFile);
} }
#endif #endif
@@ -331,15 +298,6 @@ int main(int argc, char *argv[])
SetUnhandledExceptionFilter(UnhandledExceptionHandler); SetUnhandledExceptionFilter(UnhandledExceptionHandler);
#endif #endif
#ifdef LOG_TO_FILE
// Prune the oldest existing logs if there are more than 10
QStringList existingLogNames = tempDir.entryList(QStringList("Moonlight-*.log"), QDir::NoFilter, QDir::SortFlag::Time);
for (int i = 10; i < existingLogNames.size(); i++) {
qInfo() << "Removing old log file:" << existingLogNames.at(i);
QFile(tempDir.filePath(existingLogNames.at(i))).remove();
}
#endif
#if defined(Q_OS_WIN32) #if defined(Q_OS_WIN32)
// Force AntiHooking.dll to be statically imported and loaded // Force AntiHooking.dll to be statically imported and loaded
// by ntdll on Win32 platforms by calling a dummy function. // by ntdll on Win32 platforms by calling a dummy function.
@@ -385,11 +343,6 @@ int main(int argc, char *argv[])
qWarning() << "On the Raspberry Pi, you must enable the 'fake KMS' driver in raspi-config to use Moonlight outside of the GUI environment."; qWarning() << "On the Raspberry Pi, you must enable the 'fake KMS' driver in raspi-config to use Moonlight outside of the GUI environment.";
} }
} }
// EGLFS uses OpenGLES 2.0, so we will too. Some embedded platforms may not
// even have working OpenGL implementations, so GLES is the only option.
// See https://github.com/moonlight-stream/moonlight-qt/issues/868
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengles2");
#endif #endif
} }
@@ -428,6 +381,18 @@ int main(int argc, char *argv[])
// Register custom metatypes for use in signals // Register custom metatypes for use in signals
qRegisterMetaType<NvApp>("NvApp"); qRegisterMetaType<NvApp>("NvApp");
SDL_version compileVersion;
SDL_VERSION(&compileVersion);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Compiled with SDL %d.%d.%d",
compileVersion.major, compileVersion.minor, compileVersion.patch);
SDL_version runtimeVersion;
SDL_GetVersion(&runtimeVersion);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Running with SDL %d.%d.%d",
runtimeVersion.major, runtimeVersion.minor, runtimeVersion.patch);
// Allow the display to sleep by default. We will manually use SDL_DisableScreenSaver() // Allow the display to sleep by default. We will manually use SDL_DisableScreenSaver()
// and SDL_EnableScreenSaver() when appropriate. This hint must be set before // and SDL_EnableScreenSaver() when appropriate. This hint must be set before
// initializing the SDL video subsystem to have any effect. // initializing the SDL video subsystem to have any effect.
@@ -505,58 +470,10 @@ int main(int argc, char *argv[])
QGuiApplication app(argc, argv); QGuiApplication app(argc, argv);
GlobalCommandLineParser parser;
GlobalCommandLineParser::ParseResult commandLineParserResult = parser.parse(app.arguments());
switch (commandLineParserResult) {
case GlobalCommandLineParser::ListRequested:
#ifdef USE_CUSTOM_LOGGER
// Don't log to the console since it will jumble the command output
s_SuppressVerboseOutput = true;
#endif
#ifdef Q_OS_WIN32
// Attach to the console to be able to print output.
// Since we're a /SUBSYSTEM:WINDOWS app, we won't be attached by default.
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
HANDLE conOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (conOut != INVALID_HANDLE_VALUE && conOut != NULL) {
freopen("CONOUT$", "w", stdout);
setvbuf(stdout, NULL, _IONBF, 0);
}
HANDLE conErr = GetStdHandle(STD_ERROR_HANDLE);
if (conErr != INVALID_HANDLE_VALUE && conErr != NULL) {
freopen("CONOUT$", "w", stderr);
setvbuf(stderr, NULL, _IONBF, 0);
}
}
#endif
break;
default:
break;
}
SDL_version compileVersion;
SDL_VERSION(&compileVersion);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Compiled with SDL %d.%d.%d",
compileVersion.major, compileVersion.minor, compileVersion.patch);
SDL_version runtimeVersion;
SDL_GetVersion(&runtimeVersion);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Running with SDL %d.%d.%d",
runtimeVersion.major, runtimeVersion.minor, runtimeVersion.patch);
// Apply the initial translation based on user preference // Apply the initial translation based on user preference
StreamingPreferences prefs; StreamingPreferences prefs;
prefs.retranslate(); prefs.retranslate();
// Trickily declare the translation for dialog buttons
QCoreApplication::translate("QPlatformTheme", "&Yes");
QCoreApplication::translate("QPlatformTheme", "&No");
QCoreApplication::translate("QPlatformTheme", "OK");
QCoreApplication::translate("QPlatformTheme", "Help");
QCoreApplication::translate("QPlatformTheme", "Cancel");
// After the QGuiApplication is created, the platform stuff will be initialized // After the QGuiApplication is created, the platform stuff will be initialized
// and we can set the SDL video driver to match Qt. // and we can set the SDL video driver to match Qt.
if (WMUtils::isRunningWayland() && QGuiApplication::platformName() == "xcb") { if (WMUtils::isRunningWayland() && QGuiApplication::platformName() == "xcb") {
@@ -640,25 +557,35 @@ int main(int argc, char *argv[])
// Create the identity manager on the main thread // Create the identity manager on the main thread
IdentityManager::get(); IdentityManager::get();
// We require the Material theme #ifndef Q_OS_WINRT
QQuickStyle::setStyle("Material"); // Use the dense material dark theme by default
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_STYLE")) {
// Our icons are styled for a dark theme, so we do not allow the user to override this qputenv("QT_QUICK_CONTROLS_STYLE", "Material");
qputenv("QT_QUICK_CONTROLS_MATERIAL_THEME", "Dark"); }
#else
// These are defaults that we allow the user to override // Use universal dark on WinRT
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_STYLE")) {
qputenv("QT_QUICK_CONTROLS_STYLE", "Universal");
}
#endif
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_MATERIAL_THEME")) {
qputenv("QT_QUICK_CONTROLS_MATERIAL_THEME", "Dark");
}
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_MATERIAL_ACCENT")) { if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_MATERIAL_ACCENT")) {
qputenv("QT_QUICK_CONTROLS_MATERIAL_ACCENT", "Purple"); qputenv("QT_QUICK_CONTROLS_MATERIAL_ACCENT", "Purple");
} }
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_MATERIAL_VARIANT")) { if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_MATERIAL_VARIANT")) {
qputenv("QT_QUICK_CONTROLS_MATERIAL_VARIANT", "Dense"); qputenv("QT_QUICK_CONTROLS_MATERIAL_VARIANT", "Dense");
} }
if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_UNIVERSAL_THEME")) {
qputenv("QT_QUICK_CONTROLS_UNIVERSAL_THEME", "Dark");
}
QQmlApplicationEngine engine; QQmlApplicationEngine engine;
QString initialView; QString initialView;
bool hasGUI = true;
switch (commandLineParserResult) { GlobalCommandLineParser parser;
switch (parser.parse(app.arguments())) {
case GlobalCommandLineParser::NormalStartRequested: case GlobalCommandLineParser::NormalStartRequested:
initialView = "qrc:/gui/PcView.qml"; initialView = "qrc:/gui/PcView.qml";
break; break;
@@ -683,35 +610,14 @@ int main(int argc, char *argv[])
engine.rootContext()->setContextProperty("launcher", launcher); engine.rootContext()->setContextProperty("launcher", launcher);
break; break;
} }
case GlobalCommandLineParser::PairRequested:
{
initialView = "qrc:/gui/CliPair.qml";
PairCommandLineParser pairParser;
pairParser.parse(app.arguments());
auto launcher = new CliPair::Launcher(pairParser.getHost(), pairParser.getPredefinedPin(), &app);
engine.rootContext()->setContextProperty("launcher", launcher);
break;
}
case GlobalCommandLineParser::ListRequested:
{
ListCommandLineParser listParser;
listParser.parse(app.arguments());
auto launcher = new CliListApps::Launcher(listParser.getHost(), listParser, &app);
launcher->execute(new ComputerManager(&app));
hasGUI = false;
break;
}
} }
if (hasGUI) { engine.rootContext()->setContextProperty("initialView", initialView);
engine.rootContext()->setContextProperty("initialView", initialView);
// Load the main.qml file
engine.load(QUrl(QStringLiteral("qrc:/gui/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
}
// Load the main.qml file
engine.load(QUrl(QStringLiteral("qrc:/gui/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
int err = app.exec(); int err = app.exec();
// Give worker tasks time to properly exit. Fixes PendingQuitTask // Give worker tasks time to properly exit. Fixes PendingQuitTask
+50 -38
View File
@@ -11,10 +11,6 @@
#define _GNU_SOURCE #define _GNU_SOURCE
// NOTE: This file MUST NOT include fcntl.h due to open() -> open64()
// redirection that happens when _FILE_OFFSET_BITS=64!
// See masterhook_internal.c for details.
#include <SDL.h> #include <SDL.h>
#include <dlfcn.h> #include <dlfcn.h>
#include <unistd.h> #include <unistd.h>
@@ -34,76 +30,92 @@
// Qt's DRM master FD grabbed by our hook // Qt's DRM master FD grabbed by our hook
int g_QtDrmMasterFd = -1; int g_QtDrmMasterFd = -1;
struct stat g_DrmMasterStat; struct stat64 g_DrmMasterStat;
// The DRM master FD created for SDL // The DRM master FD created for SDL
int g_SdlDrmMasterFd = -1; int g_SdlDrmMasterFd = -1;
int drmIsMaster(int fd)
{
// Detect master by attempting something that requires master.
// This method is available in Mesa DRM since Feb 2019.
return drmAuthMagic(fd, 0) != -EACCES;
}
// This hook will handle legacy DRM rendering // This hook will handle legacy DRM rendering
int drmModeSetCrtc(int fd, uint32_t crtcId, uint32_t bufferId, int drmModeSetCrtc(int fd, uint32_t crtcId, uint32_t bufferId,
uint32_t x, uint32_t y, uint32_t *connectors, int count, uint32_t x, uint32_t y, uint32_t *connectors, int count,
drmModeModeInfoPtr mode) drmModeModeInfoPtr mode)
{ {
// Grab the first DRM Master FD that makes it in here. This will be the Qt // Grab the first DRM FD that makes it in here. This will be the Qt
// EGLFS backend's DRM FD, on which we will call drmDropMaster() later. // EGLFS backend's DRM FD, which we will need later.
if (g_QtDrmMasterFd == -1 && drmIsMaster(fd)) { if (g_QtDrmMasterFd == -1) {
g_QtDrmMasterFd = fd; g_QtDrmMasterFd = fd;
fstat(g_QtDrmMasterFd, &g_DrmMasterStat); fstat64(g_QtDrmMasterFd, &g_DrmMasterStat);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Captured Qt EGLFS DRM master fd (legacy): %d", "Captured Qt EGLFS DRM master fd (legacy): %d",
g_QtDrmMasterFd); g_QtDrmMasterFd);
} }
// Call into the real thing // Call into the real thing
return ((typeof(drmModeSetCrtc)*)dlsym(RTLD_NEXT, __FUNCTION__))(fd, crtcId, bufferId, x, y, connectors, count, mode); return ((typeof(drmModeSetCrtc)*)dlsym(RTLD_NEXT, "drmModeSetCrtc"))(fd, crtcId, bufferId, x, y, connectors, count, mode);
} }
// This hook will handle atomic DRM rendering // This hook will handle atomic DRM rendering
int drmModeAtomicCommit(int fd, drmModeAtomicReqPtr req, int drmModeAtomicCommit(int fd, drmModeAtomicReqPtr req,
uint32_t flags, void *user_data) uint32_t flags, void *user_data)
{ {
// Grab the first DRM Master FD that makes it in here. This will be the Qt // Grab the first DRM FD that makes it in here. This will be the Qt
// EGLFS backend's DRM FD, on which we will call drmDropMaster() later. // EGLFS backend's DRM FD, which we will need later.
if (g_QtDrmMasterFd == -1 && drmIsMaster(fd)) { if (g_QtDrmMasterFd == -1) {
g_QtDrmMasterFd = fd; g_QtDrmMasterFd = fd;
fstat(g_QtDrmMasterFd, &g_DrmMasterStat); fstat64(g_QtDrmMasterFd, &g_DrmMasterStat);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
"Captured Qt EGLFS DRM master fd (atomic): %d", "Captured Qt EGLFS DRM master fd (atomic): %d",
g_QtDrmMasterFd); g_QtDrmMasterFd);
} }
// Call into the real thing // Call into the real thing
return ((typeof(drmModeAtomicCommit)*)dlsym(RTLD_NEXT, __FUNCTION__))(fd, req, flags, user_data); return ((typeof(drmModeAtomicCommit)*)dlsym(RTLD_NEXT, "drmModeAtomicCommit"))(fd, req, flags, user_data);
} }
// This hook will handle SDL's open() on the DRM device. We just need to // This hook will handle SDL's open() on the DRM device. We just need to
// hook this variant of open(), since that's what SDL uses. When we see // hook this variant of open(), since that's what SDL uses. When we see
// the open a FD for the same card as the Qt DRM master FD, we'll drop // the open a FD for the same card as the Qt DRM master FD, we'll drop
// master on the Qt FD to allow the new FD to have master. // master on the Qt FD to allow the new FD to have master.
int openHook(const char *funcname, const char *pathname, int flags, va_list va); int open(const char *pathname, int flags)
int open(const char *pathname, int flags, ...)
{ {
va_list va; // Call the real thing to do the open operation
va_start(va, flags); int fd = ((typeof(open)*)dlsym(RTLD_NEXT, "open"))(pathname, flags);
int fd = openHook(__FUNCTION__, pathname, flags, va);
va_end(va); // If the file was successfully opened and we have a DRM master FD,
return fd; // check if the FD we just opened is a DRM device.
} if (fd >= 0 && g_QtDrmMasterFd != -1) {
if (strncmp(pathname, "/dev/dri/card", 13) == 0) {
// It's a DRM device, but is it _our_ DRM device?
struct stat64 fdstat;
fstat64(fd, &fdstat);
if (g_DrmMasterStat.st_dev == fdstat.st_dev &&
g_DrmMasterStat.st_ino == fdstat.st_ino) {
// It is our device. Time to do the magic!
// This code assumes SDL only ever opens a single FD
// for a given DRM device.
SDL_assert(g_SdlDrmMasterFd == -1);
// Drop master on Qt's FD so we can pick it up for SDL.
if (drmDropMaster(g_QtDrmMasterFd) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to drop master on Qt DRM FD: %d",
errno);
// Hope for the best
return fd;
}
// We are not allowed to call drmSetMaster() without CAP_SYS_ADMIN,
// but since we just dropped the master, we can become master by
// simply creating a new FD. Let's do it.
close(fd);
fd = ((typeof(open)*)dlsym(RTLD_NEXT, "open"))(pathname, flags);
g_SdlDrmMasterFd = fd;
}
}
}
int open64(const char *pathname, int flags, ...)
{
va_list va;
va_start(va, flags);
int fd = openHook(__FUNCTION__, pathname, flags, va);
va_end(va);
return fd; return fd;
} }
@@ -112,7 +124,7 @@ int open64(const char *pathname, int flags, ...)
int close(int fd) int close(int fd)
{ {
// Call the real thing // Call the real thing
int ret = ((typeof(close)*)dlsym(RTLD_NEXT, __FUNCTION__))(fd); int ret = ((typeof(close)*)dlsym(RTLD_NEXT, "close"))(fd);
if (ret == 0) { if (ret == 0) {
// If we just closed the SDL DRM master FD, restore master // If we just closed the SDL DRM master FD, restore master
// to the Qt DRM FD. This works because the Qt DRM master FD // to the Qt DRM FD. This works because the Qt DRM master FD
-90
View File
@@ -1,90 +0,0 @@
// This file contains the private implementation of the open() hook
// which must be in a separate compilation unit due to fcntl.h doing
// unwanted redirection of open() to open64().
#define _GNU_SOURCE
#include <SDL.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
// __OPEN_NEEDS_MODE is a glibc-ism, so define it ourselves for other libc
#ifndef __OPEN_NEEDS_MODE
#ifdef __O_TMPFILE
# define __OPEN_NEEDS_MODE(oflag) \
(((oflag) & O_CREAT) != 0 || ((oflag) & __O_TMPFILE) == __O_TMPFILE)
#else
# define __OPEN_NEEDS_MODE(oflag) (((oflag) & O_CREAT) != 0)
#endif
#endif
#if SDL_VERSION_ATLEAST(2, 0, 15)
extern int g_QtDrmMasterFd;
extern struct stat g_DrmMasterStat;
extern int g_SdlDrmMasterFd;
int openHook(const char *funcname, const char *pathname, int flags, va_list va)
{
int fd;
mode_t mode;
// Call the real thing to do the open operation
if (__OPEN_NEEDS_MODE(flags)) {
mode = va_arg(va, mode_t);
fd = ((typeof(open)*)dlsym(RTLD_NEXT, funcname))(pathname, flags, mode);
}
else {
mode = 0;
fd = ((typeof(open)*)dlsym(RTLD_NEXT, funcname))(pathname, flags);
}
// If the file was successfully opened and we have a DRM master FD,
// check if the FD we just opened is a DRM device.
if (fd >= 0 && g_QtDrmMasterFd != -1) {
if (strncmp(pathname, "/dev/dri/card", 13) == 0) {
// It's a DRM device, but is it _our_ DRM device?
struct stat fdstat;
fstat(fd, &fdstat);
if (g_DrmMasterStat.st_dev == fdstat.st_dev &&
g_DrmMasterStat.st_ino == fdstat.st_ino) {
// It is our device. Time to do the magic!
// This code assumes SDL only ever opens a single FD
// for a given DRM device.
SDL_assert(g_SdlDrmMasterFd == -1);
// Drop master on Qt's FD so we can pick it up for SDL.
if (drmDropMaster(g_QtDrmMasterFd) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Failed to drop master on Qt DRM FD: %d",
errno);
// Hope for the best
return fd;
}
// We are not allowed to call drmSetMaster() without CAP_SYS_ADMIN,
// but since we just dropped the master, we can become master by
// simply creating a new FD. Let's do it.
close(fd);
if (__OPEN_NEEDS_MODE(flags)) {
fd = ((typeof(open)*)dlsym(RTLD_NEXT, funcname))(pathname, flags, mode);
}
else {
fd = ((typeof(open)*)dlsym(RTLD_NEXT, funcname))(pathname, flags);
}
g_SdlDrmMasterFd = fd;
}
}
}
return fd;
}
#endif
-9
View File
@@ -9,7 +9,6 @@
QString Path::s_CacheDir; QString Path::s_CacheDir;
QString Path::s_LogDir; QString Path::s_LogDir;
QString Path::s_BoxArtCacheDir; QString Path::s_BoxArtCacheDir;
QString Path::s_QmlCacheDir;
QString Path::getLogDir() QString Path::getLogDir()
{ {
@@ -23,12 +22,6 @@ QString Path::getBoxArtCacheDir()
return s_BoxArtCacheDir; return s_BoxArtCacheDir;
} }
QString Path::getQmlCacheDir()
{
Q_ASSERT(!s_QmlCacheDir.isEmpty());
return s_QmlCacheDir;
}
QByteArray Path::readDataFile(QString fileName) QByteArray Path::readDataFile(QString fileName)
{ {
QFile dataFile(getDataFilePath(fileName)); QFile dataFile(getDataFilePath(fileName));
@@ -104,7 +97,6 @@ void Path::initialize(bool portable)
if (portable) { if (portable) {
s_LogDir = QDir::currentPath(); s_LogDir = QDir::currentPath();
s_BoxArtCacheDir = QDir::currentPath() + "/boxart"; s_BoxArtCacheDir = QDir::currentPath() + "/boxart";
s_QmlCacheDir = QDir::currentPath() + "/qmlcache";
// In order for the If-Modified-Since logic to work in MappingFetcher, // In order for the If-Modified-Since logic to work in MappingFetcher,
// the cache directory must be different than the current directory. // the cache directory must be different than the current directory.
@@ -120,6 +112,5 @@ void Path::initialize(bool portable)
#endif #endif
s_CacheDir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); s_CacheDir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
s_BoxArtCacheDir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/boxart"; s_BoxArtCacheDir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/boxart";
s_QmlCacheDir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/qmlcache";
} }
} }
+1 -2
View File
@@ -7,8 +7,8 @@ class Path
{ {
public: public:
static QString getLogDir(); static QString getLogDir();
static QString getBoxArtCacheDir(); static QString getBoxArtCacheDir();
static QString getQmlCacheDir();
static QByteArray readDataFile(QString fileName); static QByteArray readDataFile(QString fileName);
static void writeCacheFile(QString fileName, QByteArray data); static void writeCacheFile(QString fileName, QByteArray data);
@@ -24,5 +24,4 @@ private:
static QString s_CacheDir; static QString s_CacheDir;
static QString s_LogDir; static QString s_LogDir;
static QString s_BoxArtCacheDir; static QString s_BoxArtCacheDir;
static QString s_QmlCacheDir;
}; };
-1
View File
@@ -18,6 +18,5 @@
<file>gui/NavigableMessageDialog.qml</file> <file>gui/NavigableMessageDialog.qml</file>
<file>gui/NavigableDialog.qml</file> <file>gui/NavigableDialog.qml</file>
<file>gui/CenteredGridView.qml</file> <file>gui/CenteredGridView.qml</file>
<file>gui/CliPair.qml</file>
</qresource> </qresource>
</RCC> </RCC>
-2
View File
@@ -1,2 +0,0 @@
[Platforms]
WindowsArguments = darkmode=1
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#fff"><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/><path d="M0 0h24v24H0z" fill="none"/></svg>

After

Width:  |  Height:  |  Size: 325 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48" fill="#fff">
<path d="M0 0h48v48H0z" fill="none"/>
<path d="M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm-4 29V15l12 9-12 9z"/>
</svg>

After

Width:  |  Height:  |  Size: 250 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48" viewBox="0 -960 960 960" width="48" fill="#FFFFFF"><path d="M370-206q-26 14-49 1t-23-40v-477q0-26 23-39t49 1l372 239q23 14 23 38.5T742-445L370-206Z"/></svg>

Before

Width:  |  Height:  |  Size: 208 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48" viewBox="0 -960 960 960" width="48" fill="#FFFFFF"><path d="M309-218q-38.425 0-64.712-26.288Q218-270.575 218-309v-342q0-38.838 26.288-65.419Q270.575-743 309-743h342q38.838 0 65.419 26.581Q743-689.838 743-651v342q0 38.425-26.581 64.712Q689.838-218 651-218H309Z"/></svg>

Before

Width:  |  Height:  |  Size: 320 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="white"><path d="M108.018-98.001q-14.17 0-25.267-7.472-11.097-7.471-17.595-17.605-6.68-10.077-7.147-23-.468-12.923 7.085-26.165l372.43-640.512q7.553-13.242 18.399-18.665 10.846-5.424 24.077-5.424 13.231 0 24.077 5.424 10.846 5.423 18.399 18.665l372.43 640.512q7.553 13.242 7.085 26.165-.468 12.923-7.147 23-6.498 10.134-17.595 17.605-11.097 7.472-25.267 7.472H108.018ZM481-220.693q18.731 0 32.019-13.288 13.288-13.288 13.288-32.019 0-18.731-13.288-32.019-13.288-13.288-32.019-13.288-18.731 0-32.019 13.288-13.288 13.288-13.288 32.019 0 18.731 13.288 32.019 13.288 13.288 32.019 13.288Zm.013-127.614q17.756 0 30.371-12.625 12.615-12.625 12.615-30.374v-118.002q0-17.75-12.628-30.374-12.629-12.625-30.384-12.625-17.756 0-30.371 12.625-12.615 12.624-12.615 30.374v118.002q0 17.749 12.628 30.374 12.629 12.625 30.384 12.625Z"/></svg>

Before

Width:  |  Height:  |  Size: 921 B

+6 -13
View File
@@ -4,10 +4,9 @@
<file>res/desktop_windows-48px.svg</file> <file>res/desktop_windows-48px.svg</file>
<file>res/ic_add_to_queue_white_48px.svg</file> <file>res/ic_add_to_queue_white_48px.svg</file>
<file>res/baseline-lock-24px.svg</file> <file>res/baseline-lock-24px.svg</file>
<file>res/play_arrow_FILL1_wght700_GRAD200_opsz48.svg</file> <file>res/baseline-play_circle_filled_white-48px.svg</file>
<file>res/baseline-warning-24px.svg</file> <file>res/baseline-warning-24px.svg</file>
<file>res/warning_FILL1_wght300_GRAD200_opsz24.svg</file> <file>res/baseline-cancel-24px.svg</file>
<file>res/stop_FILL1_wght700_GRAD200_opsz48.svg</file>
<file>res/no_app_image.png</file> <file>res/no_app_image.png</file>
<file>res/settings.svg</file> <file>res/settings.svg</file>
<file>res/arrow_left.svg</file> <file>res/arrow_left.svg</file>
@@ -22,8 +21,8 @@
<file>languages/qml_de.qm</file> <file>languages/qml_de.qm</file>
<file>languages/qml_fr.ts</file> <file>languages/qml_fr.ts</file>
<file>languages/qml_fr.qm</file> <file>languages/qml_fr.qm</file>
<file>languages/qml_zh_CN.ts</file> <file>languages/qml_zh_cn.ts</file>
<file>languages/qml_zh_CN.qm</file> <file>languages/qml_zh_cn.qm</file>
<file>languages/qml_nb_NO.ts</file> <file>languages/qml_nb_NO.ts</file>
<file>languages/qml_nb_NO.qm</file> <file>languages/qml_nb_NO.qm</file>
<file>languages/qml_ru.ts</file> <file>languages/qml_ru.ts</file>
@@ -48,8 +47,8 @@
<file>languages/qml_tr.qm</file> <file>languages/qml_tr.qm</file>
<file>languages/qml_uk.ts</file> <file>languages/qml_uk.ts</file>
<file>languages/qml_uk.qm</file> <file>languages/qml_uk.qm</file>
<file>languages/qml_zh_TW.ts</file> <file>languages/qml_zh_Hant.ts</file>
<file>languages/qml_zh_TW.qm</file> <file>languages/qml_zh_Hant.qm</file>
<file>languages/qml_el.ts</file> <file>languages/qml_el.ts</file>
<file>languages/qml_el.qm</file> <file>languages/qml_el.qm</file>
<file>languages/qml_hi.ts</file> <file>languages/qml_hi.ts</file>
@@ -58,12 +57,6 @@
<file>languages/qml_it.qm</file> <file>languages/qml_it.qm</file>
<file>languages/qml_pt.ts</file> <file>languages/qml_pt.ts</file>
<file>languages/qml_pt.qm</file> <file>languages/qml_pt.qm</file>
<file>languages/qml_pl.ts</file>
<file>languages/qml_pl.qm</file>
<file>languages/qml_cs.ts</file>
<file>languages/qml_cs.qm</file>
<file>languages/qml_he.ts</file>
<file>languages/qml_he.qm</file>
<!-- Don't include pt_BR until it is more complete --> <!-- Don't include pt_BR until it is more complete -->
<!--file>languages/qml_pt_BR.qm</file--> <!--file>languages/qml_pt_BR.qm</file-->
<!--file>languages/qml_pt_BR.ts</file--> <!--file>languages/qml_pt_BR.ts</file-->
+7 -18
View File
@@ -8,32 +8,26 @@
#define COMPAT_KEY "latestsupportedversion-" #define COMPAT_KEY "latestsupportedversion-"
CompatFetcher::CompatFetcher(QObject *parent) : CompatFetcher::CompatFetcher(QObject *parent) :
QObject(parent) QObject(parent),
m_Nam(this)
{ {
m_Nam = new QNetworkAccessManager(this);
// Never communicate over HTTP // Never communicate over HTTP
m_Nam->setStrictTransportSecurityEnabled(true); m_Nam.setStrictTransportSecurityEnabled(true);
// Allow HTTP redirects // Allow HTTP redirects
m_Nam->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy); m_Nam.setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy);
connect(m_Nam, &QNetworkAccessManager::finished, connect(&m_Nam, &QNetworkAccessManager::finished,
this, &CompatFetcher::handleCompatInfoFetched); this, &CompatFetcher::handleCompatInfoFetched);
} }
void CompatFetcher::start() void CompatFetcher::start()
{ {
if (!m_Nam) {
Q_ASSERT(m_Nam);
return;
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) && QT_VERSION < QT_VERSION_CHECK(5, 15, 1) && !defined(QT_NO_BEARERMANAGEMENT) #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) && QT_VERSION < QT_VERSION_CHECK(5, 15, 1) && !defined(QT_NO_BEARERMANAGEMENT)
// HACK: Set network accessibility to work around QTBUG-80947 (introduced in Qt 5.14.0 and fixed in Qt 5.15.1) // HACK: Set network accessibility to work around QTBUG-80947 (introduced in Qt 5.14.0 and fixed in Qt 5.15.1)
QT_WARNING_PUSH QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED QT_WARNING_DISABLE_DEPRECATED
m_Nam->setNetworkAccessible(QNetworkAccessManager::Accessible); m_Nam.setNetworkAccessible(QNetworkAccessManager::Accessible);
QT_WARNING_POP QT_WARNING_POP
#endif #endif
@@ -47,7 +41,7 @@ void CompatFetcher::start()
#endif #endif
// We'll get a callback when this is finished // We'll get a callback when this is finished
m_Nam->get(request); m_Nam.get(request);
} }
bool CompatFetcher::isGfeVersionSupported(QString gfeVersion) bool CompatFetcher::isGfeVersionSupported(QString gfeVersion)
@@ -125,11 +119,6 @@ void CompatFetcher::handleCompatInfoFetched(QNetworkReply* reply)
{ {
Q_ASSERT(reply->isFinished()); Q_ASSERT(reply->isFinished());
// Delete the QNetworkAccessManager to free resources and
// prevent the bearer plugin from polling in the background.
m_Nam->deleteLater();
m_Nam = nullptr;
if (reply->error() == QNetworkReply::NoError) { if (reply->error() == QNetworkReply::NoError) {
// Queue the reply for deletion // Queue the reply for deletion
reply->deleteLater(); reply->deleteLater();
+1 -1
View File
@@ -18,5 +18,5 @@ private slots:
void handleCompatInfoFetched(QNetworkReply* reply); void handleCompatInfoFetched(QNetworkReply* reply);
private: private:
QNetworkAccessManager* m_Nam; QNetworkAccessManager m_Nam;
}; };
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff. Show more