From 56d660dbdb1516e93db0a41683d4d76864f50ef3 Mon Sep 17 00:00:00 2001 From: Guillaume Meunier Date: Sun, 1 Sep 2024 15:31:55 +0200 Subject: [PATCH] Add server dashboard --- .github/workflows/Build.yml | 5 +- .github/workflows/Format.yml | 1 + CMakeLists.txt | 17 +- build.gradle | 1 + dashboard/CMakeLists.txt | 41 + dashboard/gui_config.h.in | 24 + dashboard/main.cpp | 84 +++ dashboard/main_window.cpp | 539 ++++++++++++++ dashboard/main_window.h | 103 +++ dashboard/main_window.ui | 513 +++++++++++++ dashboard/rectangle_partitionner.cpp | 825 +++++++++++++++++++++ dashboard/rectangle_partitionner.h | 101 +++ dashboard/settings.cpp | 432 +++++++++++ dashboard/settings.h | 50 ++ dashboard/settings.ui | 786 ++++++++++++++++++++ dashboard/wivrn_qdbus_types.h | 10 + dashboard/wivrn_server.cpp | 240 ++++++ dashboard/wivrn_server.h | 197 +++++ dashboard/wizard.cpp | 406 ++++++++++ dashboard/wizard.h | 70 ++ dashboard/wizard.ui | 526 +++++++++++++ dbus/io.github.wivrn.Server.xml | 14 +- flatpak/io.github.wivrn.wivrn.desktop | 3 +- flatpak/io.github.wivrn.wivrn.metainfo.xml | 14 +- flatpak/io.github.wivrn.wivrn.yml | 12 +- wivrn-dashboard.qrc | 6 + 26 files changed, 5008 insertions(+), 12 deletions(-) create mode 100644 dashboard/CMakeLists.txt create mode 100644 dashboard/gui_config.h.in create mode 100644 dashboard/main.cpp create mode 100644 dashboard/main_window.cpp create mode 100644 dashboard/main_window.h create mode 100644 dashboard/main_window.ui create mode 100644 dashboard/rectangle_partitionner.cpp create mode 100644 dashboard/rectangle_partitionner.h create mode 100644 dashboard/settings.cpp create mode 100644 dashboard/settings.h create mode 100644 dashboard/settings.ui create mode 100644 dashboard/wivrn_qdbus_types.h create mode 100644 dashboard/wivrn_server.cpp create mode 100644 dashboard/wivrn_server.h create mode 100644 dashboard/wizard.cpp create mode 100644 dashboard/wizard.h create mode 100644 dashboard/wizard.ui create mode 100644 wivrn-dashboard.qrc diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index ebd9ec4d..f237c708 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -25,7 +25,7 @@ jobs: - name: Install dependencies run: > - sudo apt-get update && sudo apt-get install libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libavahi-glib-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev nlohmann-json3-dev libpulse-dev xz-utils libpipewire-0.3-dev libcli11-dev + sudo apt-get update && sudo apt-get install libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libavahi-glib-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev nlohmann-json3-dev libpulse-dev xz-utils libpipewire-0.3-dev libcli11-dev qt6-base-dev qt6-tools-dev - name: Prepare Vulkan SDK uses: humbletim/setup-vulkan-sdk@286ed76c72de45dbf50c515779cf4ca2f6aa3944 with: @@ -41,6 +41,7 @@ jobs: -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_INSTALL_PREFIX=/usr -DWIVRN_BUILD_SERVER=ON + -DWIVRN_BUILD_DASHBOARD=ON -DWIVRN_BUILD_CLIENT=OFF -DWIVRN_BUILD_DISSECTOR=OFF -DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON @@ -128,6 +129,7 @@ jobs: -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_INSTALL_PREFIX=/usr -DWIVRN_BUILD_SERVER=OFF + -DWIVRN_BUILD_DASHBOARD=OFF -DWIVRN_BUILD_CLIENT=ON -DWIVRN_BUILD_DISSECTOR=OFF -DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON @@ -163,6 +165,7 @@ jobs: -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_INSTALL_PREFIX=/usr -DWIVRN_BUILD_SERVER=OFF + -DWIVRN_BUILD_DASHBOARD=OFF -DWIVRN_BUILD_CLIENT=OFF -DWIVRN_BUILD_DISSECTOR=ON -DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON diff --git a/.github/workflows/Format.yml b/.github/workflows/Format.yml index 6aba9c5d..0d1919b3 100644 --- a/.github/workflows/Format.yml +++ b/.github/workflows/Format.yml @@ -11,6 +11,7 @@ jobs: path: - 'client' - 'server' + - 'dashboard' - 'common' - 'tools/wireshark' steps: diff --git a/CMakeLists.txt b/CMakeLists.txt index 42f74f6e..f977e1a6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -26,6 +26,7 @@ auto_option(WIVRN_USE_SYSTEMD "Use libsystemd" AUTO) option(WIVRN_USE_ANDROID_VALIDATION_LAYER "Download the android version of the Vulkan validation layer" OFF) option(WIVRN_BUILD_CLIENT "Build WiVRn client" OFF) option(WIVRN_BUILD_SERVER "Build WiVRn server" ON) +option(WIVRN_BUILD_DASHBOARD "Build WiVRn dashboard" ON) option(WIVRN_BUILD_DISSECTOR "Build Wireshark dissector" OFF) option(WIVRN_WERROR "Treat warnings as errors" OFF) @@ -43,6 +44,8 @@ option(WIVRN_OPENXR_INSTALL_ABSOLUTE_RUNTIME_PATH OFF) option(ENABLE_COLOURED_OUTPUT "Always produce ANSI-coloured output (GNU/Clang only)." ON) +set(WIVRN_CLIENT_URL "https://github.com/WiVRn/WiVRn/releases/latest/download/WiVRn-standard-release.apk" CACHE STRING "URL used to download the client in the GUI") + if(ENABLE_COLOURED_OUTPUT) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") add_compile_options(-fdiagnostics-color=always) @@ -144,6 +147,13 @@ if (WIVRN_BUILD_SERVER) pkg_check_modules(glib2 REQUIRED IMPORTED_TARGET glib-2.0 gio-2.0 gio-unix-2.0) endif() +if (WIVRN_BUILD_DASHBOARD) + find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets DBus Network LinguistTools) + set(CMAKE_AUTOMOC ON) + set(CMAKE_AUTORCC ON) + set(CMAKE_AUTOUIC ON) +endif() + if (WIVRN_BUILD_CLIENT AND NOT ANDROID) pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET libavcodec libavutil libswscale libavfilter) find_package(Fontconfig REQUIRED) @@ -219,9 +229,14 @@ if (WIVRN_BUILD_SERVER) message("\tsystemd: ${WIVRN_USE_SYSTEMD}") endif() +if (WIVRN_BUILD_DASHBOARD) + add_subdirectory(dashboard) + set_target_properties(wivrn-dashboard PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/server) +endif() + add_subdirectory(tools) -foreach(TARGET_NAME wivrn wivrn-server wivrn-common wivrn-dissector) +foreach(TARGET_NAME wivrn wivrn-server wivrn-dashboard wivrn-common wivrn-dissector) if(TARGET ${TARGET_NAME}) target_compile_options(${TARGET_NAME} PRIVATE -fdiagnostics-color -Wall -Wextra -pedantic diff --git a/build.gradle b/build.gradle index d4ff7b97..9c363695 100644 --- a/build.gradle +++ b/build.gradle @@ -85,6 +85,7 @@ android { '-DWIVRN_USE_SYSTEM_FREETYPE=OFF', '-DWIVRN_BUILD_CLIENT=ON', '-DWIVRN_BUILD_SERVER=OFF', + '-DWIVRN_BUILD_DASHBOARD=OFF', '-DWIVRN_WERROR=ON' resValue "string", "app_name", "WiVRn" } diff --git a/dashboard/CMakeLists.txt b/dashboard/CMakeLists.txt new file mode 100644 index 00000000..8cc2f32a --- /dev/null +++ b/dashboard/CMakeLists.txt @@ -0,0 +1,41 @@ +qt_add_executable(wivrn-dashboard + main.cpp + main_window.cpp + main_window.h + main_window.ui + settings.cpp + settings.h + settings.ui + wivrn_server.cpp + wivrn_server.h + wizard.cpp + wizard.h + wizard.ui + rectangle_partitionner.cpp + rectangle_partitionner.h + ../wivrn-dashboard.qrc + ${CMAKE_CURRENT_BINARY_DIR}/../common/version.cpp +) + +set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/../dbus/io.github.wivrn.Server.xml PROPERTIES INCLUDE "${CMAKE_CURRENT_SOURCE_DIR}/wivrn_qdbus_types.h") +qt_add_dbus_interface(DBUS_INTERFACE_SRC ${CMAKE_CURRENT_SOURCE_DIR}/../dbus/io.github.wivrn.Server.xml wivrn_server_dbus) +target_sources(wivrn-dashboard PRIVATE ${DBUS_INTERFACE_SRC}) + +target_compile_features(wivrn-dashboard PRIVATE cxx_std_20) +target_include_directories(wivrn-dashboard PRIVATE ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}) + +configure_file(gui_config.h.in gui_config.h) + +target_link_libraries(wivrn-dashboard PRIVATE + wivrn-common + Qt6::Core + Qt6::Gui + Qt6::Widgets + Qt6::DBus + Qt6::Network +) + +file(GLOB TRANSLATION_FILES ${CMAKE_CURRENT_SOURCE_DIR}/wivrn_*.ts) +qt_add_translations(wivrn-dashboard TS_FILES ${TRANSLATION_FILES}) + +install(TARGETS wivrn-dashboard) diff --git a/dashboard/gui_config.h.in b/dashboard/gui_config.h.in new file mode 100644 index 00000000..8d323438 --- /dev/null +++ b/dashboard/gui_config.h.in @@ -0,0 +1,24 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * Copyright (C) 2024 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#define WIVRN_CLIENT_URL "@WIVRN_CLIENT_URL@" + +#define WORKAROUND_QTBUG_90005 // See https://bugreports.qt.io/browse/QTBUG-90005 diff --git a/dashboard/main.cpp b/dashboard/main.cpp new file mode 100644 index 00000000..ec027941 --- /dev/null +++ b/dashboard/main.cpp @@ -0,0 +1,84 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "main_window.h" +#include "wizard.h" + +namespace xrt::drivers::wivrn +{ +extern const char git_version[]; +} + +int main(int argc, char * argv[]) +{ + QApplication app(argc, argv); + + app.setApplicationName("wivrn-dashboard"); + app.setOrganizationName("wivrn"); + app.setApplicationVersion(xrt::drivers::wivrn::git_version); + app.setDesktopFileName("io.github.wivrn.wivrn"); + + QTranslator translator; + + QLocale locale = QLocale::system(); + if (translator.load(locale, "wivrn", "_", ":/i18n")) + { + qDebug() << "Adding translator for " << locale; + app.installTranslator(&translator); + } + else + { + qDebug() << "Cannot add translator for " << locale; + } + + app.setApplicationDisplayName(QObject::tr("WiVRn dashboard")); + + std::unique_ptr wizard_window; + + // The main window is created before QWizard::finished so that the + // server is started in the wizard + auto main = std::make_unique(); + + QSettings settings; + if (settings.value("first_run", true).toBool()) + { + wizard_window.reset(new wizard); + wizard_window->show(); + + QObject::connect(wizard_window.get(), &QWizard::finished, [&](int value) { + settings.setValue("first_run", false); + + wizard_window.release()->deleteLater(); + main->show(); + }); + } + else + { + main->show(); + } + + return app.exec(); +} diff --git a/dashboard/main_window.cpp b/dashboard/main_window.cpp new file mode 100644 index 00000000..d535ad79 --- /dev/null +++ b/dashboard/main_window.cpp @@ -0,0 +1,539 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "main_window.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "exit_codes.h" +#include "settings.h" +#include "ui_main_window.h" +#include "wivrn_server.h" +#include "wizard.h" + +#include "gui_config.h" + +Q_LOGGING_CATEGORY(wivrn_log_category, "wivrn") + +enum class server_state +{ + stopped = 0, + started = 1 +}; + +main_window::main_window() +{ + ui = new Ui::MainWindow; + ui->setupUi(this); + + if (QSystemTrayIcon::isSystemTrayAvailable()) + { + action_show.setIcon(QIcon::fromTheme("settings-configure")); + action_hide.setIcon(QIcon::fromTheme("settings-configure")); + action_exit.setIcon(QIcon::fromTheme("application-exit")); + + systray_menu.addAction(&action_show); + systray_menu.addAction(&action_hide); + systray_menu.addAction(&action_exit); + + systray.setToolTip("WiVRn"); + systray.setContextMenu(&systray_menu); + systray.show(); + + connect(&action_show, &QAction::triggered, this, &QMainWindow::show); + connect(&action_hide, &QAction::triggered, this, &QMainWindow::hide); + connect(&action_exit, &QAction::triggered, this, [&]() { QApplication::quit(); }); + + connect(&systray, &QSystemTrayIcon::activated, this, [&](QSystemTrayIcon::ActivationReason reason) { + switch (reason) + { + case QSystemTrayIcon::ActivationReason::Trigger: + setVisible(!isVisible()); + break; + + default: + break; + } + }); + } + + server_process_timeout = new QTimer; + server_process_timeout->setInterval(std::chrono::seconds(1)); + server_process_timeout->setSingleShot(true); + connect(server_process_timeout, &QTimer::timeout, this, &main_window::on_server_start_timeout); + + server_interface = new wivrn_server(this); + + connect(server_interface, &wivrn_server::serverRunningChanged, this, &main_window::on_server_running_changed); + connect(server_interface, &wivrn_server::headsetConnectedChanged, this, &main_window::on_headset_connected_changed); + + if (server_interface->isServerRunning()) + on_server_dbus_registered(); + else + start_server(); + + connect(server_interface, &wivrn_server::recommendedEyeSizeChanged, this, &main_window::on_recommended_eye_size_changed); + connect(server_interface, &wivrn_server::availableRefreshRatesChanged, this, &main_window::on_available_refresh_rates_changed); + connect(server_interface, &wivrn_server::preferredRefreshRateChanged, this, &main_window::on_preferred_refresh_rate_changed); + connect(server_interface, &wivrn_server::eyeGazeChanged, this, &main_window::on_eye_gaze_changed); + connect(server_interface, &wivrn_server::faceTrackingChanged, this, &main_window::on_face_tracking_changed); + connect(server_interface, &wivrn_server::fieldOfViewChanged, this, &main_window::on_field_of_view_changed); + connect(server_interface, &wivrn_server::handTrackingChanged, this, &main_window::on_hand_tracking_changed); + connect(server_interface, &wivrn_server::micChannelsChanged, this, &main_window::on_mic_changed); + connect(server_interface, &wivrn_server::micSampleRateChanged, this, &main_window::on_mic_changed); + connect(server_interface, &wivrn_server::speakerChannelsChanged, this, &main_window::on_speaker_changed); + connect(server_interface, &wivrn_server::speakerSampleRateChanged, this, &main_window::on_speaker_changed); + connect(server_interface, &wivrn_server::supportedCodecsChanged, this, &main_window::on_supported_codecs_changed); + connect(server_interface, &wivrn_server::steamCommandChanged, this, &main_window::on_steam_command_changed); + + connect(ui->button_start, &QPushButton::clicked, this, &main_window::start_server); + connect(ui->button_stop, &QPushButton::clicked, this, &main_window::stop_server); + connect(ui->button_settings, &QPushButton::clicked, this, &main_window::on_action_settings); + connect(ui->button_disconnect, &QPushButton::clicked, this, &main_window::disconnect_client); + connect(ui->button_wizard, &QPushButton::clicked, this, &main_window::on_action_wizard); + connect(ui->button_details, &QPushButton::toggled, this, &main_window::on_button_details_toggled); + + connect(ui->button_about, &QPushButton::clicked, this, []() { QApplication::aboutQt(); }); + connect(ui->button_exit, &QPushButton::clicked, this, []() { QApplication::quit(); }); + + connect(ui->copy_steam_command, &QPushButton::clicked, this, [&]() { + QGuiApplication::clipboard()->setText(ui->label_steam_command->text()); + }); + + retranslate(); +} + +main_window::~main_window() +{ + delete server_process_timeout; + server_process_timeout = nullptr; + + if (server_process) + { + // Disconnect signals to avoid receiving signals about the server crashing + disconnect(server_process, &QProcess::finished, this, &main_window::on_server_finished); + disconnect(server_process, &QProcess::errorOccurred, this, &main_window::on_server_error_occurred); + server_process->terminate(); + server_process->waitForFinished(); + delete server_process; + server_process = nullptr; + } + + delete ui; + ui = nullptr; +} + +void main_window::changeEvent(QEvent * e) +{ + QWidget::changeEvent(e); + + switch (e->type()) + { + case QEvent::LanguageChange: + retranslate(); + break; + + default: + break; + } +} + +bool main_window::event(QEvent * e) +{ +#ifdef WORKAROUND_QTBUG_90005 + if (wizard_window and e->type() == QEvent::WindowActivate) + { + wizard_window->activateWindow(); + return true; + } + else if (settings_window and e->type() == QEvent::WindowActivate) + { + settings_window->activateWindow(); + return true; + } + else +#endif + return QMainWindow::event(e); +} + +void main_window::retranslate() +{ + ui->retranslateUi(this); + ui->label_how_to_connect->setText(tr("Start the WiVRn app on your headset and connect to \"%1\".").arg(server_interface->hostname()) + "\n\n" + tr("If the server is not visible or the connection fails, check that port 5353 (UDP) and 9757 (TCP and UDP) are open in your firewall.")); + + action_show.setText(tr("&Show GUI")); + action_hide.setText(tr("&Hide GUI")); + action_exit.setText(tr("&Exit")); + + if (server_interface->isHeadsetConnected()) + { + on_headset_connected_changed(true); + + on_recommended_eye_size_changed(server_interface->recommendedEyeSize()); + on_available_refresh_rates_changed(server_interface->availableRefreshRates()); + on_preferred_refresh_rate_changed(server_interface->preferredRefreshRate()); + on_eye_gaze_changed(server_interface->eyeGaze()); + on_face_tracking_changed(server_interface->faceTracking()); + on_field_of_view_changed(server_interface->fieldOfView()); + on_hand_tracking_changed(server_interface->handTracking()); + on_mic_changed(); + on_speaker_changed(); + on_supported_codecs_changed(server_interface->supportedCodecs()); + on_steam_command_changed(server_interface->steamCommand()); + } + else + { + on_headset_connected_changed(false); + } +} + +void main_window::closeEvent(QCloseEvent * event) +{ + QMainWindow::closeEvent(event); + QCoreApplication::quit(); +} + +void main_window::setVisible(bool visible) +{ + if (visible) + { + action_show.setVisible(false); + action_hide.setVisible(true); + } + else + { + action_show.setVisible(true); + action_hide.setVisible(false); + } + + QMainWindow::setVisible(visible); +} + +void main_window::on_server_running_changed(bool running) +{ + if (running) + { + on_server_dbus_registered(); + + ui->stacked_widget_server->setCurrentIndex((int)server_state::started); + ui->group_client->setEnabled(true); + + ui->button_stop->setEnabled(true); + ui->button_settings->setEnabled(true); + } + else + { + ui->stacked_widget_server->setCurrentIndex((int)server_state::stopped); + ui->group_client->setEnabled(false); + + ui->button_start->setEnabled(true); + } +} + +void main_window::on_headset_connected_changed(bool connected) +{ + if (connected) + { + ui->label_client_status->setText(tr("Connected")); + } + else + { + ui->label_client_status->setText(tr("Not connected")); + } + + ui->button_disconnect->setVisible(connected); + ui->button_wizard->setHidden(connected); + ui->button_details->setVisible(connected); + ui->headset_properties->setVisible(connected and ui->button_details->isChecked()); + + ui->label_how_to_connect->setHidden(connected); +} + +void main_window::on_button_details_toggled(bool checked) +{ + ui->headset_properties->setVisible(server_interface->isHeadsetConnected() and checked); +} + +void main_window::on_recommended_eye_size_changed(QSize size) +{ + ui->label_eye_size->setText(tr("%1 \u2a2f %2").arg(size.width()).arg(size.height())); +} + +void main_window::on_available_refresh_rates_changed(const std::vector & rates) +{ + QStringList rates_str; + for (float size: rates) + rates_str.push_back(tr("%1 Hz").arg(size)); + + ui->label_refresh_rates->setText(rates_str.join(", ")); +} + +void main_window::on_preferred_refresh_rate_changed(float rate) +{ + ui->label_prefered_refresh_rate->setText(tr("%1 Hz").arg(std::round(rate))); +} + +void main_window::on_eye_gaze_changed(bool supported) +{ + ui->label_eye_gaze_tracking->setText(supported ? tr("Supported") : tr("Not supported")); +} + +void main_window::on_face_tracking_changed(bool supported) +{ + ui->label_face_tracking->setText(supported ? tr("Supported") : tr("Not supported")); +} + +void main_window::on_field_of_view_changed(const std::vector & fovs) +{ + if (fovs.size() >= 2) + { + ui->label_field_of_view->setText(tr("Left eye: %1° \u2a2f %2°, right eye: %3° \u2a2f %4°") + .arg((fovs[0].angleRight - fovs[0].angleLeft) * 180 / M_PI, 0, 'f', 1) + .arg((fovs[0].angleUp - fovs[0].angleDown) * 180 / M_PI, 0, 'f', 1) + .arg((fovs[1].angleRight - fovs[1].angleLeft) * 180 / M_PI, 0, 'f', 1) + .arg((fovs[1].angleUp - fovs[1].angleDown) * 180 / M_PI, 0, 'f', 1)); + } +} + +void main_window::on_hand_tracking_changed(bool supported) +{ + ui->label_hand_tracking->setText(supported ? tr("Supported") : tr("Not supported")); +} + +void main_window::on_mic_changed() +{ + auto channels = server_interface->micChannels(); + auto sample_rate = server_interface->micSampleRate(); + + if (channels and sample_rate) + ui->label_mic->setText(tr("%n channel(s), %1 Hz", nullptr, channels).arg(sample_rate)); + else + ui->label_mic->setText(tr("N/A")); +} + +void main_window::on_speaker_changed() +{ + auto channels = server_interface->speakerChannels(); + auto sample_rate = server_interface->speakerSampleRate(); + + if (channels and sample_rate) + ui->label_speaker->setText(tr("%n channel(s), %1 Hz", nullptr, channels).arg(sample_rate)); + else + ui->label_speaker->setText(tr("N/A")); +} + +void main_window::on_supported_codecs_changed(QStringList value) +{ + ui->label_codecs->setText(value.join(", ")); +} + +void main_window::on_steam_command_changed(QString value) +{ + ui->label_steam_command->setText(value); +} + +void main_window::on_server_dbus_registered() +{ + server_process_timeout->stop(); +} + +void main_window::on_server_finished(int exit_code, QProcess::ExitStatus status) +{ + disconnect(server_process, &QProcess::finished, this, &main_window::on_server_finished); + disconnect(server_process, &QProcess::errorOccurred, this, &main_window::on_server_error_occurred); + server_process->deleteLater(); + server_process = nullptr; + + if (exit_code != 0) + { + QString error_message = tr("Unknown error (%1), check logs").arg(exit_code); + switch (exit_code) + { + case wivrn_exit_code::cannot_connect_to_avahi: + error_message = tr("Cannot connect to avahi, make sure avahi-daemon service is started"); + break; + case wivrn_exit_code::cannot_create_pipe: + case wivrn_exit_code::cannot_create_socketpair: + error_message = tr("Insufficient system resources"); + break; + case wivrn_exit_code::success: + case wivrn_exit_code::unknown_error: + break; + } + + QMessageBox msgbox /*(this)*/; + msgbox.setIcon(QMessageBox::Critical); + msgbox.setText(tr("Server crashed:\n%1").arg(error_message)); + msgbox.setStandardButtons(QMessageBox::Close); + +#ifdef WORKAROUND_QTBUG_90005 + setEnabled(false); +#endif + msgbox.exec(); + +#ifdef WORKAROUND_QTBUG_90005 + setEnabled(true); +#endif + } +} + +void main_window::on_server_error_occurred(QProcess::ProcessError error) +{ + qDebug() << "on_server_error_occurred" << error; + + QString error_message; + switch (error) + { + case QProcess::ProcessError::FailedToStart: + error_message = tr("Failed to start"); + break; + case QProcess::ProcessError::Crashed: + error_message = tr("Crashed"); + break; + case QProcess::ProcessError::Timedout: + error_message = tr("Time out"); + break; + case QProcess::ProcessError::ReadError: + error_message = tr("Read error"); + break; + case QProcess::ProcessError::WriteError: + error_message = tr("Write error"); + break; + case QProcess::ProcessError::UnknownError: + error_message = tr("Unknown error"); + break; + } + + QMessageBox msgbox /*(this)*/; + msgbox.setIcon(QMessageBox::Critical); + msgbox.setText(tr("Failed to start server:\n%1").arg(error_message)); + msgbox.setStandardButtons(QMessageBox::Close); + +#ifdef WORKAROUND_QTBUG_90005 + setEnabled(false); +#endif + msgbox.exec(); + +#ifdef WORKAROUND_QTBUG_90005 + setEnabled(true); +#endif +} + +void main_window::on_server_start_timeout() +{ + qDebug() << "on_server_start_timeout"; + + if (server_process) + { + // Disconnect signals to avoid receiving signals about the server crashing + disconnect(server_process, &QProcess::finished, this, &main_window::on_server_finished); + disconnect(server_process, &QProcess::errorOccurred, this, &main_window::on_server_error_occurred); + server_process->terminate(); + server_process->deleteLater(); + server_process = nullptr; + } + + QMessageBox msgbox /*(this)*/; + msgbox.setIcon(QMessageBox::Critical); + msgbox.setText(tr("Timeout starting server")); + msgbox.setStandardButtons(QMessageBox::Close); + +#ifdef WORKAROUND_QTBUG_90005 + setEnabled(false); +#endif + msgbox.exec(); + +#ifdef WORKAROUND_QTBUG_90005 + setEnabled(true); +#endif +} + +void main_window::on_action_settings() +{ + assert(not settings_window); + + settings_window = new settings(server_interface); + +#ifdef WORKAROUND_QTBUG_90005 + setEnabled(false); + connect(settings_window, &QDialog::finished, this, [&](int r) { + setEnabled(true); + settings_window->deleteLater(); + settings_window = nullptr; + }); +#endif + + settings_window->exec(); +} + +void main_window::on_action_wizard() +{ + assert(not wizard_window); + + wizard_window = new wizard; + +#ifdef WORKAROUND_QTBUG_90005 + setDisabled(true); + connect(wizard_window, &QWizard::finished, this, [&]() { + setEnabled(true); + wizard_window->deleteLater(); + wizard_window = nullptr; + }); +#endif + + wizard_window->exec(); +} + +void main_window::start_server() +{ + // TODO activate by dbus? + server_process = new QProcess; + connect(server_process, &QProcess::finished, this, &main_window::on_server_finished); + connect(server_process, &QProcess::errorOccurred, this, &main_window::on_server_error_occurred); + + server_process->setProcessChannelMode(QProcess::ForwardedChannels); + + server_process->start(QCoreApplication::applicationDirPath() + "/wivrn-server"); + server_process_timeout->start(); + + ui->button_start->setEnabled(false); +} + +void main_window::stop_server() +{ + if (server_interface) + server_interface->quit() /*.waitForFinished()*/; + // server_process.terminate(); // TODO timer and kill + ui->button_stop->setEnabled(false); +} + +void main_window::disconnect_client() +{ + if (server_interface) + server_interface->disconnect_headset(); +} + +#include "moc_main_window.cpp" diff --git a/dashboard/main_window.h b/dashboard/main_window.h new file mode 100644 index 00000000..56923085 --- /dev/null +++ b/dashboard/main_window.h @@ -0,0 +1,103 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "wivrn_qdbus_types.h" + +Q_DECLARE_LOGGING_CATEGORY(wivrn_log_category) + +namespace Ui +{ +class MainWindow; +} +class IoGithubWivrnServerInterface; +class OrgFreedesktopDBusPropertiesInterface; + +class settings; +class wivrn_server; +class wizard; + +class main_window : public QMainWindow +{ + Q_OBJECT + + Ui::MainWindow * ui = nullptr; + wivrn_server * server_interface = nullptr; + + settings * settings_window = nullptr; + wizard * wizard_window = nullptr; + + QIcon icon{":/assets/wivrn.png"}; + QSystemTrayIcon systray{icon}; + + QMenu systray_menu; + QAction action_show; + QAction action_hide; + QAction action_exit; + + QProcess * server_process = nullptr; + QTimer * server_process_timeout = nullptr; + +public: + main_window(); + ~main_window(); + + void changeEvent(QEvent * e) override; + bool event(QEvent * e) override; + void closeEvent(QCloseEvent * event) override; + void setVisible(bool visible) override; + +private: + void on_server_dbus_registered(); + void on_server_finished(int exit_code, QProcess::ExitStatus status); + void on_server_error_occurred(QProcess::ProcessError error); + void on_server_start_timeout(); + + void on_button_details_toggled(bool); + + void on_server_running_changed(bool running); + void on_headset_connected_changed(bool connected); + void on_recommended_eye_size_changed(QSize size); + void on_available_refresh_rates_changed(const std::vector & rates); + void on_preferred_refresh_rate_changed(float rate); + void on_eye_gaze_changed(bool supported); + void on_face_tracking_changed(bool supported); + void on_field_of_view_changed(const std::vector & fov); + void on_hand_tracking_changed(bool supported); + void on_mic_changed(); + void on_speaker_changed(); + void on_supported_codecs_changed(QStringList value); + void on_steam_command_changed(QString value); + + void on_action_settings(); + void on_action_wizard(); + void start_server(); + void stop_server(); + void disconnect_client(); + + void retranslate(); +}; diff --git a/dashboard/main_window.ui b/dashboard/main_window.ui new file mode 100644 index 00000000..e98f7742 --- /dev/null +++ b/dashboard/main_window.ui @@ -0,0 +1,513 @@ + + + MainWindow + + + + 0 + 0 + 898 + 701 + + + + WiVRn dashboard + + + + :/images/wivrn.svg:/images/wivrn.svg + + + + + + + Server status + + + false + + + + + + 1 + + + + + + + + + + :/images/wivrn.svg + + + + + + + + + + + + 18 + + + + Stopped + + + + + + + Start + + + + + + + + + + + + Qt::Orientation::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + + + :/images/wivrn.svg + + + + + + + + + + + + 18 + + + + Running + + + + + + + Settings + + + + + + + + + + Stop + + + + + + + + + + + + Qt::Orientation::Vertical + + + + 20 + 40 + + + + + + + + For Steam games, set the command to: + + + Qt::TextFormat::PlainText + + + true + + + Qt::TextInteractionFlag::NoTextInteraction + + + + + + + + + Copy to clipboard + + + + + + + + + + + + + IBeamCursor + + + PRESSURE_VESSEL_FILESYSTEMS_RW=$XDG_RUNTIME_DIR/wivrn/comp_ipc %command% + + + true + + + Qt::TextInteractionFlag::NoTextInteraction + + + + + + + + + + + + + + + + + + Headset status + + + + + + + + + 18 + + + + client_status + + + + + + + Wizard + + + + + + + Disconnect + + + + + + + + + + Details + + + true + + + false + + + + + + + + + connect_to_this_server + + + true + + + + + + + + 0 + + + 0 + + + + + Eye gaze tracking + + + + + + + Eye resolution + + + + + + + Speaker + + + + + + + Field of view + + + + + + + refresh_rates + + + + + + + eye_size + + + + + + + Microphone + + + + + + + Available refresh rates + + + + + + + Supported codecs + + + + + + + Hand tracking + + + + + + + Preferred refresh rate + + + + + + + Face tracking + + + + + + + preferrred_refresh_rate + + + + + + + speaker + + + + + + + mic + + + + + + + field_of_view + + + + + + + hand_tracking + + + + + + + eye_gaze_tracking + + + + + + + face_tracking + + + + + + + codecs + + + + + + + + + + + + + Qt::Orientation::Vertical + + + + 20 + 104 + + + + + + + + + + Qt::Orientation::Horizontal + + + + 20 + 40 + + + + + + + + About + + + + + + + + + + Exit + + + + + + + + + + + + + + + + &Show + + + + + + + + &Hide + + + + + + + + &Exit + + + + + + + + + diff --git a/dashboard/rectangle_partitionner.cpp b/dashboard/rectangle_partitionner.cpp new file mode 100644 index 00000000..81b3b843 --- /dev/null +++ b/dashboard/rectangle_partitionner.cpp @@ -0,0 +1,825 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "rectangle_partitionner.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace +{ +const double split_edge_threshold = 0.05; +const double move_edge_threshold = 0.02; +const double magnetism_threshold = 0.05; +const int num_subdiv = 20; +const double epsilon = 1.0 / (2 * num_subdiv); + +enum class side +{ + top, + bottom, + left, + right +}; + +struct edge +{ + side edge_side; + int rectangle_index; + + bool operator==(const edge & other) const noexcept + { + return edge_side == other.edge_side and rectangle_index == other.rectangle_index; + } + + double position = 0; + double min = std::numeric_limits::max(); + double max = std::numeric_limits::lowest(); +}; +} // namespace + +struct rectangle_partitionner_private +{ + std::vector selection; + std::vector hovered; + + double min_drag_position; + double max_drag_position; + + QLine split_line; + + enum class mouse_event_type + { + move, + press, + release + }; +}; + +namespace +{ +int hovered_rectangle(QPointF position, std::vector rectangles) +{ + int n = 0; + for (const QRectF & i: rectangles) + { + if (i.contains(position)) + return n; + n++; + } + + return -1; +} + +Qt::CursorShape get_cursor_shape(QPointF position, std::vector rectangles) +{ + for (QRectF & i: rectangles) + { + if (i.contains(position)) + { + QPointF rel_pos = position - i.topLeft(); + double dx = std::min(rel_pos.x(), i.width() - rel_pos.x()); + double dy = std::min(rel_pos.y(), i.height() - rel_pos.y()); + + if (dx < move_edge_threshold and position.x() >= epsilon and position.x() <= 1 - epsilon) + return Qt::SizeHorCursor; + else if (dy < move_edge_threshold and position.y() >= epsilon and position.y() <= 1 - epsilon) + return Qt::SizeVerCursor; + else if (dx < split_edge_threshold and position.y() >= epsilon and position.y() <= 1 - epsilon) + return Qt::SplitVCursor; + else if (dy < split_edge_threshold and position.x() >= epsilon and position.x() <= 1 - epsilon) + return Qt::SplitHCursor; + else + return Qt::ArrowCursor; + + break; + } + } + + return Qt::ArrowCursor; +} + +std::vector horizontal_edges(std::vector rectangles) +{ + std::vector edges; + + for (int i = 0, n = rectangles.size(); i < n; i++) + { + if (rectangles[i].top() > epsilon) + { + edges.emplace_back(side::top, i, rectangles[i].top(), rectangles[i].left(), rectangles[i].right()); + } + + if (rectangles[i].bottom() < 1 - epsilon) + { + edges.emplace_back(side::bottom, i, rectangles[i].bottom(), rectangles[i].left(), rectangles[i].right()); + } + } + + return edges; +} + +std::vector vertical_edges(std::vector rectangles) +{ + std::vector edges; + + for (int i = 0, n = rectangles.size(); i < n; i++) + { + if (rectangles[i].left() > epsilon) + { + edges.emplace_back(side::left, i, rectangles[i].left(), rectangles[i].top(), rectangles[i].bottom()); + } + + if (rectangles[i].right() < 1 - epsilon) + { + edges.emplace_back(side::right, i, rectangles[i].right(), rectangles[i].top(), rectangles[i].bottom()); + } + } + + return edges; +} + +std::vector> partition_edges(std::vector edges) +{ + auto comp = [](const edge & a, const edge & b) { + if (a.position < b.position) + return true; + if (a.position > b.position) + return false; + + if (a.min < b.min) + return true; + if (a.min > b.min) + return false; + + if (a.max < b.max) + return true; + return false; + }; + + std::ranges::sort(edges, comp); + + std::vector> partitionned; + + double current_position = std::numeric_limits::lowest(); + double current_max = 0; + + for (auto & e: edges) + { + if (e.position != current_position) + { + current_position = e.position; + current_max = e.max; + partitionned.push_back({e}); + } + else + { + if (e.min >= current_max) + { + // All the following edges will be after the last partition + current_max = e.max; + partitionned.push_back({e}); + } + else + { + // Add the edge to the current partition + current_max = std::max(current_max, e.max); + partitionned.back().push_back(e); + } + } + } + + return partitionned; +} + +std::vector hovered_edges(QPointF position, const std::vector> & partitionned_edges, bool horizontal) +{ + if (horizontal) + position = position.transposed(); + + for (const auto & edge_list: partitionned_edges) + { + for (const auto & edge: edge_list) + { + if (std::abs(position.x() - edge.position) < move_edge_threshold and position.y() >= edge.min and position.y() <= edge.max) + { + return edge_list; + } + } + } + + return {}; +} + +bool assert_rectangle_list_is_partition(const std::vector & rectangles) +{ + return true; + + bool ok = true; + + QRectF bounding_box{0, 0, 1, 1}; + + for (const auto & i: rectangles) + { + if (i.width() < 0 or i.height() < 0) + { + qDebug() << "Invalid rectangle" << i; + ok = false; + } + } + + std::vector rectangle_y_boundaries; + for (auto & i: rectangles) + { + rectangle_y_boundaries.push_back(i.top()); + rectangle_y_boundaries.push_back(i.bottom()); + } + + // for (int y = bounding_box.top(); y < bounding_box.bottom(); ++y) + for (double y: rectangle_y_boundaries) + { + if (y < bounding_box.top()) + continue; + if (y >= bounding_box.bottom()) + continue; + + qDebug() << "Checking line" << y; + std::vector> horizontal_segments; + for (const auto & i: rectangles) + { + if (y >= i.top() and y < i.bottom()) + { + horizontal_segments.emplace_back(i.left(), i.right()); + qDebug() << " Adding segment" << i.left() << "-" << i.right(); + } + } + + std::ranges::sort(horizontal_segments); + + if (horizontal_segments.empty()) + { + qDebug() << "Line" << y << "empty"; + ok = false; + } + + if (horizontal_segments.front().first != bounding_box.left()) + { + qDebug() << "Line" << y << "does not start at the left of the bounding box" << (horizontal_segments.front().first - bounding_box.left()); + ok = false; + } + + if (horizontal_segments.back().second != bounding_box.right()) + { + qDebug() << "Last rectangle of line" << y << "does not end at the right of the bounding box" << (horizontal_segments.back().second - bounding_box.right()); + ok = false; + } + + for (int i = 1; i < horizontal_segments.size(); ++i) + { + if (horizontal_segments[i - 1].second < horizontal_segments[i].first) + { + qDebug() << "Overlap in line" << y << (horizontal_segments[i - 1].second - horizontal_segments[i].first); + ok = false; + } + else if (horizontal_segments[i - 1].second > horizontal_segments[i].first) + { + qDebug() << "Gap in line" << y << (horizontal_segments[i - 1].second - horizontal_segments[i].first); + ok = false; + } + } + } + + if (!ok) + { + qDebug() << "Bounding box:" << bounding_box; + int n = 1; + for (auto & i: rectangles) + { + qDebug() << "Rectangle" << (n++) << ":" << i.topLeft() << "-" << i.bottomRight(); + } + } + + return ok; +} + +} // namespace + +rectangle_partitionner::rectangle_partitionner(QWidget * parent) : + QFrame(parent) +{ + p = new rectangle_partitionner_private; + + setMouseTracking(true); + + std::vector encoders; + + encoders.push_back(QRectF{0, 0, 1, 1}); + set_rectangles(encoders); + + m_paint = [](QPainter & painter, QRect rect, const QVariant & data, int index, bool selected) { + if (selected) + { + painter.fillRect(rect.adjusted(1, 1, 0, 0), QColorConstants::Cyan); + } + + QString text = QString("%1").arg(index + 1); + painter.drawText(rect, Qt::AlignCenter, text); + }; +} + +rectangle_partitionner::~rectangle_partitionner() +{ + delete p; +} + +void rectangle_partitionner::paintEvent(QPaintEvent * event) +{ + QFrame::paintEvent(event); + + QPainter painter(this); + + auto positions = rectangles_position(); + + { + QList lines; + for (int i = 1; i < num_subdiv; i++) + { + QPoint p1 = to_position({0, double(i) / num_subdiv}); + QPoint p2 = to_position({1, double(i) / num_subdiv}); + lines.emplace_back(p1, p2); + + QPoint p3 = to_position({double(i) / num_subdiv, 0}); + QPoint p4 = to_position({double(i) / num_subdiv, 1}); + lines.emplace_back(p3, p4); + } + + QPen pen = painter.pen(); + painter.setPen(QPen(Qt::lightGray, 1, Qt::SolidLine)); + painter.drawLines(lines); + painter.setPen(pen); + } + + if (m_paint) + { + int n = 0; + for (QRect & i: positions) + { + painter.drawRect(i); + bool is_selected = n == m_selected_index and isEnabled(); + m_paint(painter, i, m_rectangles_data[n], n, is_selected); + + n++; + } + } + + if (not p->hovered.empty() and p->selection.empty()) + { + painter.setPen(QPen(Qt::blue, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + + auto r = frameRect(); + r.adjust(frameWidth(), frameWidth(), -2 * frameWidth(), -2 * frameWidth()); + + QList lines; + lines.reserve(p->hovered.size()); + for (const edge & i: p->hovered) + { + QLineF line; + switch (i.edge_side) + { + case side::top: + case side::bottom: + line = QLineF(i.min, i.position, i.max, i.position); + break; + + case side::left: + case side::right: + line = QLineF(i.position, i.min, i.position, i.max); + break; + } + + int x1 = std::round(r.x() + line.x1() * (r.width() - 1)); + int x2 = std::round(r.x() + line.x2() * (r.width() - 1)); + + int y1 = std::round(r.y() + line.y1() * (r.height() - 1)); + int y2 = std::round(r.y() + line.y2() * (r.height() - 1)); + + lines.emplace_back(x1, y1, x2, y2); + } + + painter.drawLines(lines); + + auto horz_partitionned = partition_edges(horizontal_edges(m_rectangles)); + auto vert_partitionned = partition_edges(vertical_edges(m_rectangles)); + } + else if ((cursor() == Qt::SplitHCursor or cursor() == Qt::SplitVCursor) and not p->split_line.isNull()) + { + auto now = std::chrono::duration_cast>(std::chrono::steady_clock::now().time_since_epoch()).count(); + + QPen pen(Qt::black, 2, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin); + pen.setDashPattern({5, 5}); + pen.setDashOffset(-now * 15); + painter.setPen(pen); + + painter.drawLine(p->split_line); + update(); + } +} + +void rectangle_partitionner::mouseMoveEvent(QMouseEvent * event) +{ + assert(m_rectangles.size() == m_rectangles_data.size()); + + auto r = frameRect(); + r.adjust(frameWidth(), frameWidth(), -2 * frameWidth(), -2 * frameWidth()); + + if (not p->selection.empty()) + { + double position; + + if (p->selection.front().edge_side == side::top or p->selection.front().edge_side == side::bottom) + position = from_position(event->pos()).y(); + else + position = from_position(event->pos()).x(); + + position = std::clamp(position, p->min_drag_position, p->max_drag_position); + position = std::round(position * num_subdiv) / num_subdiv; // magnetism + + for (edge & e: p->selection) + { + switch (e.edge_side) + { + case side::top: + m_rectangles[e.rectangle_index].setTop(position); + break; + + case side::bottom: + m_rectangles[e.rectangle_index].setBottom(position); + break; + + case side::left: + m_rectangles[e.rectangle_index].setLeft(position); + break; + + case side::right: + m_rectangles[e.rectangle_index].setRight(position); + break; + } + } + + // if (not assert_rectangle_list_is_partition(m_rectangles)) + // { + // abort(); + // } + + update(); + rectangles_change(m_rectangles); + } + else + { + p->hovered.clear(); + + if (auto horz_edges = hovered_edges(from_position(event->pos()), partition_edges(horizontal_edges(m_rectangles)), true); not horz_edges.empty()) + { + p->hovered = std::move(horz_edges); + update(); + } + else if (auto vert_edges = hovered_edges(from_position(event->pos()), partition_edges(vertical_edges(m_rectangles)), false); not vert_edges.empty()) + { + p->hovered = std::move(vert_edges); + update(); + } + else + { + int n = hovered_rectangle(from_position(event->pos()), m_rectangles); + } + + auto new_cursor = get_cursor_shape(from_position(event->pos()), m_rectangles); + if (new_cursor != cursor()) + { + update(); + setCursor(new_cursor); + } + } + + if (cursor() == Qt::SplitHCursor) + { + int n = hovered_rectangle(from_position(event->pos()), m_rectangles); + + double x = std::round(from_position(event->pos()).x() * num_subdiv) / num_subdiv; // magnetism + int px = to_position({x, 0}).x(); + + p->split_line = {px, rectangles_position()[n].top(), px, rectangles_position()[n].bottom()}; + update(); + } + else if (cursor() == Qt::SplitVCursor) + { + int n = hovered_rectangle(from_position(event->pos()), m_rectangles); + + double y = std::round(from_position(event->pos()).y() * num_subdiv) / num_subdiv; // magnetism + int py = to_position({0, y}).y(); + + p->split_line = {rectangles_position()[n].left(), py, rectangles_position()[n].right(), py}; + update(); + } + else + { + p->split_line = {0, 0, 0, 0}; + } +} + +void rectangle_partitionner::mousePressEvent(QMouseEvent * event) +{ + assert(m_rectangles.size() == m_rectangles_data.size()); + + auto r = frameRect(); + r.adjust(frameWidth(), frameWidth(), -2 * frameWidth(), -2 * frameWidth()); + + p->selection.clear(); + p->split_line = {0, 0, 0, 0}; + + if (auto horz_edges = hovered_edges(from_position(event->pos()), partition_edges(horizontal_edges(m_rectangles)), true); not horz_edges.empty()) + { + p->selection = std::move(horz_edges); + } + else if (auto vert_edges = hovered_edges(from_position(event->pos()), partition_edges(vertical_edges(m_rectangles)), false); not vert_edges.empty()) + { + p->selection = std::move(vert_edges); + } + else if (int n = hovered_rectangle(from_position(event->pos()), m_rectangles); n >= 0) + { + QRectF & hovered = m_rectangles[n]; + + // Compute distance to edges + auto pos = from_position(event->pos()); + + double dx = std::min(pos.x() - hovered.left(), hovered.right() - pos.x()); + double dy = std::min(pos.y() - hovered.top(), hovered.bottom() - pos.y()); + + if (dx < split_edge_threshold) + { + double y = std::round(pos.y() * num_subdiv) / num_subdiv; // magnetism + + // Split vertically + QRectF new_rectangle = hovered; + + hovered.setBottom(y); + new_rectangle.setTop(hovered.bottom()); + + m_rectangles.push_back(new_rectangle); + m_rectangles_data.push_back(m_rectangles_data[n]); + update(); + rectangles_change(m_rectangles); + + if (not assert_rectangle_list_is_partition(m_rectangles)) + abort(); + } + else if (dy < split_edge_threshold) + { + double x = std::round(pos.x() * num_subdiv) / num_subdiv; // magnetism + + // Split horizontally + QRectF new_rectangle = hovered; + + hovered.setRight(x); + new_rectangle.setLeft(hovered.right()); + + m_rectangles.push_back(new_rectangle); + m_rectangles_data.push_back(m_rectangles_data[n]); + update(); + rectangles_change(m_rectangles); + + if (not assert_rectangle_list_is_partition(m_rectangles)) + abort(); + } + else + { + set_selected_index(n); + } + } + + if (not p->selection.empty()) + { + p->hovered.clear(); + + p->min_drag_position = std::numeric_limits::lowest(); + p->max_drag_position = std::numeric_limits::max(); + + for (auto & e: p->selection) + { + switch (e.edge_side) + { + case side::top: + p->max_drag_position = std::min(p->max_drag_position, m_rectangles[e.rectangle_index].bottom()); + break; + case side::bottom: + p->min_drag_position = std::max(p->min_drag_position, m_rectangles[e.rectangle_index].top()); + break; + case side::left: + p->max_drag_position = std::min(p->max_drag_position, m_rectangles[e.rectangle_index].right()); + break; + case side::right: + p->min_drag_position = std::max(p->min_drag_position, m_rectangles[e.rectangle_index].left()); + break; + } + } + } + assert(m_rectangles.size() == m_rectangles_data.size()); +} + +void rectangle_partitionner::mouseReleaseEvent(QMouseEvent * event) +{ + assert(m_rectangles.size() == m_rectangles_data.size()); + + p->selection.clear(); + + // Delete empty rectangles + auto i1 = m_rectangles.begin(); + auto i3 = m_rectangles_data.begin(); + + assert(m_rectangles.size() == m_rectangles_data.size()); + + bool changed = false; + for (; i1 != m_rectangles.end();) + { + // if (i2->width() <= 1 or i2->height() <= 1) + if (i1->width() <= 0.0001 or i1->height() <= 0.0001) // TODO configurable thresholds + { + i1 = m_rectangles.erase(i1); + i3 = m_rectangles_data.erase(i3); + changed = true; + } + else + { + ++i1; + ++i3; + } + } + assert(m_rectangles.size() == m_rectangles_data.size()); + + if (changed) + { + if (not assert_rectangle_list_is_partition(m_rectangles)) + abort(); + + rectangles_change(m_rectangles); + update(); + } +} + +void rectangle_partitionner::leaveEvent(QEvent * event) +{ + p->split_line = {0, 0, 0, 0}; +} + +void rectangle_partitionner::keyPressEvent(QKeyEvent * event) +{ + auto r = frameRect(); + r.adjust(frameWidth(), frameWidth(), -2 * frameWidth(), -2 * frameWidth()); + qDebug() << "Bounding box:" << r; + int n = 1; + for (auto & i: m_rectangles) + { + qDebug() << "Rectangle" << (n++) << ":" << i.topLeft() << "-" << i.bottomRight(); + } +} + +void rectangle_partitionner::set_rectangles(rectangle_list value) +{ + assert(m_rectangles.size() == m_rectangles_data.size()); + auto old_value = std::move(m_rectangles); + + m_rectangles = std::move(value); + + for (auto & i: m_rectangles) + { + i.setBottom(std::round(i.bottom() * num_subdiv) / num_subdiv); + i.setTop(std::round(i.top() * num_subdiv) / num_subdiv); + i.setLeft(std::round(i.left() * num_subdiv) / num_subdiv); + i.setRight(std::round(i.right() * num_subdiv) / num_subdiv); + } + + if (not assert_rectangle_list_is_partition(m_rectangles)) + { + m_rectangles = std::move(old_value); + + throw std::runtime_error("Invalid partitionning"); + } + + m_rectangles_data.resize(m_rectangles.size()); + + if (m_selected_index >= m_rectangles.size()) + set_selected_index(m_rectangles.size() - 1); + + update(); + rectangles_change(m_rectangles); + assert(m_rectangles.size() == m_rectangles_data.size()); +} + +void rectangle_partitionner::set_selected_index(int new_index) +{ + new_index = std::clamp(new_index, 0, m_rectangles.size()); + + if (new_index != m_selected_index) + { + m_selected_index = new_index; + update(); + + selected_index_change(new_index); + } +} + +void rectangle_partitionner::set_rectangles_data(const data_list & value) +{ + assert(m_rectangles.size() == m_rectangles_data.size()); + m_rectangles_data = value; + m_rectangles_data.resize(m_rectangles.size()); + assert(m_rectangles.size() == m_rectangles_data.size()); + + update(); +} + +void rectangle_partitionner::set_rectangles_data(int index, QVariant value) +{ + assert(m_rectangles.size() == m_rectangles_data.size()); + assert(index < m_rectangles_data.size()); + m_rectangles_data[index] = value; + assert(m_rectangles.size() == m_rectangles_data.size()); + + update(); +} + +void rectangle_partitionner::set_paint(paint_function paint) +{ + m_paint = paint; + update(); +} + +std::vector rectangle_partitionner::rectangles_position() +{ + std::vector positions; + positions.reserve(m_rectangles.size()); + + auto r = frameRect(); + r.adjust(frameWidth(), frameWidth(), -2 * frameWidth(), -2 * frameWidth()); + + for (QRectF & i: m_rectangles) + { + int x1 = std::round(r.x() + i.x() * (r.width() - 1)); + int x2 = std::round(r.x() + (i.x() + i.width()) * (r.width() - 1)); + + int y1 = std::round(r.y() + i.y() * (r.height() - 1)); + int y2 = std::round(r.y() + (i.y() + i.height()) * (r.height() - 1)); + positions.emplace_back(x1, y1, x2 - x1 + 1, y2 - y1 + 1); + } + assert(m_rectangles.size() == positions.size()); + + return positions; +} + +QPointF rectangle_partitionner::from_position(QPoint position) +{ + auto r = frameRect(); + r.adjust(frameWidth(), frameWidth(), -2 * frameWidth(), -2 * frameWidth()); + + return QPointF{ + std::clamp(double(position.x() - r.x()) / (r.width() - 1), 0., 1.), + std::clamp(double(position.y() - r.y()) / (r.height() - 1), 0., 1.), + }; +} + +QPoint rectangle_partitionner::to_position(QPointF position) +{ + auto r = frameRect(); + r.adjust(frameWidth(), frameWidth(), -2 * frameWidth(), -2 * frameWidth()); + + return QPoint( + std::round(r.x() + position.x() * (r.width() - 1)), + std::round(r.y() + position.y() * (r.height() - 1))); +} + +#include "moc_rectangle_partitionner.cpp" diff --git a/dashboard/rectangle_partitionner.h b/dashboard/rectangle_partitionner.h new file mode 100644 index 00000000..50f7a352 --- /dev/null +++ b/dashboard/rectangle_partitionner.h @@ -0,0 +1,101 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include +#include +#include + +struct rectangle_partitionner_private; + +class rectangle_partitionner : public QFrame +{ + Q_OBJECT + + rectangle_partitionner_private * p; + +public: + explicit rectangle_partitionner(QWidget * parent = nullptr); + rectangle_partitionner(const rectangle_partitionner &) = delete; + rectangle_partitionner & operator=(const rectangle_partitionner &) = delete; + ~rectangle_partitionner(); + + using rectangle_list = std::vector; + using data_list = std::vector; + using paint_function = std::function; + + Q_PROPERTY(rectangle_list rectangles READ rectangles WRITE set_rectangles NOTIFY rectangles_change) + Q_PROPERTY(data_list rectangles_data READ rectangles_data WRITE set_rectangles_data) + Q_PROPERTY(int selected_index READ selected_index WRITE set_selected_index NOTIFY selected_index_change) + Q_PROPERTY(paint_function paint READ paint WRITE set_paint) + + const rectangle_list & rectangles() const + { + return m_rectangles; + } + + int selected_index() const + { + return m_selected_index; + } + + const data_list & rectangles_data() const + { + return m_rectangles_data; + } + + const QVariant & rectangles_data(int index) const + { + return m_rectangles_data.at(index); + } + + const paint_function & paint() const + { + return m_paint; + } + + void set_rectangles(rectangle_list); + void set_rectangles_data(const data_list &); + void set_rectangles_data(int, QVariant); + void set_selected_index(int); + void set_paint(paint_function paint); + +signals: + void selected_index_change(int); + void rectangles_change(const rectangle_list &); + +protected: + rectangle_list m_rectangles; + int m_selected_index = 0; + data_list m_rectangles_data; + paint_function m_paint; + + std::vector rectangles_position(); + QPointF from_position(QPoint position); + QPoint to_position(QPointF position); + + void paintEvent(QPaintEvent * event) override; + void mouseMoveEvent(QMouseEvent * event) override; + void mousePressEvent(QMouseEvent * event) override; + void mouseReleaseEvent(QMouseEvent * event) override; + void leaveEvent(QEvent * event) override; + + void keyPressEvent(QKeyEvent * event) override; +}; diff --git a/dashboard/settings.cpp b/dashboard/settings.cpp new file mode 100644 index 00000000..c72920dd --- /dev/null +++ b/dashboard/settings.cpp @@ -0,0 +1,432 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "settings.h" + +#include "rectangle_partitionner.h" +#include "ui_settings.h" +#include "wivrn_server.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace +{ +// The index must match the order in the combo boxes +const std::vector> encoder_ids{ + {0, "auto"}, + {1, "nvenc"}, + {2, "vaapi"}, + {3, "x264"}, +}; + +const std::vector> codec_ids{ + {0, "auto"}, + {1, "h264"}, + {1, "avc"}, + {2, "h265"}, + {3, "av1"}, +}; + +const std::vector> compatible_combos{ + // Automatically chosen encoder + {0, 0}, + // nvenc + {1, 0}, + {1, 1}, + {1, 2}, + // {1, 3}, + // vaapi + {2, 0}, + {2, 1}, + {2, 2}, + {2, 3}, + // x264 + {3, 1}, +}; + +int encoder_id_from_string(std::string_view s) +{ + for (auto & [i, j]: encoder_ids) + { + if (j == s) + return i; + } + return 0; +} + +const std::string & encoder_from_id(int id) +{ + for (auto & [i, j]: encoder_ids) + { + if (i == id) + return j; + } + + static const std::string default_value = "auto"; + return default_value; +} + +int codec_id_from_string(std::string_view s) +{ + for (auto & [i, j]: codec_ids) + { + if (j == s) + return i; + } + return 0; +} + +const std::string & codec_from_id(int id) +{ + for (auto & [i, j]: codec_ids) + { + if (i == id) + return j; + } + + static const std::string default_value = "auto"; + return default_value; +} + +} // namespace + +settings::settings(wivrn_server * server_interface) : + server_interface(server_interface) +{ + ui = new Ui::Settings; + ui->setupUi(this); + + QJsonParseError error; + json_doc = QJsonDocument::fromJson(server_interface->jsonConfiguration().toUtf8(), &error); + + std::vector rectangles; + std::vector encoder_config; + + if (error.error) + { + std::cout << "Cannot read configuration: " << error.errorString().toStdString() << ", offset " << error.offset << std::endl; + } + else + { + auto encoders = json_doc.object().find("encoders"); + + if (encoders->isArray()) + { + ui->radio_auto_encoder->setChecked(false); + ui->radio_manual_encoder->setChecked(true); + } + else + { + ui->radio_auto_encoder->setChecked(true); + ui->radio_manual_encoder->setChecked(false); + + encoders = json_doc.object().find("encoders.disabled"); + } + + if (encoders->isArray()) + { + for (QJsonValue i: encoders->toArray()) + { + int encoder = encoder_id_from_string(i["encoder"].toString("auto").toLower().toStdString()); + int codec = codec_id_from_string(i["codec"].toString("auto").toLower().toStdString()); + double width = i["width"].toDouble(1); + double height = i["height"].toDouble(1); + double offset_x = i["offset_x"].toDouble(0); + double offset_y = i["offset_y"].toDouble(0); + int group = i["group"].toInt(0); // TODO: handle groups + + rectangles.push_back(QRectF(offset_x, offset_y, width, height)); + encoder_config.push_back(QVariant::fromValue(std::pair(encoder, codec))); + } + } + } + + if (rectangles.empty()) + { + rectangles.push_back(QRectF(0, 0, 1, 1)); + std::pair config{0, 0}; + encoder_config.push_back(QVariant::fromValue(config)); + } + + try + { + ui->partitionner->set_rectangles(rectangles); + } + catch (...) + { + QMessageBox msgbox{QMessageBox::Information, tr("Invalid settings"), tr("The encoder configuration is invalid, the default values will be restored."), QMessageBox::Close, this}; + msgbox.exec(); + + ui->radio_auto_encoder->setChecked(true); + ui->radio_manual_encoder->setChecked(false); + + rectangles.clear(); + encoder_config.clear(); + + rectangles.push_back(QRectF(0, 0, 1, 1)); + ui->partitionner->set_rectangles(rectangles); + + std::pair config{0, 0}; + encoder_config.push_back(QVariant::fromValue(config)); + } + + ui->partitionner->set_rectangles_data(encoder_config); + ui->partitionner->set_selected_index(0); + + if (json_doc["scale"].isDouble()) + { + ui->slider_foveation->setValue(std::round((1 - json_doc["scale"].toDouble(1)) * 100)); + ui->spin_foveation->setValue(std::round((1 - json_doc["scale"].toDouble(1)) * 100)); + ui->radio_auto_foveation->setChecked(false); + ui->radio_manual_foveation->setChecked(true); + } + else + { + ui->radio_auto_foveation->setChecked(true); + ui->radio_manual_foveation->setChecked(false); + } + ui->bitrate->setValue(json_doc["bitrate"].toDouble(50'000'000) / 1'000'000); + + selected_rectangle_changed(0); + + connect(ui->partitionner, &rectangle_partitionner::selected_index_change, this, &settings::selected_rectangle_changed); + // connect(ui->partitionner, &rectangle_partitionner::rectangles_change, this, [](){}); + + connect(ui->encoder, &QComboBox::currentIndexChanged, this, &settings::on_encoder_changed); + connect(ui->encoder, &QComboBox::currentIndexChanged, this, &settings::on_settings_changed); + connect(ui->codec, &QComboBox::currentIndexChanged, this, &settings::on_settings_changed); + connect(ui->bitrate, &QDoubleSpinBox::valueChanged, this, &settings::on_settings_changed); + connect(ui->slider_foveation, &QSlider::valueChanged, this, &settings::on_settings_changed); + connect(ui->spin_foveation, &QSpinBox::valueChanged, this, &settings::on_settings_changed); + + // connect(ui->foveation_info, &QPushButton::clicked, this, [&]() { QToolTip::showText(ui->radio_manual_foveation->pos(), ui->radio_manual_foveation->toolTip(), ui->radio_manual_foveation); }); + + connect(this, &QDialog::accepted, this, &settings::save_settings); + connect(ui->buttonBox->button(QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, this, &settings::restore_defaults); + + ui->partitionner->set_paint([&](QPainter & painter, QRect rect, const QVariant & data, int index, bool selected) { + if (selected) + { + painter.fillRect(rect.adjusted(1, 1, 0, 0), QColorConstants::Cyan); + } + + auto [encoder_id, codec_id] = data.value>(); + + QString codec = ui->codec->itemText(codec_id); + QString encoder = ui->encoder->itemText(encoder_id); + + QFont font = painter.font(); + QFont font2 = font; + + font2.setPixelSize(24); + + QString text = QString("%1\n%2").arg(encoder, codec); + + QFontMetrics metrics{font2}; + QSize size = metrics.size(0, text); + + if (double ratio = std::max((double)size.width() / rect.width(), (double)size.height() / rect.height()); ratio > 1) + { + int pixel_size = font2.pixelSize() / ratio; + if (pixel_size > 0) + font2.setPixelSize(pixel_size); + } + + painter.setFont(font2); + painter.drawText(rect, Qt::AlignCenter, text); + painter.setFont(font); + }); + + // Update the compatible codecs + on_encoder_changed(); + + // Update the status text + on_settings_changed(); + + setWindowModality(Qt::WindowModality::ApplicationModal); +} + +settings::~settings() +{ + delete ui; + ui = nullptr; +} + +void settings::on_encoder_changed() +{ + int encoder = ui->encoder->currentIndex(); + + QStandardItemModel * model = qobject_cast(ui->codec->model()); + assert(model); + + for (int i = 0, n = model->rowCount(); i < n; i++) + { + auto * item = model->item(i); + item->setFlags(item->flags() & ~Qt::ItemIsEnabled); + } + + for (auto [i, j]: compatible_combos) + { + if (encoder == i) + { + auto * item = model->item(j); + item->setFlags(item->flags() | Qt::ItemIsEnabled); + } + } +} + +void settings::on_settings_changed() +{ + QString status; + + int encoder = ui->encoder->currentIndex(); + int codec = ui->codec->currentIndex(); + + bool compatible = false; + + for (auto [i, j]: compatible_combos) + { + if (encoder == i and codec == j) + { + compatible = true; + break; + } + } + + if (!compatible) + { + // Find a compatible codec for this encoder + for (auto [i, j]: compatible_combos) + { + if (encoder == i) + { + codec = j; + ui->codec->setCurrentIndex(j); + } + } + } + + if (codec == 3 /* av1 */) + { + status += tr("Not all headsets and GPUs support AV1\n"); + } + + ui->partitionner->set_rectangles_data(ui->partitionner->selected_index(), QVariant::fromValue(std::pair(encoder, codec))); + + ui->message->setText(status); +} + +void settings::selected_rectangle_changed(int index) +{ + auto [encoder, codec] = ui->partitionner->rectangles_data(index).value>(); + + ui->encoder->setCurrentIndex(encoder); + ui->codec->setCurrentIndex(codec); +} + +void settings::restore_defaults() +{ + ui->bitrate->setValue(50); + ui->radio_auto_foveation->setChecked(true); + ui->radio_auto_encoder->setChecked(true); + + std::vector rectangles; + std::vector encoder_config; + + rectangles.push_back(QRectF(0, 0, 1, 1)); + std::pair config{0, 0}; + encoder_config.push_back(QVariant::fromValue(config)); + + ui->partitionner->set_rectangles(rectangles); + ui->partitionner->set_rectangles_data(encoder_config); + ui->partitionner->set_selected_index(0); +} + +void settings::save_settings() +{ + QJsonObject json = json_doc.object(); + + // Remove all optional keys that might not be overwritten + auto it = json.find("scale"); + if (it != json.end()) + json.erase(it); + + it = json.find("encoders.disabled"); + if (it != json.end()) + json.erase(it); + + it = json.find("encoders"); + if (it != json.end()) + json.erase(it); + + if (not ui->radio_auto_foveation->isChecked()) + json["scale"] = 1 - ui->slider_foveation->value() / 100.0; + + json["bitrate"] = ui->bitrate->value() * 1'000'000; + + QJsonArray encoders; + + const auto & rect = ui->partitionner->rectangles(); + const auto & data = ui->partitionner->rectangles_data(); + + for (int i = 0, n = rect.size(); i < n; i++) + { + QJsonObject encoder; + auto [encoder_id, codec_id] = data[i].value>(); + + if (auto value = QString::fromLatin1(encoder_from_id(encoder_id)); value != "auto") + encoder["encoder"] = value; + + if (auto value = QString::fromLatin1(codec_from_id(codec_id)); value != "auto") + encoder["codec"] = value; + + encoder["width"] = rect[i].width(); + encoder["height"] = rect[i].height(); + encoder["offset_x"] = rect[i].x(); + encoder["offset_y"] = rect[i].y(); + + // TODO encoder groups + + encoders.push_back(encoder); + } + + // If there is only one automatic encoder, don't save it' + if (encoders.size() != 1 or encoders[0].toObject().contains("codec") or encoders[0].toObject().contains("encoder")) + { + if (ui->radio_manual_encoder->isChecked()) + json["encoders"] = encoders; + else + json["encoders.disabled"] = encoders; + } + + server_interface->setJsonConfiguration(QString::fromUtf8(QJsonDocument(json).toJson())); +} + +#include "moc_settings.cpp" diff --git a/dashboard/settings.h b/dashboard/settings.h new file mode 100644 index 00000000..4f48d9d1 --- /dev/null +++ b/dashboard/settings.h @@ -0,0 +1,50 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include +#include + +namespace Ui +{ +class Settings; +} +class wivrn_server; + +class settings : public QDialog +{ + Q_OBJECT + + Ui::Settings * ui; + wivrn_server * server_interface; + + QJsonDocument json_doc; + + void selected_rectangle_changed(int); + +public: + settings(wivrn_server * server_interface = nullptr); + ~settings(); + + void on_settings_changed(); + void on_encoder_changed(); + void save_settings(); + void restore_defaults(); +}; diff --git a/dashboard/settings.ui b/dashboard/settings.ui new file mode 100644 index 00000000..104490cc --- /dev/null +++ b/dashboard/settings.ui @@ -0,0 +1,786 @@ + + + Settings + + + + 0 + 0 + 1018 + 805 + + + + Settings + + + + 0 + + + 0 + + + + + + + Foveation strength: + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignTrailing|Qt::AlignmentFlag::AlignVCenter + + + + + + + Bitrate: + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignTrailing|Qt::AlignmentFlag::AlignVCenter + + + bitrate + + + + + + + + + Weaker + + + + + + + Qt::Orientation::Horizontal + + + + 40 + 20 + + + + + + + + Stronger + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignTrailing|Qt::AlignmentFlag::AlignVCenter + + + + + + + + + + + Mbit/s + + + 0 + + + 1.000000000000000 + + + 200.000000000000000 + + + 100.000000000000000 + + + + + + + Qt::Orientation::Horizontal + + + + 40 + 20 + + + + + + + + + + You can use several encoders in order to split the workload between your CPU and your GPU and reduce the latency. + + + + + + + + + false + + + + 0 + 0 + + + + false + + + QFrame::Shape::Panel + + + QFrame::Shadow::Sunken + + + 1 + + + 0 + + + + + + + + + false + + + + 100 + 0 + + + + Encoder + + + encoder + + + + + + + false + + + + 100 + 0 + + + + + Auto + + + + + nvenc (NVIDIA GPUs) + + + + + vaapi (AMD and Intel GPUs) + + + + + x264 (software encoding) + + + + + + + + false + + + + 100 + 0 + + + + + Auto + + + + + H.264 + + + + + H.265 + + + + + AV1 + + + + + + + + false + + + + 0 + 0 + + + + + 220 + 0 + + + + + 220 + 16777215 + + + + Qt::AlignmentFlag::AlignLeading|Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop + + + true + + + + + + + false + + + + 100 + 0 + + + + Codec + + + codec + + + + + + + + + + + Encoder configuration: + + + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignTrailing|Qt::AlignmentFlag::AlignVCenter + + + + + + + Qt::Orientation::Horizontal + + + + + + + Qt::Orientation::Horizontal + + + + 40 + 20 + + + + + + + + false + + + false + + + % + + + 80 + + + 20 + + + + + + + Qt::Orientation::Horizontal + + + + + + + Qt::Orientation::Horizontal + + + + 40 + 20 + + + + + + + + false + + + + 0 + 0 + + + + 0 + + + 80 + + + 20 + + + Qt::Orientation::Horizontal + + + QSlider::TickPosition::TicksBelow + + + + + + + Automatic + + + true + + + group_encoder + + + + + + + A stronger foveation makes the image sharper in the center than in the periphery and makes the decoding faster. This is better for fast paced games. + +A weaker foveation gives a uniform sharpness in the whole image. + +The recommended values are between 20% and 50% for headsets without eye tracking and between 50% and 70% for headsets with eye tracking. + + + true + + + + + + + Manual + + + group_encoder + + + + + + + Automatic + + + true + + + group_foveation + + + + + + + + + Qt::Orientation::Horizontal + + + + 40 + 20 + + + + + + + + + + Manual + + + group_foveation + + + + + + + Qt::Orientation::Horizontal + + + + + + + + + Qt::Orientation::Horizontal + + + QSizePolicy::Policy::Fixed + + + + 12 + 20 + + + + + + + + + 14 + + + + WiVRn settings + + + + + + + Qt::Orientation::Horizontal + + + QSizePolicy::Policy::Fixed + + + + 12 + 20 + + + + + + + + + + + + + + Qt::Orientation::Horizontal + + + QSizePolicy::Policy::Fixed + + + + 6 + 20 + + + + + + + + Qt::Orientation::Horizontal + + + QDialogButtonBox::StandardButton::Cancel|QDialogButtonBox::StandardButton::Ok|QDialogButtonBox::StandardButton::RestoreDefaults + + + + + + + Qt::Orientation::Horizontal + + + QSizePolicy::Policy::Fixed + + + + 6 + 20 + + + + + + + + + + + rectangle_partitionner + QFrame +
rectangle_partitionner.h
+ 1 +
+
+ + encoder + codec + + + + + buttonBox + accepted() + Settings + accept() + + + 260 + 778 + + + 157 + 274 + + + + + buttonBox + rejected() + Settings + reject() + + + 328 + 778 + + + 286 + 274 + + + + + slider_foveation + valueChanged(int) + spin_foveation + setValue(int) + + + 777 + 213 + + + 849 + 218 + + + + + spin_foveation + valueChanged(int) + slider_foveation + setValue(int) + + + 849 + 218 + + + 777 + 213 + + + + + radio_manual_foveation + toggled(bool) + slider_foveation + setEnabled(bool) + + + 487 + 180 + + + 777 + 213 + + + + + radio_manual_foveation + toggled(bool) + spin_foveation + setEnabled(bool) + + + 836 + 183 + + + 849 + 218 + + + + + radio_manual_encoder + toggled(bool) + partitionner + setEnabled(bool) + + + 836 + 338 + + + 388 + 508 + + + + + radio_manual_encoder + toggled(bool) + encoder + setEnabled(bool) + + + 836 + 338 + + + 834 + 378 + + + + + radio_manual_encoder + toggled(bool) + codec + setEnabled(bool) + + + 494 + 323 + + + 834 + 416 + + + + + radio_manual_encoder + toggled(bool) + encoder_label + setEnabled(bool) + + + 542 + 323 + + + 721 + 378 + + + + + radio_manual_encoder + toggled(bool) + codec_label + setEnabled(bool) + + + 560 + 322 + + + 721 + 416 + + + + + radio_manual_encoder + toggled(bool) + message + setEnabled(bool) + + + 627 + 333 + + + 675 + 465 + + + + + + + + +
diff --git a/dashboard/wivrn_qdbus_types.h b/dashboard/wivrn_qdbus_types.h new file mode 100644 index 00000000..2c406b8f --- /dev/null +++ b/dashboard/wivrn_qdbus_types.h @@ -0,0 +1,10 @@ +#pragma once + +// Same as XrFovf +struct field_of_view +{ + float angleLeft; + float angleRight; + float angleUp; + float angleDown; +}; diff --git a/dashboard/wivrn_server.cpp b/dashboard/wivrn_server.cpp new file mode 100644 index 00000000..ea070b90 --- /dev/null +++ b/dashboard/wivrn_server.cpp @@ -0,0 +1,240 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "wivrn_server.h" +#include "wivrn_server_dbus.h" + +Q_DECLARE_METATYPE(field_of_view) + +wivrn_server::wivrn_server(QObject * parent) : + QObject(parent) +{ + dbus_watcher.setConnection(QDBusConnection::sessionBus()); + dbus_watcher.addWatchedService("io.github.wivrn.Server"); + + connect(&dbus_watcher, &QDBusServiceWatcher::serviceRegistered, this, &wivrn_server::on_server_dbus_registered); + connect(&dbus_watcher, &QDBusServiceWatcher::serviceUnregistered, this, &wivrn_server::on_server_dbus_unregistered); + + const QStringList services = QDBusConnection::sessionBus().interface()->registeredServiceNames(); + if (services.contains("io.github.wivrn.Server")) + on_server_dbus_registered(); +} + +wivrn_server::~wivrn_server() +{ +} + +void wivrn_server::on_server_dbus_registered() +{ + if (server_interface) + server_interface->deleteLater(); + if (server_properties_interface) + server_properties_interface->deleteLater(); + + server_interface = new IoGithubWivrnServerInterface("io.github.wivrn.Server", "/io/github/wivrn/Server", QDBusConnection::sessionBus(), this); + server_properties_interface = new OrgFreedesktopDBusPropertiesInterface("io.github.wivrn.Server", "/io/github/wivrn/Server", QDBusConnection::sessionBus(), this); + + connect(server_properties_interface, &OrgFreedesktopDBusPropertiesInterface::PropertiesChanged, this, &wivrn_server::on_server_properties_changed); + + serverRunningChanged(m_serverRunning = true); + refresh_server_properties(); +} + +void wivrn_server::on_server_dbus_unregistered() +{ + if (server_interface) + server_interface->deleteLater(); + server_interface = nullptr; + + if (server_properties_interface) + server_properties_interface->deleteLater(); + server_properties_interface = nullptr; + + serverRunningChanged(m_serverRunning = false); + + if (isHeadsetConnected()) + headsetConnectedChanged(m_headsetConnected = false); +} + +void wivrn_server::refresh_server_properties() +{ + if (!server_properties_interface) + return; + + QDBusPendingReply props_pending = server_properties_interface->GetAll("io.github.wivrn.Server"); + + if (get_all_properties_call_watcher) + get_all_properties_call_watcher->deleteLater(); + get_all_properties_call_watcher = new QDBusPendingCallWatcher{props_pending, this}; + + connect(get_all_properties_call_watcher, &QDBusPendingCallWatcher::finished, [this, props_pending]() { + on_server_properties_changed("io.github.wivrn.Server", props_pending.value(), {}); + }); +} + +void wivrn_server::on_server_properties_changed(const QString & interface_name, const QVariantMap & changed_properties, const QStringList & invalidated_properties) +{ + if (interface_name != IoGithubWivrnServerInterface::staticInterfaceName()) + return; + + if (changed_properties.contains("HeadsetConnected")) + { + headsetConnectedChanged(m_headsetConnected = changed_properties["HeadsetConnected"].toBool()); + } + + if (changed_properties.contains("RecommendedEyeSize")) + { + const auto arg = qvariant_cast(changed_properties["RecommendedEyeSize"]); + + arg.beginStructure(); + arg >> m_recommendedEyeSize.rwidth() >> m_recommendedEyeSize.rheight(); + arg.endStructure(); + recommendedEyeSizeChanged(m_recommendedEyeSize); + } + + if (changed_properties.contains("AvailableRefreshRates")) + { + const auto rates = qvariant_cast(changed_properties["AvailableRefreshRates"]); + + m_availableRefreshRates.clear(); + rates.beginArray(); + while (!rates.atEnd()) + { + double element; + rates >> element; + m_availableRefreshRates.push_back(element); + } + rates.endArray(); + + availableRefreshRatesChanged(m_availableRefreshRates); + } + + if (changed_properties.contains("PreferredRefreshRate")) + { + preferredRefreshRateChanged(m_preferredRefreshRate = changed_properties["PreferredRefreshRate"].toFloat()); + } + + if (changed_properties.contains("EyeGaze")) + { + eyeGazeChanged(m_eyeGaze = changed_properties["EyeGaze"].toBool()); + } + + if (changed_properties.contains("FaceTracking")) + { + faceTrackingChanged(m_faceTracking = changed_properties["FaceTracking"].toBool()); + } + + if (changed_properties.contains("FieldOfView")) + { + const auto fovs = qvariant_cast(changed_properties["FieldOfView"]); + fovs.beginArray(); + + QStringList fov_str; + m_fieldOfView.clear(); + while (!fovs.atEnd()) + { + fovs.beginStructure(); + double left, right, up, down; + fovs >> left >> right >> up >> down; + fovs.endStructure(); + m_fieldOfView.push_back(field_of_view(left, right, up, down)); + } + fovs.endArray(); + + fieldOfViewChanged(m_fieldOfView); + } + + if (changed_properties.contains("HandTracking")) + { + handTrackingChanged(m_handTracking = changed_properties["HandTracking"].toBool()); + } + + if (changed_properties.contains("MicChannels")) + { + micChannelsChanged(m_micChannels = changed_properties["MicChannels"].toInt()); + } + + if (changed_properties.contains("MicSampleRate")) + { + micSampleRateChanged(m_micSampleRate = changed_properties["MicSampleRate"].toInt()); + } + + if (changed_properties.contains("SpeakerChannels")) + { + speakerChannelsChanged(m_speakerChannels = changed_properties["SpeakerChannels"].toInt()); + } + + if (changed_properties.contains("SpeakerSampleRate")) + { + speakerSampleRateChanged(m_speakerSampleRate = changed_properties["SpeakerSampleRate"].toInt()); + } + + if (changed_properties.contains("SupportedCodecs")) + { + supportedCodecsChanged(m_supportedCodecs = changed_properties["SupportedCodecs"].toStringList()); + } + + if (changed_properties.contains("SteamCommand")) + { + steamCommandChanged(m_steamCommand = changed_properties["SteamCommand"].toString()); + } +} + +void wivrn_server::setJsonConfiguration(QString new_configuration) +{ + server_interface->setJsonConfiguration(m_jsonConfiguration = new_configuration); +} + +QString wivrn_server::hostname() +{ + static auto _hostname = []() -> QString { + OrgFreedesktopDBusPropertiesInterface hostname1("org.freedesktop.hostname1", "/org/freedesktop/hostname1", QDBusConnection::systemBus()); + + for (auto property: {"PrettyHostname", "StaticHostname", "Hostname"}) + { + QString name = hostname1.Get("org.freedesktop.hostname1", property).value().variant().toString(); + + if (name != "") + return name; + }; + + char buf[HOST_NAME_MAX]; + int code = gethostname(buf, sizeof(buf)); + if (code == 0) + return buf; + + qDebug() << "Failed to get hostname"; + return "no-hostname"; + }(); + + return _hostname; +} + +void wivrn_server::disconnect_headset() +{ + if (server_interface) + server_interface->Disconnect(); +} + +void wivrn_server::quit() +{ + if (server_interface) + server_interface->Quit(); +} + +#include "moc_wivrn_server.cpp" diff --git a/dashboard/wivrn_server.h b/dashboard/wivrn_server.h new file mode 100644 index 00000000..41c5c80b --- /dev/null +++ b/dashboard/wivrn_server.h @@ -0,0 +1,197 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include +#include +#include + +#include "wivrn_qdbus_types.h" + +class IoGithubWivrnServerInterface; +class OrgFreedesktopDBusPropertiesInterface; + +class wivrn_server : public QObject +{ + Q_OBJECT + + IoGithubWivrnServerInterface * server_interface = nullptr; + OrgFreedesktopDBusPropertiesInterface * server_properties_interface = nullptr; + QDBusServiceWatcher dbus_watcher; + QDBusPendingCallWatcher * get_all_properties_call_watcher = nullptr; + +public: + wivrn_server(QObject * parent = nullptr); + wivrn_server(const wivrn_server &) = delete; + wivrn_server & operator=(const wivrn_server &) = delete; + ~wivrn_server(); + + // Server information + Q_PROPERTY(bool serverRunning READ isServerRunning NOTIFY serverRunningChanged) + Q_PROPERTY(bool headsetConnected READ isHeadsetConnected NOTIFY headsetConnectedChanged) + Q_PROPERTY(QString jsonConfiguration READ jsonConfiguration WRITE setJsonConfiguration) + + // Headset information, valid only if HeadsetConnected is true + Q_PROPERTY(QSize recommendedEyeSize READ recommendedEyeSize NOTIFY recommendedEyeSizeChanged) + Q_PROPERTY(std::vector availableRefreshRates READ availableRefreshRates NOTIFY availableRefreshRatesChanged) + Q_PROPERTY(float preferredRefreshRate READ preferredRefreshRate NOTIFY preferredRefreshRateChanged) + Q_PROPERTY(bool eyeGaze READ eyeGaze NOTIFY eyeGazeChanged) + Q_PROPERTY(bool faceTracking READ faceTracking NOTIFY faceTrackingChanged) + Q_PROPERTY(std::vector fieldOfView READ fieldOfView NOTIFY fieldOfViewChanged) + Q_PROPERTY(bool handTracking READ handTracking NOTIFY handTrackingChanged) + Q_PROPERTY(int micChannels READ micChannels NOTIFY micChannelsChanged) + Q_PROPERTY(int micSampleRate READ micSampleRate NOTIFY micSampleRateChanged) + Q_PROPERTY(int speakerChannels READ speakerChannels NOTIFY speakerChannelsChanged) + Q_PROPERTY(int speakerSampleRate READ speakerSampleRate NOTIFY speakerSampleRateChanged) + Q_PROPERTY(QStringList supportedCodecs READ supportedCodecs NOTIFY supportedCodecsChanged) + Q_PROPERTY(QString steamCommand READ steamCommand NOTIFY steamCommandChanged) + + // hostnamed + Q_PROPERTY(QString hostname READ hostname()) + + bool isServerRunning() const + { + return m_serverRunning; + } + + bool isHeadsetConnected() const + { + return m_headsetConnected; + } + + QString jsonConfiguration() const + { + return m_jsonConfiguration; + } + + void setJsonConfiguration(QString); + + QSize recommendedEyeSize() const + { + return m_recommendedEyeSize; + } + + const std::vector & availableRefreshRates() const + { + return m_availableRefreshRates; + } + + float preferredRefreshRate() const + { + return m_preferredRefreshRate; + } + + bool eyeGaze() const + { + return m_eyeGaze; + } + + bool faceTracking() const + { + return m_faceTracking; + } + + const std::vector & fieldOfView() const + { + return m_fieldOfView; + } + + bool handTracking() const + { + return m_handTracking; + } + + int micChannels() const + { + return m_micChannels; + } + + int micSampleRate() const + { + return m_micSampleRate; + } + + int speakerChannels() const + { + return m_speakerChannels; + } + + int speakerSampleRate() const + { + return m_speakerSampleRate; + } + + QStringList supportedCodecs() const + { + return m_supportedCodecs; + } + + QString steamCommand() const + { + return m_steamCommand; + } + + QString hostname(); + + void disconnect_headset(); + void quit(); + +private: + void on_server_dbus_registered(); + void on_server_dbus_unregistered(); + void on_server_properties_changed(const QString & interface_name, const QVariantMap & changed_properties, const QStringList & invalidated_properties); + + void refresh_server_properties(); + + bool m_serverRunning{}; + bool m_headsetConnected{}; + QString m_jsonConfiguration{}; + QSize m_recommendedEyeSize{}; + std::vector m_availableRefreshRates{}; + float m_preferredRefreshRate{}; + bool m_eyeGaze{}; + bool m_faceTracking{}; + std::vector m_fieldOfView{}; + bool m_handTracking{}; + int m_micChannels{}; + int m_micSampleRate{}; + int m_speakerChannels{}; + int m_speakerSampleRate{}; + QStringList m_supportedCodecs{}; + QString m_steamCommand{}; + +Q_SIGNALS: + void serverRunningChanged(bool); + void headsetConnectedChanged(bool); + + void recommendedEyeSizeChanged(QSize); + void availableRefreshRatesChanged(const std::vector &); + void preferredRefreshRateChanged(float); + void eyeGazeChanged(bool); + void faceTrackingChanged(bool); + void fieldOfViewChanged(const std::vector &); + void handTrackingChanged(bool); + void micChannelsChanged(int); + void micSampleRateChanged(int); + void speakerChannelsChanged(int); + void speakerSampleRateChanged(int); + void supportedCodecsChanged(QStringList); + void steamCommandChanged(QString); +}; diff --git a/dashboard/wizard.cpp b/dashboard/wizard.cpp new file mode 100644 index 00000000..8fc98306 --- /dev/null +++ b/dashboard/wizard.cpp @@ -0,0 +1,406 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "wizard.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ui_wizard.h" + +#include "wivrn_server.h" + +#include "gui_config.h" +#include + +enum class wizard_page +{ + select_headset_model, + sideload_download, + sideload_install, + connect_hmd, + start_game +}; + +struct headset +{ + QString name; + QString devmode_url; + QString store_name; + QString store_url; +}; + +static const std::vector headsets_info = { + // clang-format off + {"HTC Vive Focus 3", "https://developer.vive.com/resources/hardware-guides/vive-focus-specs-user-guide/how-do-i-put-focus-developer-mode/"}, + {"HTC Vive XR Elite", "https://developer.vive.com/resources/hardware-guides/vive-focus-specs-user-guide/how-do-i-put-focus-developer-mode/"}, + {"Meta Quest 1", "https://developers.meta.com/horizon/documentation/native/android/mobile-device-setup/#enable-developer-mode"}, + {"Meta Quest 2", "https://developers.meta.com/horizon/documentation/native/android/mobile-device-setup/#enable-developer-mode", "Meta Store", "https://www.meta.com/experiences/7959676140827574/"}, + {"Meta Quest 3", "https://developers.meta.com/horizon/documentation/native/android/mobile-device-setup/#enable-developer-mode", "Meta Store", "https://www.meta.com/experiences/7959676140827574/"}, + {"Meta Quest Pro", "https://developers.meta.com/horizon/documentation/native/android/mobile-device-setup/#enable-developer-mode", "Meta Store", "https://www.meta.com/experiences/7959676140827574/"}, + {"Pico Neo 4", "https://developer.picoxr.com/document/unreal/test-and-build/#Enable%20developer%20mode"}, + // clang-format on +}; + +static constexpr int role_devmode_url = Qt::UserRole + 1; +static constexpr int role_store_name = Qt::UserRole + 2; +static constexpr int role_store_url = Qt::UserRole + 3; + +wizard::wizard() : + server(new wivrn_server(this)), + apk_file(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/wivrn.apk") +{ + ui = new Ui::Wizard; + ui->setupUi(this); + + retranslate(); + + connect(this, &QWizard::currentIdChanged, this, &wizard::on_page_changed); + connect(this, &QWizard::customButtonClicked, this, &wizard::on_custom_button_clicked); + + connect(ui->copy_steam_command, &QPushButton::clicked, this, [&]() { + QGuiApplication::clipboard()->setText(ui->label_steam_command->text()); + }); + + connect(ui->copy_adb_command, &QPushButton::clicked, this, [&]() { + QGuiApplication::clipboard()->setText(ui->label_adb_install->text()); + }); + + connect(server, &wivrn_server::headsetConnectedChanged, this, &wizard::on_headset_connected_changed); + + connect(ui->button_cancel_download, &QPushButton::clicked, this, &wizard::cancel_download); + + connect(server, &wivrn_server::steamCommandChanged, this, [this](QString value) { + ui->label_steam_command->setText(value); + }); + ui->label_steam_command->setText(server->steamCommand()); + + setPixmap(WatermarkPixmap, QPixmap(":/images/wivrn.svg")); + + ui->label_adb_install->setText("adb install -r " + apk_file.fileName()); + apk_downloaded = QFileInfo(apk_file).exists() and (settings.value("client_apk_url").toString() == WIVRN_CLIENT_URL); + + for (const headset & i: headsets_info) + { + auto item = new QStandardItem(i.name); + + item->setData(i.devmode_url, role_devmode_url); + item->setData(i.store_name, role_store_name); + item->setData(i.store_url, role_store_url); + + headsets.appendRow(item); + } + headsets.appendRow(new QStandardItem(tr("Other"))); // TODO retranslatable + + ui->combo_hmd_model->setModel(&headsets); + ui->combo_hmd_model->setCurrentIndex(-1); + connect(ui->combo_hmd_model, &QComboBox::currentIndexChanged, this, &wizard::on_headset_model_changed); + connect(ui->check_sideload, &QCheckBox::clicked, this, &wizard::on_headset_model_changed); + + setWindowModality(Qt::WindowModality::ApplicationModal); +} + +void wizard::on_headset_model_changed() +{ + auto devmode_url = ui->combo_hmd_model->currentData(role_devmode_url).toString(); + auto store_name = ui->combo_hmd_model->currentData(role_store_name).toString(); + auto store_url = ui->combo_hmd_model->currentData(role_store_url).toString(); + + ui->label_store_url->setText(QString(R"(

