diff --git a/Cargo.lock b/Cargo.lock index 82e8048359..3b75819e21 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -575,17 +575,23 @@ dependencies = [ ] [[package]] -name = "obs-gpu-status" +name = "obs-fallback-warning" +version = "0.1.0" + +[[package]] +name = "obs-frontend" version = "0.1.0" dependencies = [ - "libloading", + "obs-fallback-warning", + "obs-gpu-status", ] [[package]] -name = "obs-gpu-status-frontend" +name = "obs-gpu-status" version = "0.1.0" dependencies = [ - "obs-gpu-status", + "libloading", + "obs-fallback-warning", ] [[package]] diff --git a/ci.toml b/ci.toml index f396c25143..061b6ed75c 100644 --- a/ci.toml +++ b/ci.toml @@ -1024,7 +1024,7 @@ issue = "https://github.com/obs-rust/obs-studio/issues/962" expires = "2027-04-15" [[exceptions]] rule = "RUST-018" -path = "rust/obs-gpu-status-frontend/Cargo.toml" +path = "rust/obs-frontend/Cargo.toml" reason = "No workspace complexity lint configured yet." issue = "https://github.com/obs-rust/obs-studio/issues/962" expires = "2027-04-15" diff --git a/ci/test_rust_cargo_build_order.py b/ci/test_rust_cargo_build_order.py index 0368a66899..e9a485d7a8 100644 --- a/ci/test_rust_cargo_build_order.py +++ b/ci/test_rust_cargo_build_order.py @@ -98,7 +98,7 @@ def test_application_launcher_uses_the_native_rust_cache_safeguard(self): def test_every_corrosion_import_joins_the_cargo_build_order(self): imports = { "libobs/cmake/rust.cmake": "libobs-rust", - "frontend/cmake/feature-gpu-status.cmake": "obs-gpu-status-frontend", + "frontend/cmake/frontend-rust.cmake": "obs-frontend", "plugins/obs-nvenc/CMakeLists.txt": "obs-nvenc-plugin", } for path, crate in imports.items(): diff --git a/docs/fallback-warning.md b/docs/fallback-warning.md new file mode 100644 index 0000000000..f779a6d850 --- /dev/null +++ b/docs/fallback-warning.md @@ -0,0 +1,93 @@ +# Fallback warning + +Some features of OBS-Studio-Rust have a safe mode and a less safe fallback +mode. When the safe mode cannot work, the feature uses the fallback, so that +the user does not lose the feature. Examples: + +| Feature | Safe mode | Fallback | +|---|---|---| +| Browser source (#1092) | Chromium sandbox | No sandbox | +| Streaming (#2205) | RTMPS | RTMP | + +The fallback must never be silent (decision on #1092). This document gives +the rules for every fallback, and the shared code that applies them +(obs-rust/obs-studio#2218). + +## Rules + +1. Log the fallback at error level, once for each time it occurs. The log + line also goes to stderr. +2. Warn the user in a dialog. The dialog shows what fell back and why, and a + countdown. When the countdown ends after 3 seconds, the dialog accepts the + fallback. The countdown pauses while another modal dialog is open, so the + dialog never accepts unseen. +3. The dialog has an "Accept anyway" button. It has a Cancel button only when + the caller can stop instead of using the fallback. Then Cancel is the + default button. +4. Each fallback shows its dialog once in an OBS session. The log line comes + every time. +5. Do not show a dialog when the user cannot see it: before the main window + has loaded, and while another modal dialog is open (for example the + first-run wizard), the warning waits; with a hidden main window (OBS + started to the tray), the warning accepts at once. +6. Each dialog says: "This may become an error in a future version of OBS." + A fallback is a temporary help, not a supported mode. +7. Do not fall back when a security check fails. For example, a certificate + that does not verify is an error, not a reason to use RTMP. + +## Wording + +Every fallback uses the same words, so the user knows the case at once: + +- **Title:** what runs, and without what. For example "Browser source + without the sandbox", "Streaming unencrypted (RTMP)". +- **Message:** what failed, what OBS does instead, and what the user can do + about it, in this order. One or two short sentences each. +- **Terms:** "sandbox" for the Chromium sandbox, "unencrypted" for a + connection without TLS. Do not use "insecure" or "unsafe mode". +- **Buttons:** "Accept anyway" and "Cancel". The frontend supplies them. +- **Id:** `.`, for example `browser.sandbox`, + `rtmp.unencrypted`. It is in the log line. + +A new fallback uses this helper, not a dialog of its own. Existing +warnings change to this wording case by case. + +## How to use it + +A plugin calls `obs_frontend_warn_fallback()` from `obs-frontend-api.h`: + +```c +static void sandbox_answer(void *param, bool accepted) +{ + /* accepted: continue in the fallback mode. */ +} + +obs_frontend_warn_fallback("browser.sandbox", obs_module_text("SandboxFallback.Title"), + obs_module_text("SandboxFallback.Message"), false, sandbox_answer, data); +``` + +- `id` is a stable name. Use `.`. +- The caller translates `title` and `message`. +- `cb` is called once, on the UI thread, never inside the call. Keep `param` + valid until then. `cb` can be NULL. +- Without the OBS frontend (another host of the plugin), the call logs and + calls `cb` with `true` inside the call. + +The API reference is in +[reference-frontend-api.rst](sphinx/reference-frontend-api.rst). + +## Code + +| Part | Location | +|---|---| +| Decisions: show or accept, what each end means, the countdown, the log line | `rust/obs-fallback-warning` (Rust, tested in its crate) | +| C ABI of the decisions | `frontend/utility/obs-fallback-warning.h`, linked through `rust/obs-frontend` | +| Queue: log at once, wait for the main window, one dialog at a time | `frontend/utility/FallbackWarning` | +| Dialog | `frontend/dialogs/OBSFallbackWarning` | +| API | `obs_frontend_warn_fallback()` in `frontend/api` and `OBSStudioAPI` | + +Without the frontend's Rust (the C rollback build), the frontend logs and +accepts, and shows no dialog. + +Tests: `test_fallback_warning_dialog`, `test_fallback_warning_queue` and +`test_frontend_warn_fallback` in `test/cmocka` (Linux). diff --git a/docs/features.md b/docs/features.md index 2f07e755a1..f6868d3ef4 100644 --- a/docs/features.md +++ b/docs/features.md @@ -285,6 +285,14 @@ not get a line. item opens the OBS Rust Discord, where this build's bugs and questions belong, instead of upstream OBS Studio's server. *All*, 2026-10-24. Issue [#2097](https://github.com/obs-rust/obs-studio/issues/2097). +- **Fallback warning.** When a feature falls back to a less safe mode so + that it keeps working (for example a browser source without the Chromium + sandbox), OBS logs it at error level and shows a warning with a 3-second + countdown that accepts the fallback, once per session. Plugins call + `obs_frontend_warn_fallback()` ([fallback-warning.md](fallback-warning.md)). + *All*, pending merge. Issue + [#2218](https://github.com/obs-rust/obs-studio/issues/2218), PR + [#2238](https://github.com/obs-rust/obs-studio/pull/2238). - **No upstream release notes or donor list downloads.** The What's New dialog, which showed upstream OBS Studio's release notes from obsproject.com, is off by default (`ENABLE_WHATSNEW=OFF`); a build that diff --git a/docs/rust-port/cc-build.md b/docs/rust-port/cc-build.md index 5bd2826de0..1a23a6f125 100644 --- a/docs/rust-port/cc-build.md +++ b/docs/rust-port/cc-build.md @@ -582,9 +582,9 @@ configuration is Linux with browser panels disabled; other feature/platform configurations and release paths remain under conversion. Build the GPU archive with -`soldr cargo build -p obs-gpu-status-frontend --release`, then enable the integration +`soldr cargo build -p obs-frontend --release`, then enable the integration check with `OBS_BUILD_APP=1` and `OBS_BUILD_GPU_ARCHIVE` pointing to the resulting -`target/release/libobs_gpu_status_frontend.a`. The executable runs and reports +`target/release/libobs_frontend.a`. The executable runs and reports `--version` identifies the OBS-Studio-Rust application version as `0.1.0`, based on OBS `33.0.0-cc-build`. This establishes compilation, linking and CLI execution; GUI startup, runtime diff --git a/docs/rust-port/naming.md b/docs/rust-port/naming.md index 4d0d8f0390..b7ccb331f7 100644 --- a/docs/rust-port/naming.md +++ b/docs/rust-port/naming.md @@ -63,7 +63,7 @@ One name per thing, so releases, crates and tags can't be confused (#320). | `libobs/obs-audio-controls.c.h` | `rust/obs-audio-controls` | | `libobs/obs.c.h` and the units extracted from it (`obs-video-plan.c.h`, `obs-context-names.c.h`, `obs-source-load.c.h`), and those extracted from `libobs/obs-module.c.h` (`obs-module-paths.c.h`, `obs-module-names.c.h`, `obs-module-locale.c.h`, `obs-module-source-rules.c.h`, `obs-module-type-rules.c.h`), `libobs/obs-view-api.c.h`, and `obs-video-copy-plan.c.h` and `obs-video-output-step.c.h`, extracted from `libobs/obs-video.c.h`, and `obs-canvas-draw.c.h`, extracted from `libobs/obs.c.h` and `libobs/obs-display.c.h` | `rust/obs-core` | | `plugins/obs-nvenc/` (CUDA/NVENC loader) | `rust/obs-nvenc`, linked through `rust/obs-nvenc-plugin` | -| GPU acceleration status (frontend, #846) | `rust/obs-gpu-status`, linked through `rust/obs-gpu-status-frontend` | +| GPU acceleration status (frontend, #846) | `rust/obs-gpu-status`, linked through `rust/obs-frontend` | | all libobs ports, as one C ABI drop-in | `rust/libobs-rust` | A new libobs area gets a new `obs-` row here in the PR that starts it. @@ -75,6 +75,7 @@ A new libobs area gets a new `obs-` row here in the PR that starts it. | libobs port | `obs-`, named after the libobs directory | `obs-util`, `obs-graphics`, `obs-media-io`, `obs-codec` | | libobs staticlib (C ABI drop-in) | `libobs-rust` | | | Plugin staticlib | `obs--plugin` | `obs-nvenc-plugin` | +| Frontend staticlib (the C ABI of the frontend's Rust crates) | `obs-frontend` | | | Test oracle (dev-only) | `obs-c-oracle` | | | Product binary | `obs-studio-rust` | | diff --git a/docs/sphinx/reference-frontend-api.rst b/docs/sphinx/reference-frontend-api.rst index 91e01d7812..69fa562334 100644 --- a/docs/sphinx/reference-frontend-api.rst +++ b/docs/sphinx/reference-frontend-api.rst @@ -243,6 +243,11 @@ Structures/Enumerations Undo redo callback +.. type:: void (*obs_frontend_fallback_cb)(void *param, bool accepted) + + Fallback warning callback: *accepted* is *true* when the caller continues + in the fallback mode. See :c:func:`obs_frontend_warn_fallback()`. + Functions --------- @@ -1000,3 +1005,38 @@ Functions :return: *true* if OBS was launched in Safe Mode, *false* otherwise .. versionadded:: 33.0 + +--------------------------------------- + +.. function:: void obs_frontend_warn_fallback(const char *id, const char *title, const char *message, bool can_cancel, obs_frontend_fallback_cb cb, void *param) + + Tells the user that a feature fell back to a less safe mode, so that it + keeps working (for example a browser source without the Chromium sandbox). + OBS logs *message* at error level at once, from any thread. Then, on the + UI thread, it shows a warning with a countdown that accepts the fallback + after 3 seconds, and calls *cb* once with the result. + + A warning shows once per *id* in each OBS session, and only one shows at + a time. Warnings wait until the main window has loaded, and while another + modal dialog is open. With a hidden + main window, or when the same *id* already showed, the warning accepts at + once (after the log line). At exit, an open warning closes and queued + warnings accept. + + *cb* is never called inside this call when OBS runs. In a host without + the OBS frontend, this call logs, then calls *cb* with *true* inside the + call. + + See ``docs/fallback-warning.md`` in OBS-Studio-Rust + (obs-rust/obs-studio#2218). + + :param id: A stable name for the fallback, for example + ``"browser.sandbox"``. It is in the log line. + :param title: The window title, translated by the caller + :param message: What fell back and why, translated by the caller + :param can_cancel: *true* if the caller can stop instead. The warning + then has a Cancel button. + :param cb: Called once with *accepted*: *true* for the countdown + and "Accept anyway"; *false* for Cancel or a closed + warning if *can_cancel*, else *true*. Can be NULL. + :param param: Passed to *cb*. Keep it valid until *cb* is called. diff --git a/frontend/CMakeLists.txt b/frontend/CMakeLists.txt index d6de918ac0..a4a446fda8 100644 --- a/frontend/CMakeLists.txt +++ b/frontend/CMakeLists.txt @@ -98,6 +98,8 @@ include(cmake/feature-restream.cmake) include(cmake/feature-youtube.cmake) include(cmake/feature-whatsnew.cmake) include(cmake/feature-idian-playground.cmake) +include(cmake/frontend-rust.cmake) +include(cmake/feature-fallback-warning.cmake) include(cmake/feature-gpu-status.cmake) configure_file(cmake/templates/ui-config.h.in ui-config.h) diff --git a/frontend/OBSStudioAPI.cpp.hpp b/frontend/OBSStudioAPI.cpp.hpp index cde9e97e15..20c6d7c975 100644 --- a/frontend/OBSStudioAPI.cpp.hpp +++ b/frontend/OBSStudioAPI.cpp.hpp @@ -739,6 +739,12 @@ bool OBSStudioAPI::obs_frontend_is_safe_mode_enabled() return safe_mode; } +void OBSStudioAPI::obs_frontend_warn_fallback(const char *id, const char *title, const char *message, bool can_cancel, + obs_frontend_fallback_cb cb, void *param) +{ + FallbackWarning::Warn(id, title, message, can_cancel, cb, param); +} + void OBSStudioAPI::on_load(obs_data_t *settings) { for (size_t i = saveCallbacks.size(); i > 0; i--) { diff --git a/frontend/OBSStudioAPI.hpp b/frontend/OBSStudioAPI.hpp index a058920dd6..66ee1d6b98 100644 --- a/frontend/OBSStudioAPI.hpp +++ b/frontend/OBSStudioAPI.hpp @@ -232,6 +232,9 @@ struct OBSStudioAPI : obs_frontend_callbacks { bool obs_frontend_is_safe_mode_enabled(void) override; + void obs_frontend_warn_fallback(const char *id, const char *title, const char *message, bool can_cancel, + obs_frontend_fallback_cb cb, void *param) override; + void on_load(obs_data_t *settings) override; void on_preload(obs_data_t *settings) override; diff --git a/frontend/api/obs-frontend-api.cpp.hpp b/frontend/api/obs-frontend-api.cpp.hpp index d043ada0c9..84098a70b6 100644 --- a/frontend/api/obs-frontend-api.cpp.hpp +++ b/frontend/api/obs-frontend-api.cpp.hpp @@ -691,5 +691,29 @@ bool obs_frontend_is_safe_mode_enabled(void) return !!callbacks_valid() ? c->obs_frontend_is_safe_mode_enabled() : false; } +void obs_frontend_warn_fallback(const char *id, const char *title, const char *message, bool can_cancel, + obs_frontend_fallback_cb cb, void *param) +{ + if (c) { + c->obs_frontend_warn_fallback(id, title, message, can_cancel, cb, param); + return; + } + + /* No frontend, so nobody to warn: log and accept. The line of + * rust/obs-fallback-warning's log_line(), which the frontend logs. */ + const char *future_error = "This may become an error in a future version of OBS."; + if (!id) { + id = ""; + } + if (message && *message) { + blog(LOG_ERROR, "[fallback] %s: %s %s", id, message, future_error); + } else { + blog(LOG_ERROR, "[fallback] %s: %s", id, future_error); + } + if (cb) { + cb(param, true); + } +} + /* File-local macros (BUILD.md): out of the next file in the unity group. */ #undef callbacks_valid diff --git a/frontend/api/obs-frontend-api.h b/frontend/api/obs-frontend-api.h index aedfd33e70..edfd2a86e5 100644 --- a/frontend/api/obs-frontend-api.h +++ b/frontend/api/obs-frontend-api.h @@ -264,6 +264,13 @@ EXPORT void obs_frontend_paste_sceneitem(obs_scene_t *scene, bool duplicate); EXPORT bool obs_frontend_is_safe_mode_enabled(void); +/* A feature fell back to a less safe mode (obs-rust/obs-studio#2218). Logs + * at error level, warns the user with a countdown, and calls `cb` once on the + * UI thread with whether to continue in the fallback mode. */ +typedef void (*obs_frontend_fallback_cb)(void *param, bool accepted); +EXPORT void obs_frontend_warn_fallback(const char *id, const char *title, const char *message, bool can_cancel, + obs_frontend_fallback_cb cb, void *param); + /* ------------------------------------------------------------------------- */ #ifdef __cplusplus diff --git a/frontend/api/obs-frontend-internal.hpp b/frontend/api/obs-frontend-internal.hpp index 9b7858c226..2973224e82 100644 --- a/frontend/api/obs-frontend-internal.hpp +++ b/frontend/api/obs-frontend-internal.hpp @@ -143,6 +143,9 @@ struct obs_frontend_callbacks { virtual bool obs_frontend_can_paste_sceneitem(bool duplicate) = 0; virtual void obs_frontend_paste_sceneitem(obs_scene_t *scene, bool duplicate) = 0; virtual bool obs_frontend_is_safe_mode_enabled(void) = 0; + + virtual void obs_frontend_warn_fallback(const char *id, const char *title, const char *message, bool can_cancel, + obs_frontend_fallback_cb cb, void *param) = 0; }; EXPORT void obs_frontend_set_callbacks_internal(obs_frontend_callbacks *callbacks); diff --git a/frontend/build/frontend-app-obsstudioapi.pch.hpp b/frontend/build/frontend-app-obsstudioapi.pch.hpp index 1831a6093c..ac7591f790 100644 --- a/frontend/build/frontend-app-obsstudioapi.pch.hpp +++ b/frontend/build/frontend-app-obsstudioapi.pch.hpp @@ -9,6 +9,7 @@ #include "frontend/OBSStudioAPI.hpp" #include +#include #include #include diff --git a/frontend/build/frontend-dialogs-obsfallbackwarning.pch.hpp b/frontend/build/frontend-dialogs-obsfallbackwarning.pch.hpp new file mode 100644 index 0000000000..e1b8a6547b --- /dev/null +++ b/frontend/build/frontend-dialogs-obsfallbackwarning.pch.hpp @@ -0,0 +1,21 @@ +/* Precompiled header (BUILD.md) for the frontend unity groups + * frontend.dialogs-obsfallbackwarning. C++. Every implementation file in them includes this header and + * nothing else: the includes and macro setup below are theirs, in group and + * file order. */ + +#pragma once + +/* dialogs/OBSFallbackWarning.cpp */ +#include "frontend/dialogs/OBSFallbackWarning.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include diff --git a/frontend/build/frontend-fallback-warning.pch.hpp b/frontend/build/frontend-fallback-warning.pch.hpp new file mode 100644 index 0000000000..fab80fef4a --- /dev/null +++ b/frontend/build/frontend-fallback-warning.pch.hpp @@ -0,0 +1,25 @@ +/* Precompiled header (BUILD.md) for the frontend unity groups + * frontend.fallback-warning. C++. Every implementation file in them includes this header and + * nothing else: the includes and macro setup below are theirs, in group and + * file order. */ + +#pragma once + +/* utility/FallbackWarning.cpp */ +#include "frontend/utility/FallbackWarning.hpp" +#include "frontend/dialogs/OBSFallbackWarning.hpp" + +#ifdef OBS_FRONTEND_RUST +#include "frontend/utility/obs-fallback-warning.h" +#endif + +#include + +#include +#include +#include +#include + +#include +#include +#include diff --git a/frontend/build/frontend-widgets.pch.hpp b/frontend/build/frontend-widgets.pch.hpp index a6217d9212..ac0a024618 100644 --- a/frontend/build/frontend-widgets.pch.hpp +++ b/frontend/build/frontend-widgets.pch.hpp @@ -62,6 +62,7 @@ #if defined(_WIN32) || defined(WHATSNEW_ENABLED) #include #endif +#include #include #include #include diff --git a/frontend/build/frontend.dialogs-obsfallbackwarning+.hpp.cpp b/frontend/build/frontend.dialogs-obsfallbackwarning+.hpp.cpp new file mode 100644 index 0000000000..357fdd07e0 --- /dev/null +++ b/frontend/build/frontend.dialogs-obsfallbackwarning+.hpp.cpp @@ -0,0 +1,5 @@ +/* Unity group (BUILD.md): OBSFallbackWarning.cpp on its own (#2218: the Qt test builds it without the frontend). */ + +#include "frontend/build/frontend-dialogs-obsfallbackwarning.pch.hpp" + +#include "frontend/dialogs/OBSFallbackWarning.cpp.hpp" diff --git a/frontend/build/frontend.fallback-warning+.hpp.cpp b/frontend/build/frontend.fallback-warning+.hpp.cpp new file mode 100644 index 0000000000..baa647d718 --- /dev/null +++ b/frontend/build/frontend.fallback-warning+.hpp.cpp @@ -0,0 +1,5 @@ +/* Unity group (BUILD.md): frontend fallback-warning (cpp). */ + +#include "frontend/build/frontend-fallback-warning.pch.hpp" + +#include "frontend/utility/FallbackWarning.cpp.hpp" diff --git a/frontend/build/source-sets.json b/frontend/build/source-sets.json index 97f1058e67..bd96883561 100644 --- a/frontend/build/source-sets.json +++ b/frontend/build/source-sets.json @@ -15,6 +15,13 @@ "utility/ExtraBrowsersDelegate.hpp", "utility/ExtraBrowsersModel.hpp" ], + "FALLBACK_WARNING_RUST_HEADER": [ + "utility/obs-fallback-warning.h" + ], + "FALLBACK_WARNING": [ + "build/frontend.fallback-warning+.hpp.cpp", + "utility/FallbackWarning.hpp" + ], "GPU_STATUS_RUST_HEADER": [ "utility/obs-gpu-status.h" ], @@ -227,6 +234,8 @@ "dialogs/OBSBasicSourceSelect.hpp", "dialogs/OBSBasicTransform.hpp", "dialogs/OBSBasicVCamConfig.hpp", + "build/frontend.dialogs-obsfallbackwarning+.hpp.cpp", + "dialogs/OBSFallbackWarning.hpp", "dialogs/OBSLogViewer.hpp", "dialogs/OBSMissingFiles.hpp", "build/frontend.dialogs-2+.hpp.cpp", diff --git a/frontend/cmake/feature-fallback-warning.cmake b/frontend/cmake/feature-fallback-warning.cmake new file mode 100644 index 0000000000..d156db9cf3 --- /dev/null +++ b/frontend/cmake/feature-fallback-warning.cmake @@ -0,0 +1,11 @@ +include_guard(DIRECTORY) + +# The shared fallback warning (obs-rust/obs-studio#2218). The decisions are +# rust/obs-fallback-warning, linked into the frontend through the frontend's +# staticlib rust/obs-frontend (frontend-rust.cmake). Always built: without +# the frontend's Rust it only logs and accepts. +if(TARGET obs_frontend-static) + obs_frontend_add_sources(FALLBACK_WARNING_RUST_HEADER) +endif() + +obs_frontend_add_sources(FALLBACK_WARNING) diff --git a/frontend/cmake/feature-gpu-status.cmake b/frontend/cmake/feature-gpu-status.cmake index 449b153b18..b1a3163dc6 100644 --- a/frontend/cmake/feature-gpu-status.cmake +++ b/frontend/cmake/feature-gpu-status.cmake @@ -1,57 +1,15 @@ include_guard(DIRECTORY) # GPU acceleration status light (obs-rust/obs-studio#846). The classifier is -# rust/obs-gpu-status, linked into the frontend through the staticlib -# rust/obs-gpu-status-frontend (like obs-nvenc links obs-nvenc-plugin), so -# libobs' exported symbols do not change. +# rust/obs-gpu-status, linked into the frontend through the frontend's +# staticlib rust/obs-frontend (frontend-rust.cmake), so libobs' exported +# symbols do not change. # -# It is built whenever cargo is available (#946): the crate has no crates.io -# dependencies. A build without cargo (the Flatpak sandbox) configures without -# the light and says so. +# It is built whenever the frontend's Rust is (#946). The Flatpak turns the +# light off. option(ENABLE_GPU_STATUS "Build the GPU acceleration status light (needs cargo)" ON) -if(ENABLE_GPU_STATUS AND NOT COMMAND corrosion_import_crate) - # libobs/cmake/rust.cmake fetches Corrosion whenever libobs-with-rust is - # built; otherwise this fetches the same version. - find_program(OBS_GPU_STATUS_CARGO cargo) - if(OBS_GPU_STATUS_CARGO) - include(FetchContent) - include("${CMAKE_SOURCE_DIR}/libobs/cmake/rust-target.cmake") - if(NOT Rust_CARGO_TARGET) - obs_rust_cargo_target(_obs_rust_target "${OS_MACOS}" "${CMAKE_OSX_ARCHITECTURES}") - if(_obs_rust_target) - set(Rust_CARGO_TARGET "${_obs_rust_target}" CACHE STRING "Rust target triple for the frontend's Rust code") - endif() - endif() - FetchContent_Declare(Corrosion GIT_REPOSITORY https://github.com/corrosion-rs/corrosion.git GIT_TAG v0.5.2) - FetchContent_MakeAvailable(Corrosion) - endif() -endif() - -if(ENABLE_GPU_STATUS AND COMMAND corrosion_import_crate) - corrosion_import_crate( - MANIFEST_PATH "${CMAKE_SOURCE_DIR}/Cargo.toml" - CRATES obs-gpu-status-frontend - CRATE_TYPES staticlib - PROFILE release - ) - obs_serialize_cargo_build(obs-gpu-status-frontend) - if(OS_MACOS) - # Same as libobs/cmake/rust.cmake (#777): let the linker use the selected - # Xcode SDK, not the CLT SDK Corrosion injects. - get_target_property(_obs_gpu_status_link_dirs obs_gpu_status_frontend-static INTERFACE_LINK_DIRECTORIES) - if(_obs_gpu_status_link_dirs) - list(REMOVE_ITEM _obs_gpu_status_link_dirs "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib") - set_property( - TARGET obs_gpu_status_frontend-static - PROPERTY INTERFACE_LINK_DIRECTORIES "${_obs_gpu_status_link_dirs}" - ) - endif() - endif() - target_link_libraries(obs-studio PRIVATE obs_gpu_status_frontend-static) - # A staticlib's #[link(name = ...)] system libraries don't reach the final - # link: the Windows GPU engine counters (#1228) need pdh.lib. - target_link_libraries(obs-studio PRIVATE $<$:pdh>) +if(ENABLE_GPU_STATUS AND TARGET obs_frontend-static) obs_frontend_add_sources(GPU_STATUS_RUST_HEADER) target_enable_feature(obs-studio "GPU acceleration status light" OBS_GPU_STATUS) elseif(ENABLE_GPU_STATUS) diff --git a/frontend/cmake/frontend-rust.cmake b/frontend/cmake/frontend-rust.cmake new file mode 100644 index 0000000000..acd968f6a0 --- /dev/null +++ b/frontend/cmake/frontend-rust.cmake @@ -0,0 +1,59 @@ +include_guard(DIRECTORY) + +# The frontend's Rust (obs-rust/obs-studio#2218): one staticlib, +# rust/obs-frontend, with the C ABI of the frontend's crates (obs-gpu-status +# #846, obs-fallback-warning #2218). One staticlib per binary: two would +# duplicate the Rust std symbols. Linked like obs-nvenc links +# obs-nvenc-plugin, so libobs' exported symbols do not change. +# +# Built whenever cargo is available. The default libobs backend (HYBRID) +# needs cargo already. Without it (the OBS_LIBOBS_BACKEND=C rollback build) +# the frontend configures without its Rust and says so: the GPU light is off, +# and the fallback warning only logs and accepts. +if(NOT COMMAND corrosion_import_crate) + # libobs/cmake/rust.cmake fetches Corrosion whenever libobs-with-rust is + # built; otherwise this fetches the same version. + find_program(OBS_FRONTEND_CARGO cargo) + if(OBS_FRONTEND_CARGO) + include(FetchContent) + include("${CMAKE_SOURCE_DIR}/libobs/cmake/rust-target.cmake") + if(NOT Rust_CARGO_TARGET) + obs_rust_cargo_target(_obs_rust_target "${OS_MACOS}" "${CMAKE_OSX_ARCHITECTURES}") + if(_obs_rust_target) + set(Rust_CARGO_TARGET "${_obs_rust_target}" CACHE STRING "Rust target triple for the frontend's Rust code") + endif() + endif() + FetchContent_Declare(Corrosion GIT_REPOSITORY https://github.com/corrosion-rs/corrosion.git GIT_TAG v0.5.2) + FetchContent_MakeAvailable(Corrosion) + endif() +endif() + +if(COMMAND corrosion_import_crate) + corrosion_import_crate( + MANIFEST_PATH "${CMAKE_SOURCE_DIR}/Cargo.toml" + CRATES obs-frontend + CRATE_TYPES staticlib + PROFILE release + ) + obs_serialize_cargo_build(obs-frontend) + if(OS_MACOS) + # Same as libobs/cmake/rust.cmake (#777): let the linker use the selected + # Xcode SDK, not the CLT SDK Corrosion injects. + get_target_property(_obs_frontend_link_dirs obs_frontend-static INTERFACE_LINK_DIRECTORIES) + if(_obs_frontend_link_dirs) + list(REMOVE_ITEM _obs_frontend_link_dirs "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib") + set_property(TARGET obs_frontend-static PROPERTY INTERFACE_LINK_DIRECTORIES "${_obs_frontend_link_dirs}") + endif() + endif() + target_link_libraries(obs-studio PRIVATE obs_frontend-static) + # A staticlib's #[link(name = ...)] system libraries don't reach the final + # link: the Windows GPU engine counters (#1228) need pdh.lib. + target_link_libraries(obs-studio PRIVATE $<$:pdh>) + target_enable_feature(obs-studio "Frontend Rust (rust/obs-frontend)" OBS_FRONTEND_RUST) +else() + message( + WARNING + "cargo not found: building the frontend without its Rust (rust/obs-frontend, obs-rust/obs-studio#2218)" + ) + target_disable_feature(obs-studio "Frontend Rust (cargo not found)") +endif() diff --git a/frontend/data/locale/en-US.ini b/frontend/data/locale/en-US.ini index 0912d016e1..dc10b3fa52 100644 --- a/frontend/data/locale/en-US.ini +++ b/frontend/data/locale/en-US.ini @@ -1903,3 +1903,7 @@ Basic.DeviceBusy.ForceExplain="Force Camera asks %1 to close so OBS can use the Basic.DeviceBusy.Wait="OBS starts the camera as soon as it is free." Basic.DeviceBusy.Force="Force Camera" Basic.DeviceBusy.ForceFailed="%1 (PID %2) did not close, so the camera is still in use. Close it yourself; OBS starts the camera as soon as it is free." + +# Shared fallback warning (obs-rust/obs-studio#2218): a feature fell back to a less safe mode +FallbackWarning.AcceptAnyway="Accept anyway" +FallbackWarning.FutureError="This may become an error in a future version of OBS." diff --git a/frontend/dialogs/OBSFallbackWarning.cpp.hpp b/frontend/dialogs/OBSFallbackWarning.cpp.hpp new file mode 100644 index 0000000000..25e65a37ce --- /dev/null +++ b/frontend/dialogs/OBSFallbackWarning.cpp.hpp @@ -0,0 +1,119 @@ +#include "frontend/build/frontend-dialogs-obsfallbackwarning.pch.hpp" + +/* How often the countdown progress moves. */ +static constexpr int fallback_warning_tick_ms = 50; + +OBSFallbackWarning::OBSFallbackWarning(QWidget *parent, const Texts &texts, qint64 countdownMs_) + : QDialog(parent), + countdownMs(std::clamp(countdownMs_, 0, std::numeric_limits::max())) +{ + setAttribute(Qt::WA_DeleteOnClose); + setModal(false); + setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); + setWindowTitle(texts.title); + + QVBoxLayout *layout = new QVBoxLayout(this); + + messageLabel = new QLabel(texts.message, this); + messageLabel->setObjectName("message"); + messageLabel->setTextFormat(Qt::PlainText); + messageLabel->setWordWrap(true); + layout->addWidget(messageLabel); + + futureErrorLabel = new QLabel(texts.futureError, this); + futureErrorLabel->setObjectName("futureError"); + futureErrorLabel->setTextFormat(Qt::PlainText); + futureErrorLabel->setWordWrap(true); + layout->addWidget(futureErrorLabel); + + progress = new QProgressBar(this); + progress->setObjectName("progress"); + progress->setRange(0, (int)countdownMs); + progress->setValue(0); + progress->setTextVisible(false); + layout->addWidget(progress); + + QDialogButtonBox *buttons = new QDialogButtonBox(this); + acceptButton = buttons->addButton(texts.accept, QDialogButtonBox::AcceptRole); + acceptButton->setObjectName("acceptButton"); + connect(acceptButton, &QPushButton::clicked, this, [this]() { + finish(End::AcceptClicked); + close(); + }); + if (!texts.cancel.isEmpty()) { + /* The safe choice is the default one; the countdown accepts anyway. */ + cancelButton = buttons->addButton(texts.cancel, QDialogButtonBox::RejectRole); + cancelButton->setObjectName("cancelButton"); + cancelButton->setDefault(true); + connect(cancelButton, &QPushButton::clicked, this, [this]() { + finish(End::CancelClicked); + close(); + }); + } + layout->addWidget(buttons); + + timer = new QTimer(this); + timer->setInterval(fallback_warning_tick_ms); + connect(timer, &QTimer::timeout, this, &OBSFallbackWarning::tick); + clock.start(); + timer->start(); +} + +qint64 OBSFallbackWarning::elapsedShown() const +{ + return progress->value(); +} + +/* QDialog::closeEvent() would call reject() and keep the window open while + * it is visible, so this does not call it. */ +void OBSFallbackWarning::closeEvent(QCloseEvent *event) +{ + finish(End::Closed); + event->accept(); +} + +/* Escape. */ +void OBSFallbackWarning::reject() +{ + finish(End::Closed); + close(); +} + +void OBSFallbackWarning::tick() +{ + if (done) { + return; + } + qint64 step = clock.restart(); + /* Another modal dialog covers this one or takes its input (the + * first-run wizard opens right after the main window has loaded): do + * not accept unseen. Go on, in front, once it has closed. */ + QWidget *modal = QApplication::activeModalWidget(); + if (modal && modal != this) { + paused = true; + return; + } + if (paused) { + paused = false; + raise(); + activateWindow(); + } + elapsed = std::min(elapsed + step, countdownMs); + progress->setValue((int)elapsed); + if (elapsed >= countdownMs) { + finish(End::CountdownDone); + close(); + } +} + +/* Reports the first end only: every way out passes here, some twice (a + * button click, then the close it causes). */ +void OBSFallbackWarning::finish(End end) +{ + if (done) { + return; + } + done = true; + timer->stop(); + emit ended(end); +} diff --git a/frontend/dialogs/OBSFallbackWarning.hpp b/frontend/dialogs/OBSFallbackWarning.hpp new file mode 100644 index 0000000000..fb24553d80 --- /dev/null +++ b/frontend/dialogs/OBSFallbackWarning.hpp @@ -0,0 +1,66 @@ +#pragma once + +#include +#include +#include + +class QLabel; +class QProgressBar; +class QPushButton; +class QTimer; + +/* The shared fallback warning (obs-rust/obs-studio#2218): a feature fell back + * to a less safe mode, and the user sees why, with a countdown that accepts + * the fallback by itself. The decisions (whether to show it, what an end + * means) are in rust/obs-fallback-warning; this is only the window. It takes + * every text from its caller (no App(), no Str()), so it builds without the + * frontend. It is not modal: OBS keeps running while it counts down. The + * countdown pauses while another modal dialog is open. */ +class OBSFallbackWarning : public QDialog { + Q_OBJECT + +public: + /* How the dialog ended. The values are the OBS_FALLBACK_WARNING_END_* + * values of the C ABI (rust/obs-fallback-warning/src/ffi/mod.rs). */ + enum class End { CountdownDone = 0, AcceptClicked = 1, CancelClicked = 2, Closed = 3 }; + + struct Texts { + QString title; + QString message; + /* The sentence below the message ("This may become an error ..."). */ + QString futureError; + QString accept; + /* Empty: no Cancel button (the caller cannot stop). */ + QString cancel; + }; + + OBSFallbackWarning(QWidget *parent, const Texts &texts, qint64 countdownMs); + + /* The countdown progress shown, 0 to countdownMs. */ + qint64 elapsedShown() const; + +signals: + /* Emitted exactly once, before the dialog closes. */ + void ended(OBSFallbackWarning::End end); + +protected: + void closeEvent(QCloseEvent *event) override; + void reject() override; + +private: + void tick(); + void finish(End end); + + qint64 countdownMs; + bool done = false; + /* Time counted down, only while no other modal dialog is open. */ + qint64 elapsed = 0; + bool paused = false; + QElapsedTimer clock; + QTimer *timer = nullptr; + QLabel *messageLabel = nullptr; + QLabel *futureErrorLabel = nullptr; + QProgressBar *progress = nullptr; + QPushButton *acceptButton = nullptr; + QPushButton *cancelButton = nullptr; +}; diff --git a/frontend/utility/FallbackWarning.cpp.hpp b/frontend/utility/FallbackWarning.cpp.hpp new file mode 100644 index 0000000000..65a3b87dff --- /dev/null +++ b/frontend/utility/FallbackWarning.cpp.hpp @@ -0,0 +1,163 @@ +#include "frontend/build/frontend-fallback-warning.pch.hpp" + +namespace FallbackWarning { + +struct FwRequest { + std::string id; + std::string title; + std::string message; + bool can_cancel; + Callback cb; + void *param; +}; + +/* UI thread only. */ +static struct { + QPointer window; + Texts texts; + /* SetMainWindow() was called: warnings run instead of waiting. */ + bool ready = false; + std::deque pending; + QPointer open; +} fw_state; + +static const char *fw_text(const char *s) +{ + return s ? s : ""; +} + +static void fw_answer(const FwRequest &r, bool accepted) +{ + if (r.cb) { + r.cb(r.param, accepted); + } +} + +static void fw_log(const char *id, const char *message) +{ +#ifdef OBS_FRONTEND_RUST + char *line = obs_fallback_warning_log_line(id, message); + if (line) { + blog(LOG_ERROR, "%s", line); + obs_fallback_warning_free(line); + } +#else + /* The C rollback build: the line of rust/obs-fallback-warning's log_line(). */ + const char *future_error = "This may become an error in a future version of OBS."; + if (*message) { + blog(LOG_ERROR, "[fallback] %s: %s %s", id, message, future_error); + } else { + blog(LOG_ERROR, "[fallback] %s: %s", id, future_error); + } +#endif +} + +static void fw_pump(); + +#ifdef OBS_FRONTEND_RUST +static void fw_open(const FwRequest &r) +{ + OBSFallbackWarning::Texts t; + t.title = QString::fromStdString(r.title); + t.message = QString::fromStdString(r.message); + t.futureError = fw_state.texts.futureError; + t.accept = fw_state.texts.accept; + t.cancel = r.can_cancel ? fw_state.texts.cancel : QString(); + + OBSFallbackWarning *dialog = + new OBSFallbackWarning(fw_state.window, t, (qint64)obs_fallback_warning_countdown_ms()); + auto answered = std::make_shared(false); + QObject::connect(dialog, &OBSFallbackWarning::ended, qApp, [r, answered](OBSFallbackWarning::End end) { + *answered = true; + fw_state.open = nullptr; + fw_answer(r, obs_fallback_warning_accepted((int)end, r.can_cancel)); + /* The next one after this dialog has closed. */ + QTimer::singleShot(0, qApp, fw_pump); + }); + /* Deleted without an end (its main window went away first): it closed. */ + QObject::connect(dialog, &QObject::destroyed, qApp, [r, answered]() { + if (*answered) { + return; + } + *answered = true; + fw_answer(r, obs_fallback_warning_accepted(OBS_FALLBACK_WARNING_END_CLOSED, r.can_cancel)); + QTimer::singleShot(0, qApp, fw_pump); + }); + fw_state.open = dialog; + dialog->show(); +} +#endif + +#ifdef OBS_FRONTEND_RUST +/* How often the queue looks again while another modal dialog is open. */ +static constexpr int fw_modal_retry_ms = 250; +static bool fw_retry_queued = false; + +static void fw_retry_pump() +{ + fw_retry_queued = false; + fw_pump(); +} +#endif + +/* Runs the queued warnings until one shows a dialog. */ +static void fw_pump() +{ + if (!fw_state.ready || fw_state.open) { + return; + } + while (!fw_state.pending.empty()) { +#ifdef OBS_FRONTEND_RUST + bool visible = fw_state.window && fw_state.window->isVisible(); + /* Another modal dialog (the first-run wizard opens right after + * the main window has loaded) would hide the warning or take its + * input, and it would accept unseen: wait until it has closed. The + * warning is not counted as shown before it shows. */ + if (visible && QApplication::activeModalWidget()) { + if (!fw_retry_queued) { + fw_retry_queued = true; + QTimer::singleShot(fw_modal_retry_ms, qApp, fw_retry_pump); + } + return; + } +#endif + FwRequest r = std::move(fw_state.pending.front()); + fw_state.pending.pop_front(); +#ifdef OBS_FRONTEND_RUST + if (obs_fallback_warning_begin(r.id.c_str(), visible) == OBS_FALLBACK_WARNING_DIALOG) { + fw_open(r); + return; + } +#endif + fw_answer(r, true); + } +} + +void SetMainWindow(QWidget *window, const Texts &texts) +{ + fw_state.window = window; + fw_state.texts = texts; + fw_state.ready = true; + if (!window && fw_state.open) { + fw_state.open->close(); + } + fw_pump(); +} + +void Warn(const char *id, const char *title, const char *message, bool can_cancel, Callback cb, void *param) +{ + id = fw_text(id); + message = fw_text(message); + fw_log(id, message); + + FwRequest r{id, fw_text(title), message, can_cancel, cb, param}; + QMetaObject::invokeMethod( + qApp, + [r]() { + fw_state.pending.push_back(r); + fw_pump(); + }, + Qt::QueuedConnection); +} + +} // namespace FallbackWarning diff --git a/frontend/utility/FallbackWarning.hpp b/frontend/utility/FallbackWarning.hpp new file mode 100644 index 0000000000..7a34db2a04 --- /dev/null +++ b/frontend/utility/FallbackWarning.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include + +class QWidget; + +/* The shared fallback warning (obs-rust/obs-studio#2218), between its callers + * (obs_frontend_warn_fallback) and the window (OBSFallbackWarning). It logs + * at error level at once, then on the UI thread shows the dialog or accepts + * now, as rust/obs-fallback-warning decides, one dialog at a time, and not + * while another modal dialog is open. + * + * Without the frontend's Rust (OBS_FRONTEND_RUST, the C rollback build) it + * only logs and accepts. It does not use App() or OBSBasic: the main window + * hands it the window and the translated texts. */ +namespace FallbackWarning { + +/* Called once per warning, on the UI thread: whether the caller continues in + * the fallback mode. */ +typedef void (*Callback)(void *param, bool accepted); + +/* The texts every dialog shares; each warning brings its title and message. */ +struct Texts { + QString accept; + QString cancel; + QString futureError; +}; + +/* UI thread. Dialogs show on `window` from now on, and warnings that came + * before it run now (the main window calls it when it has loaded). nullptr + * (shutdown): the open dialog closes, and later and queued warnings accept + * without a dialog. */ +void SetMainWindow(QWidget *window, const Texts &texts); + +/* Any thread. Logs now. Then, on the UI thread and never inside this call, + * shows the dialog or accepts, and calls `cb` (if not NULL) once. NULL + * strings are empty. */ +void Warn(const char *id, const char *title, const char *message, bool can_cancel, Callback cb, void *param); + +} // namespace FallbackWarning diff --git a/frontend/utility/obs-fallback-warning.h b/frontend/utility/obs-fallback-warning.h new file mode 100644 index 0000000000..ebead7c449 --- /dev/null +++ b/frontend/utility/obs-fallback-warning.h @@ -0,0 +1,48 @@ +#pragma once + +/* C ABI of rust/obs-fallback-warning (src/ffi/mod.rs), linked into the + * frontend through rust/obs-frontend when OBS_FRONTEND_RUST is defined + * (obs-rust/obs-studio#2218). Call it from the UI thread. */ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* obs_fallback_warning_begin results. */ +#define OBS_FALLBACK_WARNING_DIALOG 0 +#define OBS_FALLBACK_WARNING_ACCEPT_NOW 1 + +/* How a dialog ended, for obs_fallback_warning_accepted. */ +#define OBS_FALLBACK_WARNING_END_COUNTDOWN 0 +#define OBS_FALLBACK_WARNING_END_ACCEPT 1 +#define OBS_FALLBACK_WARNING_END_CANCEL 2 +#define OBS_FALLBACK_WARNING_END_CLOSED 3 + +/* Whether warning `id` shows a dialog now: the first time per process while + * the main window is visible. Without a visible window it accepts now and is + * not remembered. NULL or "" is never remembered. */ +int obs_fallback_warning_begin(const char *id, bool window_visible); + +/* Whether the caller continues in the fallback mode after the dialog ended + * with `end` (OBS_FALLBACK_WARNING_END_*). Cancel and Close stop only a + * caller that can stop. */ +bool obs_fallback_warning_accepted(int end, bool can_cancel); + +/* The countdown progress after `elapsed_ms`, 0 to 100. */ +int obs_fallback_warning_progress(uint64_t elapsed_ms); + +/* How long the countdown runs before it accepts by itself. */ +uint64_t obs_fallback_warning_countdown_ms(void); + +/* The log line for warning `id`: the message, then the future-error + * sentence. NULL is empty. Free it with obs_fallback_warning_free. */ +char *obs_fallback_warning_log_line(const char *id, const char *message); + +void obs_fallback_warning_free(char *s); + +#ifdef __cplusplus +} +#endif diff --git a/frontend/widgets/OBSBasic.cpp.hpp b/frontend/widgets/OBSBasic.cpp.hpp index a9b0929963..68bf7c6e0f 100644 --- a/frontend/widgets/OBSBasic.cpp.hpp +++ b/frontend/widgets/OBSBasic.cpp.hpp @@ -1216,6 +1216,10 @@ void OBSBasic::OnFirstLoad() { OnEvent(OBS_FRONTEND_EVENT_FINISHED_LOADING); + /* Fallback warnings (#2218) waited for the main window; they run now. */ + FallbackWarning::SetMainWindow(this, {QTStr("FallbackWarning.AcceptAnyway"), QTStr("Cancel"), + QTStr("FallbackWarning.FutureError")}); + #ifdef WHATSNEW_ENABLED /* Attempt to load init screen if available */ if (cef) { @@ -1878,6 +1882,11 @@ void OBSBasic::closeWindow() #endif #endif + /* Answer every fallback warning (#2218), also those still queued, while + * its callers (sources) exist: the open dialog closes, the rest accept. */ + FallbackWarning::SetMainWindow(nullptr, {}); + QApplication::sendPostedEvents(nullptr); + OnEvent(OBS_FRONTEND_EVENT_SCRIPTING_SHUTDOWN); disableSaving++; diff --git a/local-gate.toml b/local-gate.toml index a19b976231..ce87bf0d25 100644 --- a/local-gate.toml +++ b/local-gate.toml @@ -64,7 +64,8 @@ tools = ["docker"] # Every workspace manifest stays an input: cargo reads them all. exclude = ["docs/**", "**/*.md", "build-aux/**", "libobs-d3d11/**", "libobs-metal/**", "libobs-winrt/**", "additional_install_files/**", "tools/**", "ci/**", ".github/**", ".claude/**", "rust/*/tests/**", "rust/*/benches/**", "rust/*/examples/**", - "rust/obs-c-oracle/**", "rust/obs-gpu-status/**", "rust/obs-gpu-status-frontend/**"] + "rust/obs-c-oracle/**", "rust/obs-fallback-warning/**", "rust/obs-gpu-status/**", + "rust/obs-frontend/**"] keep = ["rust/*/Cargo.toml"] # GATE-008: decided from THIS file as committed on the PR's base. Fails diff --git a/rust/README.md b/rust/README.md index fba33f0cbf..633f00c691 100644 --- a/rust/README.md +++ b/rust/README.md @@ -27,7 +27,8 @@ are in [docs/rust-port/naming.md](../docs/rust-port/naming.md#repository-layout- | `obs-audio-controls/` | Port of `libobs/obs-audio-controls.c.h` | | `obs-core/` | Ports of the units extracted from `libobs/obs.c.h`, `libobs/obs-module.c.h` and `libobs/obs-audio.c.h`: so far `libobs/obs-video-plan.c.h` (the video output plan), `libobs/obs-context-names.c.h` (the context names), `libobs/obs-source-load.c.h` (the source load migration and value rules), `libobs/obs-module-paths.c.h` (the module search paths), `libobs/obs-module-names.c.h` (module names and files), `libobs/obs-module-locale.c.h` (the module locale files), `libobs/obs-module-source-rules.c.h` (the source registration rules), `libobs/obs-module-type-rules.c.h` (the output, encoder and service registration rules), `libobs/obs-audio-mix.c.h` (the audio tick arithmetic); of `libobs/util/source-profiler.c.h` (per-source tick and render timing), which reads core state; of `libobs/obs-view-api.c.h` (views); and of `libobs/obs-video-copy-plan.c.h` (the output frame copy plan and scale effect choice, from `libobs/obs-video.c.h`); and of `libobs/obs-video-output-step.c.h` (the per-frame video output step decisions, from `libobs/obs-video.c.h`); and of `libobs/obs-canvas-draw.c.h` (the canvas texture draw and display clear decisions, from `libobs/obs.c.h` and `libobs/obs-display.c.h`) | | `obs-nvenc/`, `obs-nvenc-plugin/` | Port of the `plugins/obs-nvenc` CUDA/NVENC loader, and the staticlib that plugin links | -| `obs-gpu-status/`, `obs-gpu-status-frontend/` | GPU acceleration status (#846), and the staticlib the frontend links | +| `obs-gpu-status/`, `obs-frontend/` | GPU acceleration status (#846), and the staticlib the frontend links | +| `obs-fallback-warning/` | The shared warning for fallbacks that lower security (#2218): when a dialog shows, how it ends, the countdown and the log line | | `obs-c-oracle/` | Test-only: original C sources compiled with `oracle_` symbols for layout and differential tests | | `libobs-rust/` | The single staticlib linked into production hybrid `libobs` | | `obs-studio-rust/` | Standalone CLI that starts, stops and inspects OBS streaming over obs-websocket v5. Named after the product, with no release tags of its own (`docs/rust-port/naming.md`) | diff --git a/rust/obs-build/src/cli.rs b/rust/obs-build/src/cli.rs index f1c62b770c..51a57fdb89 100644 --- a/rust/obs-build/src/cli.rs +++ b/rust/obs-build/src/cli.rs @@ -255,7 +255,7 @@ where "-p", "libobs-rust", "-p", - "obs-gpu-status-frontend", + "obs-frontend", "--target", ]) .arg(&build.target) diff --git a/rust/obs-build/src/platform/mod.rs b/rust/obs-build/src/platform/mod.rs index a694e6e505..cbd6193c98 100644 --- a/rust/obs-build/src/platform/mod.rs +++ b/rust/obs-build/src/platform/mod.rs @@ -80,7 +80,7 @@ pub fn application_rust_archives( application_sources(target, true, true)?; Ok(crate::application::RustArchives { core: directory.join("liblibobs_rust.a"), - gpu_status: directory.join("libobs_gpu_status_frontend.a"), + gpu_status: directory.join("libobs_frontend.a"), nvenc: directory.join("libobs_nvenc_plugin.a"), }) } diff --git a/rust/obs-build/tests/libobs.rs b/rust/obs-build/tests/libobs.rs index 7f01d6caae..e81818c1fe 100644 --- a/rust/obs-build/tests/libobs.rs +++ b/rust/obs-build/tests/libobs.rs @@ -487,7 +487,7 @@ fn c_and_rust_twins_preserve_public_data_lifecycle_and_module_apis() { if enabled("OBS_BUILD_APP") { let gpu_archive = PathBuf::from( std::env::var_os("OBS_BUILD_GPU_ARCHIVE") - .expect("build obs-gpu-status-frontend in release mode first"), + .expect("build obs-frontend in release mode first"), ); let executable = frontend::build_application_with_options( &build, diff --git a/rust/obs-fallback-warning/Cargo.toml b/rust/obs-fallback-warning/Cargo.toml new file mode 100644 index 0000000000..9b2a0e30ec --- /dev/null +++ b/rust/obs-fallback-warning/Cargo.toml @@ -0,0 +1,17 @@ +[package] +autotests = false +name = "obs-fallback-warning" +version = "0.1.0" +description = "The shared warning for fallbacks that lower security (obs-rust/obs-studio#2218)" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[lints] +workspace = true + +# The tests run in obs-gpu-status's obs-tests-gpu (ci/test_binary_cap.py: one +# executable per category; both are the frontend's Rust). +[lib] +test = false diff --git a/rust/obs-fallback-warning/src/ffi/mod.rs b/rust/obs-fallback-warning/src/ffi/mod.rs new file mode 100644 index 0000000000..60d2b6643e --- /dev/null +++ b/rust/obs-fallback-warning/src/ffi/mod.rs @@ -0,0 +1,107 @@ +//! C ABI for the frontend (#2218), declared in +//! `frontend/utility/obs-fallback-warning.h`. It converts types and calls the +//! safe core; there is no logic here. The frontend calls it from its UI +//! thread; the session is one per process. + +use std::ffi::{CStr, CString, c_char, c_int}; +use std::sync::Mutex; + +use crate::{End, Session, Show}; + +/// [`Show::Dialog`] at the C boundary. +pub const OBS_FALLBACK_WARNING_DIALOG: c_int = 0; +/// [`Show::AcceptNow`] at the C boundary. +pub const OBS_FALLBACK_WARNING_ACCEPT_NOW: c_int = 1; + +/// [`End`] values at the C boundary; anything else is [`End::Closed`]. +pub const OBS_FALLBACK_WARNING_END_COUNTDOWN: c_int = 0; +pub const OBS_FALLBACK_WARNING_END_ACCEPT: c_int = 1; +pub const OBS_FALLBACK_WARNING_END_CANCEL: c_int = 2; +pub const OBS_FALLBACK_WARNING_END_CLOSED: c_int = 3; + +static SESSION: Mutex> = Mutex::new(None); + +/// A C string as `&str`; null is empty, invalid UTF-8 is replaced. +/// +/// # Safety +/// `s` is null or a NUL-terminated string. +unsafe fn text<'a>(s: *const c_char) -> std::borrow::Cow<'a, str> { + if s.is_null() { + return std::borrow::Cow::Borrowed(""); + } + // SAFETY: the caller passes a NUL-terminated string. + unsafe { CStr::from_ptr(s) }.to_string_lossy() +} + +/// [`Session::begin`] on the process's session. +/// +/// # Safety +/// `id` is null or a NUL-terminated string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_fallback_warning_begin( + id: *const c_char, + window_visible: bool, +) -> c_int { + // SAFETY: as the caller promises. + let id = unsafe { text(id) }; + let mut session = SESSION.lock().unwrap_or_else(|e| e.into_inner()); + match session + .get_or_insert_with(Session::new) + .begin(&id, window_visible) + { + Show::Dialog => OBS_FALLBACK_WARNING_DIALOG, + Show::AcceptNow => OBS_FALLBACK_WARNING_ACCEPT_NOW, + } +} + +/// [`crate::accepted`]. +#[unsafe(no_mangle)] +pub extern "C" fn obs_fallback_warning_accepted(end: c_int, can_cancel: bool) -> bool { + let end = match end { + OBS_FALLBACK_WARNING_END_COUNTDOWN => End::CountdownDone, + OBS_FALLBACK_WARNING_END_ACCEPT => End::AcceptClicked, + OBS_FALLBACK_WARNING_END_CANCEL => End::CancelClicked, + _ => End::Closed, + }; + crate::accepted(end, can_cancel) +} + +/// [`crate::progress_percent`]. +#[unsafe(no_mangle)] +pub extern "C" fn obs_fallback_warning_progress(elapsed_ms: u64) -> c_int { + c_int::from(crate::progress_percent(elapsed_ms)) +} + +/// [`crate::COUNTDOWN_MS`]. +#[unsafe(no_mangle)] +pub extern "C" fn obs_fallback_warning_countdown_ms() -> u64 { + crate::COUNTDOWN_MS +} + +/// [`crate::log_line`], as a string the caller frees with +/// [`obs_fallback_warning_free`]. Null `id` or `message` is empty. +/// +/// # Safety +/// `id` and `message` are null or NUL-terminated strings. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_fallback_warning_log_line( + id: *const c_char, + message: *const c_char, +) -> *mut c_char { + // SAFETY: as the caller promises. + let (id, message) = unsafe { (text(id), text(message)) }; + let line = crate::log_line(&id, &message).replace('\0', " "); + CString::new(line).map_or(std::ptr::null_mut(), CString::into_raw) +} + +/// Free a string from [`obs_fallback_warning_log_line`]. Null is ignored. +/// +/// # Safety +/// `s` is null or from [`obs_fallback_warning_log_line`], freed once. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_fallback_warning_free(s: *mut c_char) { + if !s.is_null() { + // SAFETY: from CString::into_raw in obs_fallback_warning_log_line. + drop(unsafe { CString::from_raw(s) }); + } +} diff --git a/rust/obs-fallback-warning/src/lib.rs b/rust/obs-fallback-warning/src/lib.rs new file mode 100644 index 0000000000..07f27dacdb --- /dev/null +++ b/rust/obs-fallback-warning/src/lib.rs @@ -0,0 +1,101 @@ +//! The shared warning for fallbacks that lower security +//! (obs-rust/obs-studio#2218). +//! +//! Some features fall back to a less safe mode when the safe one cannot +//! work, so that users do not lose them: the browser source without the +//! Chromium sandbox (#1092), RTMPS to RTMP (#2205). As decided on #1092, OBS +//! then logs the error (also on stderr), and warns the user with a countdown +//! that accepts the fallback by itself after 3 seconds. +//! +//! This crate is the pure part: whether a warning shows a dialog, how a +//! dialog ends, the countdown progress and the log line. The frontend draws +//! the dialog (Qt) and calls the C ABI in [`ffi`]. + +#![deny(unsafe_code)] + +use std::collections::HashSet; + +#[allow(unsafe_code)] +pub mod ffi; + +/// How long the warning counts down before it accepts by itself. +pub const COUNTDOWN_MS: u64 = 3_000; + +/// The sentence every fallback warning ends with. +pub const FUTURE_ERROR: &str = "This may become an error in a future version of OBS."; + +/// What the frontend does with a warning. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Show { + /// Show the dialog with the countdown. + Dialog, + /// No dialog: log only, and continue as with "Accept anyway". + AcceptNow, +} + +/// How a dialog ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum End { + /// The countdown reached its end. + CountdownDone, + /// The user clicked "Accept anyway". + AcceptClicked, + /// The user clicked "Cancel". + CancelClicked, + /// The user closed the dialog (window close, Escape). + Closed, +} + +/// The warnings that showed a dialog in this session. +#[derive(Debug, Default)] +pub struct Session { + shown: HashSet, +} + +impl Session { + /// A session in which no warning has shown a dialog. + pub fn new() -> Self { + Self::default() + } + + /// Whether warning `id` shows a dialog. With no visible main window + /// nobody sees a dialog, so it does not show one and is not remembered. + /// An `id` that already showed one in this session does not show it + /// again. An empty `id` is never remembered. + pub fn begin(&mut self, id: &str, window_visible: bool) -> Show { + if !window_visible { + return Show::AcceptNow; + } + if id.is_empty() || self.shown.insert(id.to_owned()) { + Show::Dialog + } else { + Show::AcceptNow + } + } +} + +/// Whether the caller continues in the fallback mode after the dialog +/// ended with `end`. Cancel and Close stop only a caller that can stop +/// (`can_cancel`); for the others there is nothing to stop. +pub fn accepted(end: End, can_cancel: bool) -> bool { + match end { + End::CountdownDone | End::AcceptClicked => true, + End::CancelClicked | End::Closed => !can_cancel, + } +} + +/// The countdown progress after `elapsed_ms`, from 0 to 100. +pub fn progress_percent(elapsed_ms: u64) -> u8 { + let percent = elapsed_ms.min(COUNTDOWN_MS) * 100 / COUNTDOWN_MS; + u8::try_from(percent).unwrap_or(100) +} + +/// The log line for warning `id`: the message, then [`FUTURE_ERROR`]. +/// The frontend logs it at error level, so it is on stderr once. +pub fn log_line(id: &str, message: &str) -> String { + if message.is_empty() { + format!("[fallback] {id}: {FUTURE_ERROR}") + } else { + format!("[fallback] {id}: {message} {FUTURE_ERROR}") + } +} diff --git a/rust/obs-fallback-warning/tests/fallback_warning/end.rs b/rust/obs-fallback-warning/tests/fallback_warning/end.rs new file mode 100644 index 0000000000..63a1beb00e --- /dev/null +++ b/rust/obs-fallback-warning/tests/fallback_warning/end.rs @@ -0,0 +1,31 @@ +//! How a dialog ends. + +use obs_fallback_warning::{End, accepted}; + +#[test] +fn the_countdown_accepts() { + assert!(accepted(End::CountdownDone, false)); + assert!(accepted(End::CountdownDone, true)); +} + +#[test] +fn accept_anyway_accepts() { + assert!(accepted(End::AcceptClicked, false)); + assert!(accepted(End::AcceptClicked, true)); +} + +#[test] +fn cancel_stops_a_caller_that_can_stop() { + assert!(!accepted(End::CancelClicked, true)); +} + +#[test] +fn closing_the_dialog_stops_a_caller_that_can_stop() { + assert!(!accepted(End::Closed, true)); +} + +#[test] +fn cancel_and_close_accept_when_there_is_nothing_to_stop() { + assert!(accepted(End::CancelClicked, false)); + assert!(accepted(End::Closed, false)); +} diff --git a/rust/obs-fallback-warning/tests/fallback_warning/ffi.rs b/rust/obs-fallback-warning/tests/fallback_warning/ffi.rs new file mode 100644 index 0000000000..b6127a0ee5 --- /dev/null +++ b/rust/obs-fallback-warning/tests/fallback_warning/ffi.rs @@ -0,0 +1,113 @@ +//! The C ABI the frontend calls (#2218). + +use std::ffi::{CStr, CString}; + +use obs_fallback_warning::ffi::{ + OBS_FALLBACK_WARNING_ACCEPT_NOW, OBS_FALLBACK_WARNING_DIALOG, OBS_FALLBACK_WARNING_END_ACCEPT, + OBS_FALLBACK_WARNING_END_CANCEL, OBS_FALLBACK_WARNING_END_CLOSED, + OBS_FALLBACK_WARNING_END_COUNTDOWN, obs_fallback_warning_accepted, obs_fallback_warning_begin, + obs_fallback_warning_countdown_ms, obs_fallback_warning_free, obs_fallback_warning_log_line, + obs_fallback_warning_progress, +}; + +/// The log line through the C ABI, freed. +fn line(id: Option<&CStr>, message: Option<&CStr>) -> String { + let ptr = |s: Option<&CStr>| s.map_or(std::ptr::null(), CStr::as_ptr); + // SAFETY: null or C strings. + let raw = unsafe { obs_fallback_warning_log_line(ptr(id), ptr(message)) }; + assert!(!raw.is_null()); + // SAFETY: NUL-terminated and still ours. + let text = unsafe { CStr::from_ptr(raw) }.to_str().unwrap().to_owned(); + // SAFETY: from obs_fallback_warning_log_line, freed once. + unsafe { obs_fallback_warning_free(raw) }; + text +} + +#[test] +fn begin_uses_one_session_per_process() { + // A unique id: the tests in this binary share the process session. + let id = CString::new("ffi-begin-once").unwrap(); + // SAFETY: a C string. + assert_eq!( + unsafe { obs_fallback_warning_begin(id.as_ptr(), true) }, + OBS_FALLBACK_WARNING_DIALOG + ); + // SAFETY: as above. + assert_eq!( + unsafe { obs_fallback_warning_begin(id.as_ptr(), true) }, + OBS_FALLBACK_WARNING_ACCEPT_NOW + ); +} + +#[test] +fn begin_without_a_window_accepts_now() { + let id = CString::new("ffi-begin-no-window").unwrap(); + // SAFETY: a C string. + assert_eq!( + unsafe { obs_fallback_warning_begin(id.as_ptr(), false) }, + OBS_FALLBACK_WARNING_ACCEPT_NOW + ); +} + +#[test] +fn a_null_id_is_an_empty_id() { + // SAFETY: null is allowed. + assert_eq!( + unsafe { obs_fallback_warning_begin(std::ptr::null(), true) }, + OBS_FALLBACK_WARNING_DIALOG + ); + // SAFETY: as above. + assert_eq!( + unsafe { obs_fallback_warning_begin(std::ptr::null(), true) }, + OBS_FALLBACK_WARNING_DIALOG + ); +} + +#[test] +fn accepted_maps_every_end() { + assert!(obs_fallback_warning_accepted( + OBS_FALLBACK_WARNING_END_COUNTDOWN, + true + )); + assert!(obs_fallback_warning_accepted( + OBS_FALLBACK_WARNING_END_ACCEPT, + true + )); + assert!(!obs_fallback_warning_accepted( + OBS_FALLBACK_WARNING_END_CANCEL, + true + )); + assert!(!obs_fallback_warning_accepted( + OBS_FALLBACK_WARNING_END_CLOSED, + true + )); + // An unknown value is a close. + assert!(!obs_fallback_warning_accepted(42, true)); + assert!(obs_fallback_warning_accepted(42, false)); +} + +#[test] +fn progress_and_countdown() { + assert_eq!(obs_fallback_warning_countdown_ms(), 3_000); + assert_eq!(obs_fallback_warning_progress(1_500), 50); + assert_eq!(obs_fallback_warning_progress(u64::MAX), 100); +} + +#[test] +fn log_line_through_the_c_abi() { + let id = CString::new("browser-sandbox").unwrap(); + let message = CString::new("Browser sources run without the sandbox.").unwrap(); + assert_eq!( + line(Some(&id), Some(&message)), + "[fallback] browser-sandbox: Browser sources run without the sandbox. This may become an error in a \ + future version of OBS." + ); +} + +#[test] +fn log_line_with_null_strings() { + assert_eq!( + line(None, None), + "[fallback] : This may become an error in a future version of OBS." + ); +} diff --git a/rust/obs-fallback-warning/tests/fallback_warning/log_line.rs b/rust/obs-fallback-warning/tests/fallback_warning/log_line.rs new file mode 100644 index 0000000000..a724ab7d66 --- /dev/null +++ b/rust/obs-fallback-warning/tests/fallback_warning/log_line.rs @@ -0,0 +1,31 @@ +//! The log line. + +use obs_fallback_warning::{FUTURE_ERROR, log_line}; + +#[test] +fn the_line_has_the_id_the_message_and_the_standard_sentence() { + assert_eq!( + log_line( + "browser-sandbox", + "Browser sources run without the sandbox." + ), + "[fallback] browser-sandbox: Browser sources run without the sandbox. This may become an error in a \ + future version of OBS." + ); +} + +#[test] +fn the_standard_sentence_is_the_decided_one() { + assert_eq!( + FUTURE_ERROR, + "This may become an error in a future version of OBS." + ); +} + +#[test] +fn an_empty_message_still_gives_the_standard_sentence() { + assert_eq!( + log_line("browser-sandbox", ""), + "[fallback] browser-sandbox: This may become an error in a future version of OBS." + ); +} diff --git a/rust/obs-fallback-warning/tests/fallback_warning/main.rs b/rust/obs-fallback-warning/tests/fallback_warning/main.rs new file mode 100644 index 0000000000..bfdbdfa285 --- /dev/null +++ b/rust/obs-fallback-warning/tests/fallback_warning/main.rs @@ -0,0 +1,7 @@ +//! obs-fallback-warning integration tests (#2218). + +mod end; +mod ffi; +mod log_line; +mod progress; +mod show; diff --git a/rust/obs-fallback-warning/tests/fallback_warning/progress.rs b/rust/obs-fallback-warning/tests/fallback_warning/progress.rs new file mode 100644 index 0000000000..30715afafe --- /dev/null +++ b/rust/obs-fallback-warning/tests/fallback_warning/progress.rs @@ -0,0 +1,23 @@ +//! The countdown progress. + +use obs_fallback_warning::{COUNTDOWN_MS, progress_percent}; + +#[test] +fn the_countdown_is_3_seconds() { + assert_eq!(COUNTDOWN_MS, 3_000); +} + +#[test] +fn progress_goes_from_0_to_100() { + assert_eq!(progress_percent(0), 0); + assert_eq!(progress_percent(30), 1); + assert_eq!(progress_percent(1_500), 50); + assert_eq!(progress_percent(2_999), 99); + assert_eq!(progress_percent(3_000), 100); +} + +#[test] +fn progress_stays_at_100_after_the_end() { + assert_eq!(progress_percent(3_001), 100); + assert_eq!(progress_percent(u64::MAX), 100); +} diff --git a/rust/obs-fallback-warning/tests/fallback_warning/show.rs b/rust/obs-fallback-warning/tests/fallback_warning/show.rs new file mode 100644 index 0000000000..bb45c09eac --- /dev/null +++ b/rust/obs-fallback-warning/tests/fallback_warning/show.rs @@ -0,0 +1,47 @@ +//! Whether a warning shows a dialog. + +use obs_fallback_warning::{Session, Show}; + +#[test] +fn first_warning_with_a_visible_window_shows_the_dialog() { + let mut session = Session::new(); + assert_eq!(session.begin("browser-sandbox", true), Show::Dialog); +} + +#[test] +fn the_same_warning_shows_the_dialog_once_per_session() { + let mut session = Session::new(); + assert_eq!(session.begin("browser-sandbox", true), Show::Dialog); + assert_eq!(session.begin("browser-sandbox", true), Show::AcceptNow); + assert_eq!(session.begin("browser-sandbox", true), Show::AcceptNow); +} + +#[test] +fn another_warning_still_shows_its_dialog() { + let mut session = Session::new(); + assert_eq!(session.begin("browser-sandbox", true), Show::Dialog); + assert_eq!(session.begin("rtmps-fallback", true), Show::Dialog); +} + +#[test] +fn no_visible_window_accepts_now_and_is_not_remembered() { + let mut session = Session::new(); + assert_eq!(session.begin("browser-sandbox", false), Show::AcceptNow); + // Nobody saw it, so the dialog shows when there is a window. + assert_eq!(session.begin("browser-sandbox", true), Show::Dialog); +} + +#[test] +fn an_empty_id_is_never_remembered() { + let mut session = Session::new(); + assert_eq!(session.begin("", true), Show::Dialog); + assert_eq!(session.begin("", true), Show::Dialog); +} + +#[test] +fn sessions_do_not_share_what_they_showed() { + let mut first = Session::new(); + let mut second = Session::new(); + assert_eq!(first.begin("browser-sandbox", true), Show::Dialog); + assert_eq!(second.begin("browser-sandbox", true), Show::Dialog); +} diff --git a/rust/obs-gpu-status-frontend/Cargo.toml b/rust/obs-frontend/Cargo.toml similarity index 61% rename from rust/obs-gpu-status-frontend/Cargo.toml rename to rust/obs-frontend/Cargo.toml index 96f8636cba..048eac81a3 100644 --- a/rust/obs-gpu-status-frontend/Cargo.toml +++ b/rust/obs-frontend/Cargo.toml @@ -1,8 +1,8 @@ [package] autotests = false -name = "obs-gpu-status-frontend" +name = "obs-frontend" version = "0.1.0" -description = "The staticlib the frontend links: obs-gpu-status's C ABI (obs-rust/obs-studio#846)" +description = "The frontend's staticlib: the C ABI of obs-gpu-status (#846) and obs-fallback-warning (#2218)" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -17,4 +17,5 @@ test = false doctest = false [dependencies] +obs-fallback-warning = { path = "../obs-fallback-warning" } obs-gpu-status = { path = "../obs-gpu-status" } diff --git a/rust/obs-frontend/src/lib.rs b/rust/obs-frontend/src/lib.rs new file mode 100644 index 0000000000..01265736ee --- /dev/null +++ b/rust/obs-frontend/src/lib.rs @@ -0,0 +1,13 @@ +//! The frontend's one staticlib (frontend/cmake/frontend-rust.cmake): the C +//! ABI of the frontend's Rust crates. One staticlib per binary, so later +//! frontend crates join this one (#2218). +//! +//! A separate crate so the crates stay plain rlibs: an rlib + staticlib crate +//! breaks its own test build (#592). + +#![forbid(unsafe_code)] + +/// The shared fallback warning (#2218): `frontend/utility/obs-fallback-warning.h`. +pub use obs_fallback_warning::ffi as fallback_warning; +/// GPU acceleration status (#846): `frontend/utility/obs-gpu-status.h`. +pub use obs_gpu_status::ffi as gpu_status; diff --git a/rust/obs-gpu-status-frontend/src/lib.rs b/rust/obs-gpu-status-frontend/src/lib.rs deleted file mode 100644 index f093b3af07..0000000000 --- a/rust/obs-gpu-status-frontend/src/lib.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! The staticlib the frontend links (frontend/cmake/feature-gpu-status.cmake): -//! obs-gpu-status's C ABI shim. -//! -//! A separate crate so obs-gpu-status stays a plain rlib: an rlib + staticlib -//! crate breaks its own test build (#592). - -#![forbid(unsafe_code)] - -pub use obs_gpu_status::ffi; diff --git a/rust/obs-gpu-status/Cargo.toml b/rust/obs-gpu-status/Cargo.toml index 73b277ab0d..1849d7fad1 100644 --- a/rust/obs-gpu-status/Cargo.toml +++ b/rust/obs-gpu-status/Cargo.toml @@ -14,6 +14,9 @@ workspace = true [dependencies] libloading = { workspace = true, default-features = true } +[dev-dependencies] +obs-fallback-warning = { path = "../obs-fallback-warning" } + [lib] test = false diff --git a/rust/obs-gpu-status/src/ffi/mod.rs b/rust/obs-gpu-status/src/ffi/mod.rs index 14c2122146..6a5cf35a7c 100644 --- a/rust/obs-gpu-status/src/ffi/mod.rs +++ b/rust/obs-gpu-status/src/ffi/mod.rs @@ -1,5 +1,5 @@ //! C ABI for the frontend (`frontend/utility/obs-gpu-status.h`). The -//! frontend links it through the staticlib rust/obs-gpu-status-frontend, +//! frontend links it through the staticlib rust/obs-frontend, //! like obs-nvenc links obs-nvenc-plugin, so libobs' exported symbol set //! does not change. diff --git a/rust/obs-gpu-status/tests/gpu_status/main.rs b/rust/obs-gpu-status/tests/gpu_status/main.rs index 4a642937de..f160272015 100644 --- a/rust/obs-gpu-status/tests/gpu_status/main.rs +++ b/rust/obs-gpu-status/tests/gpu_status/main.rs @@ -7,6 +7,9 @@ mod device_cache; mod dxgi; mod fdinfo; mod ffi; +// obs-fallback-warning (#2218): the frontend's other Rust, same category. +#[path = "../../../obs-fallback-warning/tests/fallback_warning/main.rs"] +mod fallback_warning; mod frame_window; mod frames; mod iokit; diff --git a/test/cmocka/test_fallback_warning_dialog.cpp b/test/cmocka/test_fallback_warning_dialog.cpp new file mode 100644 index 0000000000..3c3634f16f --- /dev/null +++ b/test/cmocka/test_fallback_warning_dialog.cpp @@ -0,0 +1,242 @@ +/* The shared fallback warning window (obs-rust/obs-studio#2218). A feature + * that falls back to a less safe mode (the browser source without its + * sandbox, #1092; RTMPS to RTMP, #2205) shows it: the caller's texts, a + * countdown that accepts by itself, "Accept anyway" and, when the caller can + * stop, "Cancel". The glue maps the end to the C ABI of + * rust/obs-fallback-warning, so every way out must report exactly one end, + * and the right one. + * + * Builds the real OBSFallbackWarning on Qt's offscreen platform, without the + * frontend (the window takes all texts from its caller), and drives it with + * Qt Test: the countdown, both buttons, Escape and the window close. */ + +#include +#include +#include +#include +#include +#include +#include + +#include "dialogs/OBSFallbackWarning.hpp" + +#include + +#include +#include +#include +#include +extern "C" { +#include +} + +using End = OBSFallbackWarning::End; + +static OBSFallbackWarning::Texts texts(bool can_cancel) +{ + OBSFallbackWarning::Texts t; + t.title = "Browser source without sandbox"; + t.message = "The Chromium sandbox could not start."; + t.futureError = "This may become an error in a future version of OBS."; + t.accept = "Accept anyway"; + t.cancel = can_cancel ? "Cancel" : QString(); + return t; +} + +struct Shown { + /* The context of the ended() connection: it goes with this struct, so a + * dialog that a later teardown closes cannot write into a finished test. */ + QObject context; + QPointer dialog; + std::vector ends; +}; + +static void show(Shown &s, bool can_cancel, qint64 countdown_ms) +{ + s.dialog = new OBSFallbackWarning(nullptr, texts(can_cancel), countdown_ms); + QObject::connect(s.dialog.data(), &OBSFallbackWarning::ended, &s.context, + [&s](End end) { s.ends.push_back(end); }); + s.dialog->show(); + QTest::qWait(20); +} + +/* Lets deferred deletes run, so a dialog that deletes itself on close is gone. */ +static void settle(int ms) +{ + QTest::qWait(ms); + QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); + QCoreApplication::processEvents(); +} + +static void check_one_end(Shown &s, End expected) +{ + assert_int_equal(s.ends.size(), 1); + assert_int_equal((int)s.ends[0], (int)expected); + /* The window closes and deletes itself: nobody holds it after the end. */ + assert_null(s.dialog.data()); +} + +static void click(Shown &s, const char *name) +{ + auto *button = s.dialog->findChild(name); + assert_non_null(button); + QTest::mouseClick(button, Qt::LeftButton); +} + +static int teardown(void **) +{ + QApplication::closeAllWindows(); + settle(0); + return 0; +} + +static void shows_the_callers_texts(void **) +{ + Shown s; + show(s, true, 60000); + + assert_true(s.dialog->windowTitle() == "Browser source without sandbox"); + auto *message = s.dialog->findChild("message"); + auto *future = s.dialog->findChild("futureError"); + auto *accept = s.dialog->findChild("acceptButton"); + auto *cancel = s.dialog->findChild("cancelButton"); + assert_non_null(message); + assert_non_null(future); + assert_non_null(accept); + assert_non_null(cancel); + assert_true(message->text() == "The Chromium sandbox could not start."); + assert_true(future->text() == "This may become an error in a future version of OBS."); + assert_true(accept->text() == "Accept anyway"); + assert_true(cancel->text() == "Cancel"); + assert_true(cancel->isVisible()); + /* Not modal: OBS keeps running while it counts down. */ + assert_false(s.dialog->isModal()); + assert_true(s.ends.empty()); +} + +static void no_cancel_button_without_cancel_text(void **) +{ + Shown s; + show(s, false, 60000); + + auto *accept = s.dialog->findChild("acceptButton"); + auto *cancel = s.dialog->findChild("cancelButton"); + assert_non_null(accept); + assert_true(accept->isVisible()); + assert_true(cancel == nullptr || !cancel->isVisible()); +} + +static void countdown_moves_the_progress(void **) +{ + Shown s; + show(s, true, 2000); + settle(400); + + auto *progress = s.dialog->findChild("progress"); + assert_non_null(progress); + assert_true(s.dialog->elapsedShown() > 0); + assert_true(s.dialog->elapsedShown() < 2000); + assert_int_equal(progress->maximum(), 2000); + assert_int_equal(progress->value(), s.dialog->elapsedShown()); + assert_true(s.ends.empty()); +} + +static void countdown_accepts_once(void **) +{ + Shown s; + show(s, true, 200); + settle(700); + + check_one_end(s, End::CountdownDone); +} + +static void accept_click_ends_once(void **) +{ + Shown s; + show(s, true, 300); + click(s, "acceptButton"); + /* Past the countdown: a stopped countdown must not end it again. */ + settle(700); + + check_one_end(s, End::AcceptClicked); +} + +static void cancel_click_ends_once(void **) +{ + Shown s; + show(s, true, 300); + click(s, "cancelButton"); + settle(700); + + check_one_end(s, End::CancelClicked); +} + +static void escape_closes(void **) +{ + Shown s; + show(s, true, 300); + QTest::keyClick(s.dialog.data(), Qt::Key_Escape); + settle(700); + + check_one_end(s, End::Closed); +} + +/* Another modal dialog opened over the warning (OBS queues the first-run + * wizard right after the main window has loaded): the warning is hidden or + * takes no input, so its countdown must not accept it unseen. It pauses + * while that dialog is open and goes on after it has closed. */ +static void countdown_pauses_while_another_dialog_is_modal(void **) +{ + Shown s; + show(s, true, 400); + settle(100); + + QDialog *modal = new QDialog(); + modal->setModal(true); + modal->show(); + settle(50); + assert_true(QApplication::activeModalWidget() == modal); + qint64 before = s.dialog->elapsedShown(); + settle(900); + assert_true(s.ends.empty()); + assert_non_null(s.dialog.data()); + /* One tick may still have counted when the modal opened. */ + assert_true(s.dialog->elapsedShown() <= before + 100); + + modal->close(); + delete modal; + settle(900); + check_one_end(s, End::CountdownDone); +} + +static void window_close_closes(void **) +{ + Shown s; + show(s, false, 300); + s.dialog->close(); + settle(700); + + check_one_end(s, End::Closed); +} + +int main(int argc, char **argv) +{ + qputenv("QT_QPA_PLATFORM", "offscreen"); + QApplication app(argc, argv); + + const struct CMUnitTest tests[] = { + cmocka_unit_test_teardown(shows_the_callers_texts, teardown), + cmocka_unit_test_teardown(no_cancel_button_without_cancel_text, teardown), + cmocka_unit_test_teardown(countdown_moves_the_progress, teardown), + cmocka_unit_test_teardown(countdown_accepts_once, teardown), + cmocka_unit_test_teardown(accept_click_ends_once, teardown), + cmocka_unit_test_teardown(cancel_click_ends_once, teardown), + cmocka_unit_test_teardown(escape_closes, teardown), + cmocka_unit_test_teardown(window_close_closes, teardown), + cmocka_unit_test_teardown(countdown_pauses_while_another_dialog_is_modal, teardown), + }; + if (argc > 1) { + cmocka_set_test_filter(argv[1]); + } + return cmocka_run_group_tests(tests, NULL, NULL); +} diff --git a/test/cmocka/test_fallback_warning_queue.cpp b/test/cmocka/test_fallback_warning_queue.cpp new file mode 100644 index 0000000000..d532c13041 --- /dev/null +++ b/test/cmocka/test_fallback_warning_queue.cpp @@ -0,0 +1,372 @@ +/* The shared fallback warning between its callers and the window + * (obs-rust/obs-studio#2218, frontend/utility/FallbackWarning). A caller on + * any thread warns; the glue logs at error level at once, then on the UI + * thread shows OBSFallbackWarning or accepts, as rust/obs-fallback-warning + * decides, and calls the caller back once. Warnings wait for the main window + * (a browser source falls back while the scene collection loads), and only + * one dialog shows at a time. + * + * Builds the glue and the window on Qt's offscreen platform with the + * frontend's real Rust staticlib (rust/obs-frontend) when it is built, and + * captures the log through its own blog(). Without the frontend's Rust (the + * C rollback build) the glue only logs and accepts, and that is checked + * instead. The Rust session and the glue are per process: every case uses + * its own ids and ends with the shutdown call, and the case before any main + * window runs first. */ + +#include +#include +#include +#include +#include + +#include "dialogs/OBSFallbackWarning.hpp" +#include "utility/FallbackWarning.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +extern "C" { +#include +} + +struct LogLine { + int level; + std::string text; +}; +static std::vector logged; + +extern "C" void blog(int log_level, const char *format, ...) +{ + char buf[1024]; + va_list args; + va_start(args, format); + vsnprintf(buf, sizeof(buf), format, args); + va_end(args); + logged.push_back({log_level, buf}); +} + +struct Answer { + bool accepted; + bool on_ui_thread; +}; + +struct Caller { + std::vector answers; +}; + +/* Every case's callers live until the next case: a failed assertion leaves + * its case early, and the teardown's shutdown call still answers them. */ +static std::list callers; + +static Caller &new_caller() +{ + return callers.emplace_back(); +} + +static void answer(void *param, bool accepted) +{ + auto *caller = static_cast(param); + caller->answers.push_back({accepted, QThread::currentThread() == qApp->thread()}); +} + +static FallbackWarning::Texts texts() +{ + FallbackWarning::Texts t; + t.accept = "Accept anyway"; + t.cancel = "Cancel"; + t.futureError = "This may become an error in a future version of OBS."; + return t; +} + +static QWidget *main_window; + +static void settle(int ms = 30) +{ + QTest::qWait(ms); + QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); + QCoreApplication::processEvents(); +} + +static std::vector dialogs() +{ + std::vector shown; + if (main_window) { + for (OBSFallbackWarning *d : main_window->findChildren()) { + if (d->isVisible()) { + shown.push_back(d); + } + } + } + return shown; +} + +static void click(OBSFallbackWarning *dialog, const char *name) +{ + auto *button = dialog->findChild(name); + assert_non_null(button); + QTest::mouseClick(button, Qt::LeftButton); + settle(); +} + +static int setup(void **) +{ + logged.clear(); + callers.clear(); + main_window = new QWidget(); + main_window->show(); + settle(); + return 0; +} + +static int teardown(void **) +{ + FallbackWarning::SetMainWindow(nullptr, texts()); + settle(); + delete main_window; + main_window = nullptr; + settle(); + return 0; +} + +/* Runs first: the glue has never seen a main window. The log line is + * written at once, at error level, on the caller's thread. Before the main + * window has loaded nothing shows and nobody is answered; then the warning + * runs, on the UI thread. */ +static void logs_at_once_then_waits_for_the_main_window(void **) +{ + Caller &caller = new_caller(); + std::thread t([&caller]() { + FallbackWarning::Warn("test.wait", "Wait title", "The sandbox could not start.", true, answer, &caller); + }); + t.join(); + + assert_int_equal(logged.size(), 1); + assert_int_equal(logged[0].level, LOG_ERROR); + assert_string_equal(logged[0].text.c_str(), "[fallback] test.wait: The sandbox could not start. " + "This may become an error in a future version of OBS."); + settle(); + assert_true(caller.answers.empty()); + assert_int_equal(dialogs().size(), 0); + + FallbackWarning::SetMainWindow(main_window, texts()); + settle(); +#ifdef OBS_FRONTEND_RUST + assert_int_equal(dialogs().size(), 1); + OBSFallbackWarning *dialog = dialogs()[0]; + assert_true(dialog->windowTitle() == "Wait title"); + assert_true(caller.answers.empty()); + click(dialog, "cancelButton"); + assert_int_equal(caller.answers.size(), 1); + assert_false(caller.answers[0].accepted); +#else + assert_int_equal(dialogs().size(), 0); + assert_int_equal(caller.answers.size(), 1); + assert_true(caller.answers[0].accepted); +#endif + assert_true(caller.answers[0].on_ui_thread); +} + +/* Never inside Warn(), even on the UI thread with the main window ready. */ +static void never_answers_inside_warn(void **) +{ + FallbackWarning::SetMainWindow(main_window, texts()); + Caller &caller = new_caller(); + FallbackWarning::Warn("test.inside", "Title", "Message", false, answer, &caller); + assert_true(caller.answers.empty()); + settle(); +#ifdef OBS_FRONTEND_RUST + assert_int_equal(dialogs().size(), 1); + click(dialogs()[0], "acceptButton"); +#endif + assert_int_equal(caller.answers.size(), 1); + assert_true(caller.answers[0].accepted); + assert_true(caller.answers[0].on_ui_thread); +} + +/* A caller that cannot stop gets no Cancel button. */ +static void no_cancel_for_a_caller_that_cannot_stop(void **) +{ + FallbackWarning::SetMainWindow(main_window, texts()); + Caller &caller = new_caller(); + FallbackWarning::Warn("test.nocancel", "Title", "Message", false, answer, &caller); + settle(); +#ifdef OBS_FRONTEND_RUST + assert_int_equal(dialogs().size(), 1); + auto *cancel = dialogs()[0]->findChild("cancelButton"); + assert_true(cancel == nullptr || !cancel->isVisible()); + click(dialogs()[0], "acceptButton"); +#endif + assert_int_equal(caller.answers.size(), 1); + assert_true(caller.answers[0].accepted); +} + +/* One dialog at a time: the second waits for the first. */ +static void one_dialog_at_a_time(void **) +{ + FallbackWarning::SetMainWindow(main_window, texts()); + Caller &first = new_caller(); + Caller &second = new_caller(); + FallbackWarning::Warn("test.first", "First", "Message", true, answer, &first); + FallbackWarning::Warn("test.second", "Second", "Message", true, answer, &second); + settle(); +#ifdef OBS_FRONTEND_RUST + assert_int_equal(dialogs().size(), 1); + assert_true(dialogs()[0]->windowTitle() == "First"); + click(dialogs()[0], "acceptButton"); + assert_int_equal(first.answers.size(), 1); + assert_true(second.answers.empty()); + + assert_int_equal(dialogs().size(), 1); + assert_true(dialogs()[0]->windowTitle() == "Second"); + click(dialogs()[0], "cancelButton"); + assert_int_equal(second.answers.size(), 1); + assert_false(second.answers[0].accepted); +#else + assert_int_equal(dialogs().size(), 0); + assert_int_equal(first.answers.size(), 1); + assert_int_equal(second.answers.size(), 1); +#endif + assert_true(first.answers[0].accepted); +} + +/* The same id shows its dialog once per session; again, it accepts at once + * (and still logs). */ +static void same_id_shows_once(void **) +{ + FallbackWarning::SetMainWindow(main_window, texts()); + Caller &first = new_caller(); + Caller &again = new_caller(); + FallbackWarning::Warn("test.once", "Once", "Message", true, answer, &first); + settle(); +#ifdef OBS_FRONTEND_RUST + assert_int_equal(dialogs().size(), 1); + click(dialogs()[0], "acceptButton"); +#endif + FallbackWarning::Warn("test.once", "Once", "Message", true, answer, &again); + settle(); + assert_int_equal(dialogs().size(), 0); + assert_int_equal(again.answers.size(), 1); + assert_true(again.answers[0].accepted); + assert_int_equal(logged.size(), 2); +} + +/* Nobody sees a dialog on a hidden main window: it accepts at once. */ +static void hidden_main_window_accepts(void **) +{ + main_window->hide(); + FallbackWarning::SetMainWindow(main_window, texts()); + Caller &caller = new_caller(); + FallbackWarning::Warn("test.hidden", "Title", "Message", true, answer, &caller); + settle(); + assert_int_equal(main_window->findChildren().size(), 0); + assert_int_equal(caller.answers.size(), 1); + assert_true(caller.answers[0].accepted); +} + +/* Another modal dialog is open (the first-run wizard opens right after the + * main window has loaded): a warning would show behind it or take no input, + * and accept unseen. It waits until that dialog has closed, and is not yet + * counted as shown. */ +static void waits_while_another_dialog_is_modal(void **) +{ + FallbackWarning::SetMainWindow(main_window, texts()); + QDialog *modal = new QDialog(main_window); + modal->setModal(true); + modal->show(); + settle(); + assert_true(QApplication::activeModalWidget() == modal); + + Caller &caller = new_caller(); + FallbackWarning::Warn("test.modal", "Behind a modal", "Message", true, answer, &caller); + settle(400); +#ifdef OBS_FRONTEND_RUST + assert_int_equal(dialogs().size(), 0); + assert_true(caller.answers.empty()); + + modal->close(); + settle(600); + assert_int_equal(dialogs().size(), 1); + assert_true(dialogs()[0]->windowTitle() == "Behind a modal"); + click(dialogs()[0], "cancelButton"); + assert_int_equal(caller.answers.size(), 1); + assert_false(caller.answers[0].accepted); +#else + /* No dialog to hide: it accepts. */ + assert_int_equal(caller.answers.size(), 1); + assert_true(caller.answers[0].accepted); + modal->close(); +#endif + delete modal; +} + +/* At shutdown the open dialog closes (Close: a caller that can stop stops), + * and queued warnings accept without a dialog. */ +static void shutdown_answers_everyone(void **) +{ + FallbackWarning::SetMainWindow(main_window, texts()); + Caller &open = new_caller(); + Caller &queued = new_caller(); + FallbackWarning::Warn("test.open", "Open", "Message", true, answer, &open); + FallbackWarning::Warn("test.queued", "Queued", "Message", true, answer, &queued); + settle(); + + FallbackWarning::SetMainWindow(nullptr, texts()); + settle(); + assert_int_equal(dialogs().size(), 0); + assert_int_equal(open.answers.size(), 1); + assert_int_equal(queued.answers.size(), 1); +#ifdef OBS_FRONTEND_RUST + assert_false(open.answers[0].accepted); +#else + assert_true(open.answers[0].accepted); +#endif + assert_true(queued.answers[0].accepted); +} + +/* No callback and NULL strings are allowed. */ +static void null_callback_and_strings(void **) +{ + FallbackWarning::SetMainWindow(main_window, texts()); + FallbackWarning::Warn("test.null", nullptr, nullptr, false, nullptr, nullptr); + settle(); +#ifdef OBS_FRONTEND_RUST + assert_int_equal(dialogs().size(), 1); + click(dialogs()[0], "acceptButton"); +#endif + assert_int_equal(logged.size(), 1); + assert_string_equal(logged[0].text.c_str(), + "[fallback] test.null: This may become an error in a future version of OBS."); +} + +int main(int argc, char **argv) +{ + qputenv("QT_QPA_PLATFORM", "offscreen"); + QApplication app(argc, argv); + + const struct CMUnitTest tests[] = { + /* First: before any main window. */ + cmocka_unit_test_setup_teardown(logs_at_once_then_waits_for_the_main_window, setup, teardown), + cmocka_unit_test_setup_teardown(never_answers_inside_warn, setup, teardown), + cmocka_unit_test_setup_teardown(no_cancel_for_a_caller_that_cannot_stop, setup, teardown), + cmocka_unit_test_setup_teardown(one_dialog_at_a_time, setup, teardown), + cmocka_unit_test_setup_teardown(same_id_shows_once, setup, teardown), + cmocka_unit_test_setup_teardown(hidden_main_window_accepts, setup, teardown), + cmocka_unit_test_setup_teardown(waits_while_another_dialog_is_modal, setup, teardown), + cmocka_unit_test_setup_teardown(shutdown_answers_everyone, setup, teardown), + cmocka_unit_test_setup_teardown(null_callback_and_strings, setup, teardown), + }; + if (argc > 1) { + cmocka_set_test_filter(argv[1]); + } + return cmocka_run_group_tests(tests, NULL, NULL); +} diff --git a/test/cmocka/test_frontend_warn_fallback.c b/test/cmocka/test_frontend_warn_fallback.c new file mode 100644 index 0000000000..25486469a2 --- /dev/null +++ b/test/cmocka/test_frontend_warn_fallback.c @@ -0,0 +1,89 @@ +/* obs_frontend_warn_fallback() without a frontend (obs-rust/obs-studio#2218). + * A plugin that falls back to a less safe mode calls it; in a host with no + * OBS frontend (no callbacks set) there is nobody to warn, so the API + * library logs the warning at error level and accepts at once, inside the + * call, without the "no callbacks" error every other call logs. The line is + * the one rust/obs-fallback-warning logs in the frontend. */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +static int log_count; +static int log_level; +static char log_line[512]; + +static void capture_log(int level, const char *format, va_list args, void *param) +{ + (void)param; + log_count++; + log_level = level; + vsnprintf(log_line, sizeof(log_line), format, args); +} + +struct answers { + int count; + bool accepted; +}; + +static void answer(void *param, bool accepted) +{ + struct answers *a = param; + a->count++; + a->accepted = accepted; +} + +static int setup(void **state) +{ + (void)state; + log_count = 0; + log_line[0] = 0; + base_set_log_handler(capture_log, NULL); + return 0; +} + +static int teardown(void **state) +{ + (void)state; + base_set_log_handler(NULL, NULL); + return 0; +} + +static void logs_and_accepts_at_once(void **state) +{ + (void)state; + struct answers a = {0}; + obs_frontend_warn_fallback("browser.sandbox", "Title", "The sandbox could not start.", true, answer, &a); + + assert_int_equal(a.count, 1); + assert_true(a.accepted); + assert_int_equal(log_count, 1); + assert_int_equal(log_level, LOG_ERROR); + assert_string_equal(log_line, "[fallback] browser.sandbox: The sandbox could not start. " + "This may become an error in a future version of OBS."); +} + +static void null_callback_and_strings(void **state) +{ + (void)state; + obs_frontend_warn_fallback(NULL, NULL, NULL, false, NULL, NULL); + + assert_int_equal(log_count, 1); + assert_string_equal(log_line, "[fallback] : This may become an error in a future version of OBS."); +} + +int main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test_setup_teardown(logs_and_accepts_at_once, setup, teardown), + cmocka_unit_test_setup_teardown(null_callback_and_strings, setup, teardown), + }; + return cmocka_run_group_tests(tests, NULL, NULL); +} diff --git a/test/cmocka/tests.d/test_fallback_warning_dialog.cmake b/test/cmocka/tests.d/test_fallback_warning_dialog.cmake new file mode 100644 index 0000000000..df2b8b2236 --- /dev/null +++ b/test/cmocka/tests.d/test_fallback_warning_dialog.cmake @@ -0,0 +1,30 @@ +# Fallback warning window (obs-rust/obs-studio#2218): the countdown, both +# buttons, Escape and the window close each end the dialog exactly once, with +# the right end value of the C ABI. Builds the real +# OBSFallbackWarning (its own unity group, frontend/build/) without the +# frontend and runs it on Qt's offscreen platform, so it needs Qt Widgets and +# Qt Test but no display. +if(OS_LINUX) + find_package(Qt6 QUIET COMPONENTS Widgets Test) + if(TARGET Qt6::Widgets AND TARGET Qt6::Test) + set(_fw_dir "${CMAKE_SOURCE_DIR}/frontend") + add_executable( + test_fallback_warning_dialog + test_fallback_warning_dialog.cpp + "${_fw_dir}/build/frontend.dialogs-obsfallbackwarning+.hpp.cpp" + "${_fw_dir}/dialogs/OBSFallbackWarning.hpp" + ) + set_target_properties(test_fallback_warning_dialog PROPERTIES AUTOMOC ON) + target_include_directories( + test_fallback_warning_dialog + PRIVATE ${CMOCKA_INCLUDE_DIR} "${_fw_dir}" "${CMAKE_SOURCE_DIR}" + ) + target_link_libraries(test_fallback_warning_dialog PRIVATE Qt6::Widgets Qt6::Test ${CMOCKA_LIBRARIES}) + add_dependencies(cmocka-tests test_fallback_warning_dialog) + obs_test_sanitize(test_fallback_warning_dialog address,undefined) + add_test(test_fallback_warning_dialog ${CMAKE_CURRENT_BINARY_DIR}/test_fallback_warning_dialog) + # Qt and fontconfig keep allocations until exit; only memory errors count. + set_tests_properties(test_fallback_warning_dialog PROPERTIES ENVIRONMENT "ASAN_OPTIONS=detect_leaks=0") + unset(_fw_dir) + endif() +endif() diff --git a/test/cmocka/tests.d/test_fallback_warning_queue.cmake b/test/cmocka/tests.d/test_fallback_warning_queue.cmake new file mode 100644 index 0000000000..92057cc875 --- /dev/null +++ b/test/cmocka/tests.d/test_fallback_warning_queue.cmake @@ -0,0 +1,46 @@ +# Fallback warning glue (obs-rust/obs-studio#2218): frontend/utility/ +# FallbackWarning logs at once from any thread, waits for the main window, +# shows one OBSFallbackWarning at a time and answers each caller once on the +# UI thread. Builds the glue and the window (their own unity groups) without +# the frontend, on Qt's offscreen platform, with the frontend's Rust +# staticlib when frontend-rust.cmake builds it (this directory is configured +# before the frontend, so it is a generator expression). Without it the +# glue's C rollback path is tested. blog() is the test's own, so libobs is +# not linked. +if(OS_LINUX) + find_package(Qt6 QUIET COMPONENTS Widgets Test) + if(TARGET Qt6::Widgets AND TARGET Qt6::Test) + set(_fw_dir "${CMAKE_SOURCE_DIR}/frontend") + add_executable( + test_fallback_warning_queue + test_fallback_warning_queue.cpp + "${_fw_dir}/build/frontend.dialogs-obsfallbackwarning+.hpp.cpp" + "${_fw_dir}/build/frontend.fallback-warning+.hpp.cpp" + "${_fw_dir}/dialogs/OBSFallbackWarning.hpp" + "${_fw_dir}/utility/FallbackWarning.hpp" + ) + set_target_properties(test_fallback_warning_queue PROPERTIES AUTOMOC ON) + target_include_directories( + test_fallback_warning_queue + PRIVATE + ${CMOCKA_INCLUDE_DIR} + "${_fw_dir}" + "${CMAKE_SOURCE_DIR}" + $ + ) + target_compile_definitions( + test_fallback_warning_queue + PRIVATE $<$:OBS_FRONTEND_RUST> + ) + target_link_libraries( + test_fallback_warning_queue + PRIVATE $ Qt6::Widgets Qt6::Test ${CMOCKA_LIBRARIES} + ) + add_dependencies(cmocka-tests test_fallback_warning_queue) + obs_test_sanitize(test_fallback_warning_queue address,undefined) + add_test(test_fallback_warning_queue ${CMAKE_CURRENT_BINARY_DIR}/test_fallback_warning_queue) + # Qt and fontconfig keep allocations until exit; only memory errors count. + set_tests_properties(test_fallback_warning_queue PROPERTIES ENVIRONMENT "ASAN_OPTIONS=detect_leaks=0") + unset(_fw_dir) + endif() +endif() diff --git a/test/cmocka/tests.d/test_frontend_warn_fallback.cmake b/test/cmocka/tests.d/test_frontend_warn_fallback.cmake new file mode 100644 index 0000000000..708ce035a3 --- /dev/null +++ b/test/cmocka/tests.d/test_frontend_warn_fallback.cmake @@ -0,0 +1,11 @@ +# obs_frontend_warn_fallback() without a frontend (obs-rust/obs-studio#2218): +# the API library logs at error level and accepts at once. test/cmocka is +# configured before frontend/, so OBS::frontend-api resolves when the build +# is generated; Linux, and skipped when the frontend is not built. +if(OS_LINUX AND ENABLE_FRONTEND) + add_executable(test_frontend_warn_fallback test_frontend_warn_fallback.c) + target_include_directories(test_frontend_warn_fallback PRIVATE ${CMOCKA_INCLUDE_DIR}) + target_link_libraries(test_frontend_warn_fallback PRIVATE OBS::libobs OBS::frontend-api ${CMOCKA_LIBRARIES}) + add_dependencies(cmocka-tests test_frontend_warn_fallback) + add_test(test_frontend_warn_fallback ${CMAKE_CURRENT_BINARY_DIR}/test_frontend_warn_fallback) +endif()