%2

)").arg(store_url).arg(store_name)); + ui->label_devmode_url->setText(QString(R"(

%2

)").arg(devmode_url).arg(tr("How?"))); + + if (ui->combo_hmd_model->currentIndex() < 0) + { + ui->widget_store->setVisible(false); + ui->check_sideload->setVisible(false); + button(NextButton)->setEnabled(false); + } + else if (store_name != "") + { + ui->widget_store->setVisible(not ui->check_sideload->isChecked()); + ui->check_sideload->setVisible(true); + button(NextButton)->setEnabled(true); + } + else + { + ui->widget_store->setVisible(false); + ui->check_sideload->setVisible(false); + button(NextButton)->setEnabled(true); + } + + ui->label_devmode_url->setVisible(devmode_url != ""); + + if (nextId() == (int)wizard_page::sideload_download and ui->combo_hmd_model->currentIndex() >= 0) + button(NextButton)->setText(tr("Download")); + else + button(NextButton)->setText(QWizard::tr("&Next >", "do not translate, the QWizard translation will be used")); +} + +void wizard::on_custom_button_clicked(int which) +{ + switch ((wizard_page)currentId()) + { + case wizard_page::select_headset_model: + if (which == QWizard::CustomButton1) // Download + next(); + else if (which == QWizard::CustomButton2) // Skip + setCurrentId((int)wizard_page::connect_hmd); + return; + + case wizard_page::sideload_download: + return; + + case wizard_page::sideload_install: + return; + + case wizard_page::connect_hmd: + if (which == QWizard::CustomButton1) // Skip + next(); + return; + + case wizard_page::start_game: + return; + } +} + +void wizard::on_page_changed(int id) +{ + switch ((wizard_page)id) + { + case wizard_page::select_headset_model: + button(WizardButton::CustomButton1)->setText(tr("Download")); + button(WizardButton::CustomButton2)->setText(tr("Skip")); + + setButtonLayout({QWizard::Stretch, QWizard::BackButton, QWizard::NextButton, QWizard::CustomButton2, QWizard::CancelButton}); + on_headset_model_changed(); + return; + + case wizard_page::sideload_download: + assert(not apk_downloaded); + start_download(); + + setButtonLayout({QWizard::Stretch, QWizard::BackButton, QWizard::NextButton, QWizard::CancelButton}); + button(BackButton)->setEnabled(false); + button(NextButton)->setEnabled(false); + return; + + case wizard_page::sideload_install: + setButtonLayout({QWizard::Stretch, QWizard::BackButton, QWizard::NextButton, QWizard::CancelButton}); + return; + + case wizard_page::connect_hmd: + button(WizardButton::CustomButton1)->setText(tr("Skip")); + setButtonLayout({QWizard::Stretch, QWizard::BackButton, QWizard::NextButton, QWizard::CustomButton1, QWizard::CancelButton}); + on_headset_connected_changed(server->isHeadsetConnected()); + return; + + case wizard_page::start_game: + setButtonLayout({QWizard::Stretch, QWizard::BackButton, QWizard::FinishButton, QWizard::CancelButton}); + return; + } +} + +void wizard::changeEvent(QEvent * e) +{ + QWidget::changeEvent(e); + + switch (e->type()) + { + case QEvent::LanguageChange: + retranslate(); + break; + + default: + break; + } +} + +int wizard::nextId() const +{ + switch ((wizard_page)currentId()) + { + case wizard_page::select_headset_model: + if (ui->combo_hmd_model->currentData(role_store_name).toString() != "" and not ui->check_sideload->isChecked()) + return (int)wizard_page::connect_hmd; + else if (apk_downloaded) + return (int)wizard_page::sideload_install; + else + return (int)wizard_page::sideload_download; + + case wizard_page::sideload_install: + return (int)wizard_page::connect_hmd; + + default: + return QWizard::nextId(); + } +} + +void wizard::retranslate() +{ + ui->retranslateUi(this); + ui->label_how_to_connect->setText(tr("Start the WiVRn app on your headset and connect to \"%1\".").arg(server->hostname())); + on_headset_connected_changed(server->isHeadsetConnected()); +} + +wizard::~wizard() +{ + delete ui; + ui = nullptr; +} + +void wizard::start_download() +{ + ui->button_cancel_download->setEnabled(true); + + QUrl url(WIVRN_CLIENT_URL); + + qDebug() << "Downloading from " << url.toString(); + + auto apk_dir = std::filesystem::path(apk_file.fileName().toStdString()).parent_path(); + std::filesystem::create_directories(apk_dir); + + apk_file.open(QIODeviceBase::WriteOnly | QIODeviceBase::Truncate); + + QNetworkRequest request(url); + + if (reply) + { + disconnect(reply, &QNetworkReply::downloadProgress, this, &wizard::on_download_progress); + disconnect(reply, &QNetworkReply::errorOccurred, this, &wizard::on_download_error); + disconnect(reply, &QNetworkReply::finished, this, &wizard::on_download_finished); + reply->abort(); + reply->deleteLater(); + } + + reply = manager.get(request); + + connect(reply, &QNetworkReply::downloadProgress, this, &wizard::on_download_progress); + connect(reply, &QNetworkReply::errorOccurred, this, &wizard::on_download_error); + connect(reply, &QNetworkReply::finished, this, &wizard::on_download_finished); + + ui->progress_download->setValue(0); +} + +void wizard::cancel_download() +{ + assert(reply); + + disconnect(reply, &QNetworkReply::downloadProgress, this, &wizard::on_download_progress); + disconnect(reply, &QNetworkReply::errorOccurred, this, &wizard::on_download_error); + disconnect(reply, &QNetworkReply::finished, this, &wizard::on_download_finished); + reply->abort(); + reply->deleteLater(); + reply = nullptr; + + // Cancel and commit to close without saving the already written data, so that it can be reopened + apk_file.cancelWriting(); + apk_file.commit(); + + back(); +} + +void wizard::on_download_progress(qint64 bytesReceived, qint64 bytesTotal) +{ + assert(reply); + + if (not reply->error()) + { + if (bytesTotal > 0) + ui->progress_download->setValue(bytesReceived * 100 / bytesTotal); + + apk_file.write(reply->readAll()); + } +} + +void wizard::on_download_error(QNetworkReply::NetworkError code) +{ + qDebug() << "Download error" << code; + + // Cancel and commit to close without saving the already written data, so that it can be reopened + apk_file.cancelWriting(); + apk_file.commit(); + + QMessageBox msgbox /*(this)*/; + msgbox.setIcon(QMessageBox::Critical); + msgbox.setText(tr("Error downloading the client:\n%1").arg(QMetaEnum::fromType().valueToKey(code))); + msgbox.setStandardButtons(QMessageBox::Retry | QMessageBox::Cancel); + +#ifdef WORKAROUND_QTBUG_90005 + setEnabled(false); +#endif + + switch (msgbox.exec()) + { + case QMessageBox::Retry: + start_download(); + break; + + case QMessageBox::Cancel: + back(); + break; + } + +#ifdef WORKAROUND_QTBUG_90005 + setEnabled(true); +#endif +} + +void wizard::on_download_finished() +{ + assert(reply); + + if (not reply->error()) + { + reply->deleteLater(); + reply = nullptr; + + ui->button_cancel_download->setEnabled(false); + apk_file.commit(); + apk_downloaded = true; + settings.setValue("client_apk_url", WIVRN_CLIENT_URL); + + back(); // Remove current page from history before going to the install page + setCurrentId((int)wizard_page::sideload_install); + } +} + +void wizard::on_headset_connected_changed(bool connected) +{ + if (currentId() == (int)wizard_page::connect_hmd) + { + if (connected) + ui->label_client_status->setText(tr("The headset is connected.")); + else + ui->label_client_status->setText(tr("The headset is not connected.")); + + button(NextButton)->setEnabled(connected); + ui->widget_troubleshoot->setHidden(connected); + } +} + +#include "moc_wizard.cpp" diff --git a/dashboard/wizard.h b/dashboard/wizard.h new file mode 100644 index 00000000..1b4921e3 --- /dev/null +++ b/dashboard/wizard.h @@ -0,0 +1,70 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace Ui +{ +class Wizard; +} + +class wivrn_server; + +class wizard : public QWizard +{ + Q_OBJECT + + Ui::Wizard * ui = nullptr; + QStandardItemModel headsets; + + wivrn_server * server; + + QSettings settings; + QNetworkAccessManager manager; + QNetworkReply * reply = nullptr; + QSaveFile apk_file; + bool apk_downloaded = false; + +public: + wizard(); + ~wizard(); + + void changeEvent(QEvent * e) override; + void retranslate(); + + int nextId() const override; + + void on_page_changed(int id); + + void start_download(); + void cancel_download(); + void on_download_progress(qint64 bytesReceived, qint64 bytesTotal); + void on_download_error(QNetworkReply::NetworkError code); + void on_download_finished(); + + void on_headset_model_changed(); + void on_headset_connected_changed(bool); + void on_custom_button_clicked(int which); +}; diff --git a/dashboard/wizard.ui b/dashboard/wizard.ui new file mode 100644 index 00000000..719c1530 --- /dev/null +++ b/dashboard/wizard.ui @@ -0,0 +1,526 @@ + + + Wizard + + + + 0 + 0 + 846 + 586 + + + + Connection wizard + + + true + + + 1 + + + + Welcome + + + + + + 0 + + + + + + Qt::Orientation::Vertical + + + QSizePolicy::Policy::Fixed + + + + 20 + 40 + + + + + + + + You will need to have the WiVRn client installed on your headset. If the client is already installed, click "Skip". + + + true + + + + + + + + + -1 + + + Select your headset + + + + + + + Qt::Orientation::Horizontal + + + + 40 + 20 + + + + + + + + + + I want to sideload the client instead + + + + + + + + 0 + + + 0 + + + + + + + Go to the store to install the client app on your headset. + + + true + + + true + + + + + + + store_url + + + Qt::TextFormat::RichText + + + true + + + + + + + + + + + + Qt::Orientation::Vertical + + + + 20 + 40 + + + + + + + + + Downloading the WiVRn app + + + + + + 1 + + + + + + Qt::Orientation::Vertical + + + QSizePolicy::Policy::Fixed + + + + 20 + 40 + + + + + + + + + + 0 + + + + + + + Cancel + + + + + + + + + Downloading + + + + + + + Qt::Orientation::Vertical + + + + 20 + 40 + + + + + + + + + Install the WiVRn app on your headset + + + + + + 2 + + + + + + Qt::Orientation::Vertical + + + QSizePolicy::Policy::Fixed + + + + 20 + 40 + + + + + + + + + + Make sure your headset is in developer mode to continue. + + + true + + + + + + + devmode_url + + + Qt::TextFormat::RichText + + + true + + + + + + + + + Run the following command to install the client: + + + true + + + + + + + + + Copy to clipboard + + + + + + + + + + + + + + Noto Sans Mono + + + + IBeamCursor + + + adb install wivrn.apk + + + Qt::TextInteractionFlag::TextSelectableByKeyboard|Qt::TextInteractionFlag::TextSelectableByMouse + + + + + + + + + Qt::Orientation::Vertical + + + + 20 + 40 + + + + + + + + + Start the WiVRn app and connect to this computer + + + + + + 3 + + + + + + Qt::Orientation::Vertical + + + QSizePolicy::Policy::Fixed + + + + 20 + 40 + + + + + + + + client_status + + + true + + + + + + + Qt::Orientation::Vertical + + + QSizePolicy::Policy::Fixed + + + + 20 + 40 + + + + + + + + + 0 + + + 0 + + + + + connect_to_this_server + + + + + + + If the server is not visible or the connection fails, check that port 5353 (UDP) and 9757 (TCP and UDP) are open in your firewall. + + + true + + + + + + + + + + Qt::Orientation::Vertical + + + + 20 + 40 + + + + + + + + + Finished + + + + + + 4 + + + + + + Qt::Orientation::Vertical + + + QSizePolicy::Policy::Fixed + + + + 20 + 40 + + + + + + + + You can now start an OpenXR application on this computer. + + + + + + + For Steam games, set the command to: + + + Qt::TextFormat::PlainText + + + true + + + Qt::TextInteractionFlag::NoTextInteraction + + + + + + + + + Copy to clipboard + + + + + + + + + + + + + IBeamCursor + + + steam_command + + + Qt::TextInteractionFlag::NoTextInteraction + + + + + + + + + Qt::Orientation::Vertical + + + + 20 + 40 + + + + + + + + + + diff --git a/dbus/io.github.wivrn.Server.xml b/dbus/io.github.wivrn.Server.xml index df9ad3e0..176560be 100644 --- a/dbus/io.github.wivrn.Server.xml +++ b/dbus/io.github.wivrn.Server.xml @@ -10,6 +10,7 @@ + @@ -19,6 +20,7 @@ + @@ -32,14 +34,20 @@ - - + + + + + + - + + + diff --git a/flatpak/io.github.wivrn.wivrn.desktop b/flatpak/io.github.wivrn.wivrn.desktop index 55516c44..8e49cd30 100644 --- a/flatpak/io.github.wivrn.wivrn.desktop +++ b/flatpak/io.github.wivrn.wivrn.desktop @@ -5,5 +5,4 @@ GenericName=WiVRn server Exec=launch-wivrn-server Icon=io.github.wivrn.wivrn Type=Application -Categories=ConsoleOnly -Terminal=true +Categories=Network;Game diff --git a/flatpak/io.github.wivrn.wivrn.metainfo.xml b/flatpak/io.github.wivrn.wivrn.metainfo.xml index 658dd628..e56d5a69 100644 --- a/flatpak/io.github.wivrn.wivrn.metainfo.xml +++ b/flatpak/io.github.wivrn.wivrn.metainfo.xml @@ -1,5 +1,5 @@ - + io.github.wivrn.wivrn WiVRn server FSFAP @@ -41,6 +41,18 @@ io.github.wivrn.wivrn.desktop + + Game + Network + + + + + https://wivrn.github.io/assets/img/mountains.jpeg + A caption + + + https://wivrn.github.io https://www.github.com/WiVRn/WiVRn https://github.com/WiVRn/WiVRn/issues diff --git a/flatpak/io.github.wivrn.wivrn.yml b/flatpak/io.github.wivrn.wivrn.yml index 7aec1606..eb52d81d 100644 --- a/flatpak/io.github.wivrn.wivrn.yml +++ b/flatpak/io.github.wivrn.wivrn.yml @@ -1,7 +1,7 @@ id: io.github.wivrn.wivrn -runtime: org.freedesktop.Platform -runtime-version: '23.08' -sdk: org.freedesktop.Sdk +runtime: org.kde.Platform +runtime-version: '6.7' +sdk: org.kde.Sdk command: launch-wivrn-server finish-args: @@ -26,6 +26,8 @@ finish-args: # Let outside application access the WiVRn socket - --filesystem=xdg-run/wivrn:create - --own-name=io.github.wivrn.Server + # QSystemTrayIcon + - --talk-name=org.kde.StatusNotifierWatcher cleanup: - /lib/pkgconfig @@ -144,6 +146,8 @@ modules: config-opts: - -DCMAKE_BUILD_TYPE=RelWithDebInfo - -DWIVRN_BUILD_CLIENT=OFF + - -DWIVRN_BUILD_SERVER=ON + - -DWIVRN_BUILD_DASHBOARD=ON - -DWIVRN_USE_VAAPI=ON - -DWIVRN_USE_X264=ON - -DWIVRN_USE_NVENC=ON @@ -198,7 +202,7 @@ modules: - sed -ne 's#app-path=\(.*\)#{"runtime":["\1/OpenComposite"],"version":1}#p' /.flatpak-info > $XDG_CONFIG_HOME/openvr/openvrpaths.vrpath - chmod -w $XDG_CONFIG_HOME/openvr/openvrpaths.vrpath - - - wivrn-server + - wivrn-dashboard - - rm -f $XDG_CONFIG_HOME/openvr/openvrpaths.vrpath - if [ -f $XDG_CONFIG_HOME/openvrpaths.vrpath-backup ] diff --git a/wivrn-dashboard.qrc b/wivrn-dashboard.qrc new file mode 100644 index 00000000..bf8c8578 --- /dev/null +++ b/wivrn-dashboard.qrc @@ -0,0 +1,6 @@ + + + images/wivrn.svg + assets/wivrn.png + +