feat(qt): renderer tier, GPU selection and a real shader build

Closes PARITY-DEBT #83 and #104, and unblocks the immersive shader scenes.

THE TIER. Slint resolves one bool, use_gpu_renderer, and hands it to three
features: the shader scenes, the dynamic background and half of reduce-motion.
This port had none of it, which is why the scenes could not be offered — off
the GPU tier they render black and nothing could tell. QbzShell now carries
rendererApi, gpuTier, shaderScenesAvailable and appBackgroundAvailable, all
written from one latch. Only QML can source it: QRhi picks the backend after
QGuiApplication, so the pre-init code knows only what it asked for.

Per-item GraphicsInfo.api stays where it is. "Can this item draw?" and "should
this feature be offered?" are different questions, and routing the first
through Rust would make every cover wait on a round trip.

SHADERS ARE BUILT NOW. build.rs bakes every .frag/.vert to .qsb with ten
variants and the batching rewrite. They used to be baked by hand and committed
carrying no GLES variants at all, so any GLES context failed them with "No
GLSL shader code found" — which is exactly how the NPB Large visualiser went
blank while this branch was being tested. Adding a scene is now dropping a
.frag in the folder.

GPU SELECTION enumerates real devices through Vulkan and lists them by model,
never by class: a machine with no discrete GPU can no longer be told to use
one. Legacy class keys still resolve, but only against hardware that exists.
Picking a non-default device implies the Vulkan backend, which the row's own
description states in all eight locales — measured as the only route that
keeps a working context: DRI_PRIME lands on llvmpipe and the NVIDIA PRIME
pair lands on OpenGL ES.

The renderer row gains the auto-revert sentinel and the frame-liveness
watchdog it shipped without. The sentinel arms only for a choice that truly
forces a backend, and liveness means frames rendered over a window, not merely
a window that opened.

Also fixes the kiosk toggle overwriting the tier half of reduce-motion.

Verified by 312 tests, both QML audits, the offscreen smoke, and a probe
against the real hybrid GPU: both devices enumerate by name and the stored
preference applies.

cc
This commit is contained in:
vicrodh committed 2026-08-11 13:59:24 -06:00
1 parent 8ba9483462
commit 21e941bdf6
21 files changed
+1031 -30

No files matched your search

+9
View File
@@ -59,6 +59,15 @@ qbz-audio = { path = "../qbz-audio" }
# the Slint adapter and pulls in qbz-ui + slint, the ~1.6 M-line generated
# module this whole track exists to stay out of.
qbz-dac-wizard-core = { path = "../qbz-dac-wizard-core" }
# Vulkan enumeration for the Preferred-GPU row — real adapter NAMES, MODELS and
# types, in the exact order `QT_VK_PHYSICAL_DEVICE_INDEX` counts them (both are
# `vkEnumeratePhysicalDevices`). This is the Qt analogue of what the reference
# does with `wgpu::Instance::enumerate_adapters`.
#
# `ash` is a thin FFI binding that dlopens libvulkan at RUNTIME: no Vulkan SDK
# at build time, and a box without libvulkan simply enumerates nothing. It was
# already in the workspace lock (wgpu pulls it), so it costs no new compile.
ash = "0.38"
qbz-qobuz = { path = "../qbz-qobuz" }
qbz-models = { path = "../qbz-models" }
qbz-cache = { path = "../qbz-cache" }
+95
View File
@@ -16,7 +16,102 @@ fn collect_qrc_files(dir: &Path, out: &mut Vec<String>) {
}
}
/// Every RHI variant a Qt Quick shader should carry.
///
/// `qsb --qt6` is only `100 es,120,150` + HLSL 50 + MSL 12. This is that plus
/// the modern GLES levels and desktop 440, because the runtime asks for the
/// HIGHEST it can use and falls through: on a GLES 3.2 context Qt tries
/// 320, 310, 300, 100 in that order and gives up if none is present.
const SHADER_GLSL: &str = "100 es,300 es,310 es,320 es,120,150,440";
const SHADER_HLSL: &str = "50";
const SHADER_MSL: &str = "12";
/// Locate Qt's `qsb`. PATH first, then the usual install layouts (Linux
/// distro, Homebrew on the Mac mini).
fn find_qsb() -> Option<std::path::PathBuf> {
if let Ok(explicit) = std::env::var("QSB") {
let p = std::path::PathBuf::from(explicit);
if p.is_file() {
return Some(p);
}
}
if let Ok(path) = std::env::var("PATH") {
for dir in std::env::split_paths(&path) {
let p = dir.join("qsb");
if p.is_file() {
return Some(p);
}
}
}
for candidate in [
"/usr/lib64/qt6/bin/qsb",
"/usr/lib/qt6/bin/qsb",
"/usr/lib/x86_64-linux-gnu/qt6/bin/qsb",
"/opt/homebrew/opt/qt/bin/qsb",
"/usr/local/opt/qt/bin/qsb",
] {
let p = std::path::PathBuf::from(candidate);
if p.is_file() {
return Some(p);
}
}
None
}
/// Compile every `.frag` / `.vert` under `qml/assets/shaders/` to a `.qsb`
/// beside it, with the full variant set.
///
/// WHY THIS EXISTS. The `.qsb` files used to be baked BY HAND and committed,
/// with no record of the command. They carried SPIR-V + GLSL 440 + MSL and
/// **no GLES variants at all**, so the moment the app got a GLES context every
/// one of them failed with "No GLSL shader code found (versions tried: 320,
/// 310, 300, 100)" and the visualiser went blank (2026-08-11). A hand-baked
/// artifact cannot be audited and will be copied by the next person who adds a
/// shader — so the bake is part of the build now.
///
/// Missing `qsb` is a WARNING, not an error: the committed `.qsb` are still
/// in the tree and still load, so a box without Qt's shader tools can build.
fn build_shaders() {
let dir = Path::new("qml/assets/shaders");
if !dir.is_dir() {
return;
}
let Some(qsb) = find_qsb() else {
println!(
"cargo:warning=qsb not found — shaders keep their committed .qsb. \
Set QSB=/path/to/qsb to re-bake them."
);
return;
};
for entry in std::fs::read_dir(dir).expect("read shaders dir").flatten() {
let src = entry.path();
let ext = src.extension().and_then(|e| e.to_str()).unwrap_or("");
if !matches!(ext, "frag" | "vert") {
continue;
}
println!("cargo:rerun-if-changed={}", src.display());
let out = src.with_extension(format!("{ext}.qsb"));
let mut cmd = std::process::Command::new(&qsb);
cmd.args(["--glsl", SHADER_GLSL, "--hlsl", SHADER_HLSL, "--msl", SHADER_MSL]);
// Vertex shaders used by Qt Quick need the batching rewrite, or the
// scene graph cannot batch the item and falls back per-node.
if ext == "vert" {
cmd.arg("-b");
}
cmd.arg("-o").arg(&out).arg(&src);
match cmd.status() {
Ok(s) if s.success() => {}
Ok(s) => panic!("qsb failed ({s}) on {}", src.display()),
Err(e) => panic!("could not run qsb on {}: {e}", src.display()),
}
}
}
fn main() {
// Bake the shaders BEFORE the qrc sweep below collects qml/assets, so a
// freshly compiled .qsb is the one that gets embedded.
build_shaders();
// The WHOLE asset tree, recursively. This used to name the root-level
// files by hand with only icons/ and fonts/ collected, so dropping a new
// asset next to hi-res.svg compiled fine and then failed at runtime with
+59
View File
@@ -182,6 +182,65 @@ ApplicationWindow {
// Phase 23: every domain singleton boots (registers its Qt-thread
// hop; QbzSession.boot additionally fires the app boot sequence).
// ── The renderer probe ────────────────────────────────────────────────
// The ONLY place that answers "what is actually drawing". QRhi decides it
// when the scene graph initialises, so `main::apply_renderer_preference()`
// — which runs before QGuiApplication — knows only what we ASKED for; a
// driver that refuses the request lands us somewhere else entirely.
//
// The enum is mapped to a NAME here, so Rust never depends on
// GraphicsInfo's numeric values (a Qt implementation detail). Rust ignores
// "unknown", the value reported before the graph resolves, so the report
// fires again for free once it does.
//
// This is the feature gate (shader scenes / dynamic background /
// reduce-motion), NOT the per-item drawing check: items that need to pick
// a draw path keep reading their own `GraphicsInfo.api`, which is per
// window and needs no round trip. See src/renderer_qt.rs.
Item {
id: rendererProbe
width: 0
height: 0
readonly property int api: GraphicsInfo.api
function report() {
var name = "unknown"
switch (rendererProbe.api) {
case GraphicsInfo.Software: name = "software"; break
case GraphicsInfo.OpenGL: name = "opengl"; break
case GraphicsInfo.Direct3D11: name = "d3d11"; break
case GraphicsInfo.Direct3D12: name = "d3d12"; break
case GraphicsInfo.Vulkan: name = "vulkan"; break
case GraphicsInfo.Metal: name = "metal"; break
case GraphicsInfo.Null: name = "null"; break
}
QbzShell.reportRendererApi(name)
}
onApiChanged: report()
Component.onCompleted: report()
}
// ── The frame-liveness watchdog ───────────────────────────────────────
// Disarms the startup sentinel that `apply_renderer_preference()` armed
// for a forced renderer. The proof it waits for is FRAMES, not a window: a
// backend can create a window and then never present, which from the
// outside is indistinguishable from a healthy start until the user is
// looking at a frozen pane — and that is exactly the state the sentinel
// must NOT accept as success.
//
// 10 s rather than the first swap: a renderer that dies two seconds in
// would otherwise have already been declared healthy, and the next launch
// would keep re-forcing it. The reference waits for real user input with a
// 30 s no-touch fallback (`disarm_renderer_sentinel_on_liveness`); frames
// are the same idea with a signal Qt gives us directly.
property int _framesSwapped: 0
onFrameSwapped: window._framesSwapped++
Timer {
interval: 10000
repeat: false
running: true
onTriggered: QbzShell.reportFrameLiveness(window._framesSwapped)
}
Component.onCompleted: {
// DIAGNOSTIC (macOS chrome): the Rust side reports what AppKit ended
// up with; this reports what QML asked for. Together they pin the
Binary file not shown.
@@ -534,9 +534,20 @@ Column {
}
}
SettingRow {
visible: QbzShell.isLinux
// `gpuSelectable`, not `isLinux`: same answer today, but it comes from
// the SAME place as the code that applies the choice
// (`renderer_qt::gpu_selectable`), so the row cannot outlive the
// capability. macOS is false because QRhi hardcodes
// `MTLCreateSystemDefaultDevice` — there is no env and no API, so the
// row hides rather than lying (PARITY-DEBT #83 scoping).
visible: root.doc.gpuSelectable === true
label: QbzSession.tr("Preferred GPU", QbzSession.trRev)
description: QbzSession.tr("Which GPU renders the app. On a hybrid laptop, picking the discrete GPU moves the dynamic-background load off the integrated one (cooler, but more power). Auto is recommended (requires restart)", QbzSession.trRev)
// The description states the Vulkan coupling out loud: picking a
// non-default GPU changes the RENDERER too, and a setting that quietly
// moves another setting is exactly the kind of surprise this row must
// not spring. Vulkan is the only Qt backend that can select a device —
// measured, see src/renderer_qt.rs.
description: QbzSession.tr("Which GPU renders the app. Only the GPUs actually present are listed. Choosing one other than the default also switches the renderer to Vulkan — the only backend Qt can select a GPU on (requires restart)", QbzSession.trRev)
QbzSelect {
menuWidth: 260
options: root.doc.gpuPowers || []
+8 -3
View File
@@ -125,11 +125,16 @@ pub fn toggle() {
log::info!("[qbz-qt] profile -> {value}");
// Forced reduce-motion follows the profile (`main.rs:8596-8598`): the
// reference computes `kiosk_profile || !use_gpu_renderer`, and only the
// kiosk half has an honest source in this port (shell_bridge.rs:551-566).
// reference computes `kiosk_profile || !use_gpu_renderer`. BOTH halves are
// honest now (2026-08-11) — `renderer_qt` latches the tier from the QML
// probe — so this composes them instead of assigning the kiosk half alone.
// It used to write `to_kiosk` bare, which meant leaving kiosk on a
// software-tier box turned reduce-motion OFF and handed that box full-rate
// animations, the exact thing the tier half exists to prevent.
shell_bridge::ui(move |mut b| {
b.as_mut().set_kiosk_profile(to_kiosk);
b.as_mut().set_reduce_motion(to_kiosk);
b.as_mut()
.set_reduce_motion(crate::renderer_qt::reduce_motion(to_kiosk));
});
session_bridge::ui(move |mut b| {
b.as_mut()
+59 -8
View File
@@ -114,6 +114,11 @@ mod folders_qt;
// user pastes into their own system, so two implementations would be the one
// divergence this port must never produce.
mod dac_wizard_qt;
// The renderer TIER — one source of truth for what QRhi actually gave us and
// what may be offered because of it (the Qt analogue of Slint's
// `use_gpu_renderer`). A plain module: it declares no #[cxx_qt::bridge], so it
// must NOT appear in build.rs's rust_files.
mod renderer_qt;
mod foryou_qt;
mod genre_filter_qt;
mod home_qt;
@@ -2420,41 +2425,82 @@ fn publish_home_sections(sections: &home_qt::DiscoverSections) {
/// Metal default on macOS (the Slint remaps GL to skia(Metal) there,
/// main.rs:7651-7653); `software` maps to `QT_QUICK_BACKEND=software`.
///
/// OWED and kept in PARITY-DEBT #104: the crash auto-revert sentinel and
/// the frame-liveness watchdog — forcing a renderer without them can leave
/// a broken startup, exactly what the Slint sentinel was built for.
/// PARITY-DEBT #104 is CLOSED as of 2026-08-11: the crash auto-revert
/// sentinel and the frame-liveness watchdog now exist (`renderer_qt`). A
/// forced choice arms a sentinel here and the QML watchdog disarms it once
/// frames have genuinely been rendered; a launch that finds it still armed
/// reverts to "auto", so a backend this machine cannot start can no longer
/// lock the user out of Settings.
fn apply_renderer_preference() {
// Do this FIRST, before any early return: a launch that died on a forced
// backend must be undone even when this one is being overridden by env.
let reverted = renderer_qt::revert_if_previous_launch_died();
if std::env::var_os("QSG_RHI_BACKEND").is_some()
|| std::env::var_os("QT_QUICK_BACKEND").is_some()
{
log::info!("[renderer] explicit Qt backend env present; leaving the choice to it");
return;
}
let choice = match std::env::var("QBZ_RENDERER")
let from_env = std::env::var("QBZ_RENDERER")
.ok()
.map(|s| s.trim().to_ascii_lowercase())
.filter(|s| !s.is_empty() && s != "auto")
{
.filter(|s| !s.is_empty() && s != "auto");
let choice = match from_env.clone() {
Some(v) => v,
// A revert has just rewritten the pref to "auto"; use that rather than
// a value read one line before it changed.
None if reverted => "auto".to_string(),
None => settings_qt::pref_str("renderer", "auto"),
};
match choice.as_str() {
// Does this choice actually FORCE a backend? Only a forced one can brick a
// startup, and only a forced one may arm the sentinel: arming for a choice
// that changes nothing would let a crash from an unrelated cause silently
// reset the user's renderer preference on the next launch.
//
// The GPU-tier aliases (auto / wgpu / gpu / hardware / hw) all resolve to
// Qt's own default backend, so they force nothing — `wgpu` is a
// cross-frontend name kept for the shared pref, not a Qt backend.
let forces_backend = match choice.as_str() {
"software" | "cpu" | "soft" => {
std::env::set_var("QT_QUICK_BACKEND", "software");
log::info!("[renderer] '{choice}' -> QT_QUICK_BACKEND=software");
true
}
"gl" | "gles" | "femtovg" => {
if cfg!(target_os = "macos") {
log::info!("[renderer] '{choice}' on macOS -> Metal default (the Slint GL remap)");
false
} else {
std::env::set_var("QSG_RHI_BACKEND", "opengl");
log::info!("[renderer] '{choice}' -> QSG_RHI_BACKEND=opengl");
true
}
}
"auto" | "wgpu" | "gpu" | "hardware" | "hw" => {
log::info!("[renderer] '{choice}' -> Qt default backend (GPU path)");
false
}
other => {
log::warn!("[renderer] unrecognized choice '{other}' -> Qt default backend");
false
}
};
// NOT armed for a `QBZ_RENDERER` override either: the revert rewrites the
// PERSISTED pref, which an env override never set — it would blame (and
// silently reset) a setting the user did not choose, while the env would
// keep forcing the same dead backend on the next launch anyway.
//
// Arming AFTER `set_var` is still before anything reads it: Qt only
// consults these when `QGuiApplication` builds the backend, which is the
// caller's next statement.
if forces_backend && from_env.is_none() {
renderer_qt::arm_for_choice(&choice);
} else {
renderer_qt::clear_stale_sentinel();
if from_env.is_some() && forces_backend {
log::info!("[renderer] QBZ_RENDERER override — the startup sentinel stays out of it");
}
other => log::warn!("[renderer] unrecognized choice '{other}' -> Qt default backend"),
}
}
@@ -2573,7 +2619,12 @@ fn main() {
}
let _ = APP.set(runtime);
// BOTH must run before QGuiApplication: the renderer envs are read when
// the backend is chosen, and the GPU envs when the graphics context is
// created. Setting either afterwards is a silent no-op — the context is
// already up and nothing complains.
apply_renderer_preference();
renderer_qt::apply_gpu_preference();
let mut app = QGuiApplication::new();
let mut engine = QQmlApplicationEngine::new();
+545
View File
@@ -0,0 +1,545 @@
//! The renderer TIER — one source of truth for "what is actually drawing, and
//! what may we offer because of it".
//!
//! # The gap this closes
//!
//! Slint resolves `use_gpu_renderer` from `select_slint_backend()` and hands
//! that ONE bool to three features (`crates/qbz/src/main.rs`):
//!
//! | consumer | line | meaning |
//! |---|---|---|
//! | `shader_scenes_available` | `:8557` | the 6 immersive shader scenes — they render BLACK off the GPU tier |
//! | `app_background_available` | `:8563` | the app-wide dynamic background ("modo Cider") |
//! | `reduce_motion` | `:8597` | `kiosk_profile \|\| !use_gpu_renderer` |
//!
//! This port had none of it. `reduce_motion` shipped as the kiosk half alone
//! (`shell_bridge::reduce_motion_at_boot`), and the immersive contract records
//! the rest as deliberately absent (D11: *"The RENDERER-TIER half is still
//! genuinely absent"*) — which is precisely why the immersive shader scenes
//! could not be offered: there was nothing to gate them on.
//!
//! # Why the truth can only come from QML
//!
//! `main::apply_renderer_preference()` runs BEFORE `QGuiApplication` and knows
//! only what we ASKED FOR. What we actually GOT is decided by QRhi when the
//! scene graph initialises, and is readable only as `GraphicsInfo.api` on a
//! live item. Asking for OpenGL on a box whose driver refuses it lands on
//! software, and nothing before the window exists can know that.
//!
//! So QML reports the resolved api in exactly one place (`Main.qml`'s renderer
//! probe) and this module latches it. Slint has the same split; its
//! `select_slint_backend()` actually initialises the backend, which is why it
//! can return the truth synchronously and we cannot.
//!
//! # Two questions, two answers — do NOT collapse them
//!
//! * *"Can THIS item draw a shader right now?"* → the item's own
//! `GraphicsInfo.api`, which is per-window and already correct at the six
//! call sites that use it (`RoundedImage`, `Cortinilla`, `PlaylistCollage`,
//! `TrackInfoModal`, `ImmersiveView`, `StaticPanel`).
//! * *"Should this FEATURE be offered at all?"* → this tier.
//!
//! They look like duplicates and are not: the first is a drawing decision on
//! one item, the second is a product decision made once. Collapsing the first
//! onto this module would also make every cover in the app wait for a
//! round trip through Rust before it could pick its draw path.
//!
//! # The default is `true`, on purpose
//!
//! Until the probe reports, the tier reads GPU-capable. Both platforms were
//! measured on the GPU (OpenGL RHI on Linux, Metal on macOS, 2026-07-29), so
//! `true` is the honest prior AND it keeps today's behaviour byte for byte
//! until the probe disagrees — a `false` default would step every animation to
//! the reduce-motion cadence for the first frames of every launch.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
/// The resolved `GraphicsInfo.api`, lowercased: "opengl" | "metal" | "vulkan"
/// | "d3d11" | "d3d12" | "software" | "null" | "unknown".
static ACTIVE_API: Mutex<String> = Mutex::new(String::new());
/// Does the active backend carry the GPU tier? See the module header for why
/// this starts `true`.
static GPU_TIER: AtomicBool = AtomicBool::new(true);
/// Has a real (non-"unknown") report landed? Guards the one-shot log and lets
/// callers tell "GPU" from "not asked yet".
static RESOLVED: AtomicBool = AtomicBool::new(false);
/// The two api names that mean "no shaders": Qt's software rasteriser, and the
/// null backend the offscreen platform uses.
fn api_is_gpu(api: &str) -> bool {
!matches!(api, "software" | "null" | "unknown" | "")
}
/// Latch the api QRhi actually gave us. Called once from the QML probe; a
/// repeat with the same value is free, and "unknown" (the pre-resolution
/// value) is ignored rather than latched as "no GPU".
///
/// Returns true when this call CHANGED the tier, so the caller can decide
/// whether anything needs republishing.
pub fn set_active_api(api: &str) -> bool {
let api = api.trim().to_ascii_lowercase();
if api.is_empty() || api == "unknown" {
return false;
}
let tier = api_is_gpu(&api);
let previous_tier = GPU_TIER.swap(tier, Ordering::SeqCst);
let first = !RESOLVED.swap(true, Ordering::SeqCst);
{
let mut slot = ACTIVE_API.lock().unwrap_or_else(|e| e.into_inner());
if !first && *slot == api {
return false;
}
*slot = api.clone();
}
// Log the REQUESTED tier beside the resolved one: a mismatch is the whole
// reason this probe exists (asking for opengl on a box whose driver
// refuses it lands on software), and it is what the crash sentinel needs
// to reason about.
log::info!(
"[qbz-qt] renderer: requested={} resolved={api} gpu_tier={tier}",
crate::settings_qt::pref_str("renderer", "auto"),
);
if !tier {
log::warn!(
"[qbz-qt] renderer: NO GPU tier — shader scenes and the dynamic \
background stay hidden, reduce-motion is forced on"
);
}
first || previous_tier != tier
}
/// True when the active backend can run shaders. The Qt analogue of Slint's
/// `use_gpu_renderer`.
pub fn gpu_tier() -> bool {
GPU_TIER.load(Ordering::SeqCst)
}
/// The resolved api name, or "unknown" before the probe reports.
pub fn active_api() -> String {
let slot = ACTIVE_API.lock().unwrap_or_else(|e| e.into_inner());
if slot.is_empty() {
"unknown".to_string()
} else {
slot.clone()
}
}
/// The reduce-motion value, both halves composed — `kiosk || !gpu_tier`,
/// exactly the reference's expression (`main.rs:8597`).
///
/// It lives here rather than in either half's module because BOTH halves write
/// it: the kiosk live toggle and this probe. When the kiosk toggle owned the
/// property alone it simply overwrote the tier's contribution, which is the
/// bug this function exists to make impossible.
pub fn reduce_motion(kiosk: bool) -> bool {
kiosk || !gpu_tier()
}
// ===========================================================================
// The startup auto-revert sentinel (PARITY-DEBT #104's owed half)
// ===========================================================================
//
// Forcing a renderer is the one Settings row that can lock the user OUT of
// Settings: pick a backend this machine cannot start and the next launch dies
// before a window exists, with no way to undo the choice. Slint built a
// sentinel for exactly this (`crates/qbz/src/main.rs:7183-7210`); this port
// shipped the row WITHOUT it, which is what PARITY-DEBT #104 records as still
// owed.
//
// The shape: a file armed BEFORE the risky backend init and cleared once the
// session proves it is alive. Finding it still there at startup means the
// previous forced launch never got that far — so the pref reverts to "auto"
// and this launch uses Qt's own default.
//
// FILENAME: `qt_renderer_attempt`, deliberately NOT Slint's
// `renderer_attempt`. Both apps share `<data>/qbz/`, they can be run in either
// order, and one crashing must never revert the OTHER's renderer choice.
/// `<data>/qbz/qt_renderer_attempt` — see above for why the name differs from
/// the Slint sentinel's.
fn sentinel_path() -> Option<std::path::PathBuf> {
Some(dirs::data_dir()?.join("qbz").join("qt_renderer_attempt"))
}
/// Arm the sentinel for a non-auto choice, just before the env that forces it.
fn arm_sentinel(choice: &str) {
let Some(path) = sentinel_path() else { return };
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Err(e) = std::fs::write(&path, choice) {
log::warn!("[qbz-qt] renderer: could not arm the startup sentinel: {e}");
}
}
fn clear_sentinel() {
if let Some(path) = sentinel_path() {
let _ = std::fs::remove_file(path);
}
}
/// Is a sentinel currently armed? Lets the liveness report stay quiet on the
/// runs where there is nothing to protect — notably the offscreen smoke, which
/// presents no frames by design and would otherwise log a scary warning on
/// every gate.
pub fn sentinel_armed() -> bool {
sentinel_path().map(|p| p.exists()).unwrap_or(false)
}
/// The choice the armed sentinel was protecting, if one survived a launch.
fn armed_choice() -> Option<String> {
std::fs::read_to_string(sentinel_path()?)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
/// Called at the TOP of `apply_renderer_preference()`, before anything is
/// forced. If a previous forced launch left the sentinel armed it never
/// reached liveness, so the choice is reverted to "auto" and this launch runs
/// on Qt's default.
///
/// Returns true when a revert happened — the caller then ignores the persisted
/// pref for this launch (it has just been rewritten to "auto" anyway).
pub fn revert_if_previous_launch_died() -> bool {
let Some(choice) = armed_choice() else {
return false;
};
clear_sentinel();
log::warn!(
"[qbz-qt] renderer: the previous launch forced '{choice}' and never reached \
liveness — reverting to auto so the choice cannot lock you out of Settings"
);
crate::settings_qt::save_pref("renderer", serde_json::json!("auto"));
true
}
/// Arm for a choice that genuinely FORCES a backend. The caller decides that —
/// the GPU-tier aliases all resolve to Qt's own default and force nothing, so
/// arming for them would let an unrelated crash silently reset the pref.
pub fn arm_for_choice(choice: &str) {
arm_sentinel(choice);
log::info!("[qbz-qt] renderer: startup sentinel armed for '{choice}'");
}
/// Drop any sentinel left over from a previous configuration — this launch
/// forces nothing, so there is nothing to protect and nothing to revert.
pub fn clear_stale_sentinel() {
clear_sentinel();
}
/// Disarm on proof of LIVENESS — frames actually rendered over a window of
/// time, reported by the QML watchdog. Once-guarded, so the repeat calls a
/// binding might make are free.
pub fn disarm_on_liveness(frames: i32) {
static DISARMED: AtomicBool = AtomicBool::new(false);
if DISARMED.swap(true, Ordering::SeqCst) {
return;
}
// Only claim a disarm when something WAS armed. Saying "sentinel disarmed"
// on every ordinary launch trains the reader to skim past the line, which
// is precisely the run where it carries information.
if sentinel_armed() {
log::info!("[qbz-qt] renderer: startup sentinel disarmed ({frames} frames rendered)");
clear_sentinel();
} else {
log::debug!("[qbz-qt] renderer: liveness confirmed ({frames} frames), nothing armed");
}
}
// ===========================================================================
// Preferred GPU (PARITY-DEBT #83)
// ===========================================================================
//
// Scoping: `qbz-nix-docs/qt-frontend/2026-08-02-gpu-selection-scoping.md`.
// Qt's own documentation is blunt: QRhi "will choose the system default GPU
// adapter … No further adapter configurability is provided at this time." So
// there is no API — only the driver's env vars, and only on some platforms.
//
// | platform | selectable | how |
// |---|---|---|
// | Linux (OpenGL, this port's default) | YES | `DRI_PRIME`, or the NVIDIA PRIME pair |
// | Windows D3D | yes, when that port lands | `QT_D3D_ADAPTER_INDEX` |
// | macOS Metal | **NO** | QRhi hardcodes `MTLCreateSystemDefaultDevice` |
//
// So: implement Linux, HIDE the row on macOS. A row that cannot do anything is
// worse than no row — and until today this one was worse still, because it
// silently DROPPED every selection that was not "Auto"
// (`settings_qt.rs`, the old `"gpu-power"` arm persisted only index 0).
//
// CLASS KEYS, NEVER NAMES. The pref lives in the ui_prefs.json shared with the
// shipping Slint build, which accepts `"auto" | "integrated" | "discrete"` and
// falls back to Auto for anything it cannot parse. Writing an adapter NAME
// here would silently degrade the Slint side — and its wgpu/Vulkan names would
// not string-match what we read from sysfs anyway.
/// One physical GPU, as Vulkan enumerates it.
///
/// `index` is the position in `vkEnumeratePhysicalDevices` — the SAME number
/// `QT_VK_PHYSICAL_DEVICE_INDEX` selects by, because Qt calls the same
/// function. That identity is the whole reason this row can work at all.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GpuInfo {
pub index: u32,
/// The model, verbatim from the driver: "NVIDIA GeForce RTX 4070 Laptop
/// GPU", "Intel(R) Arc(tm) Graphics (MTL)".
pub name: String,
pub discrete: bool,
}
impl GpuInfo {
/// The dropdown label, in the reference's shape
/// (`"<name> (discrete|integrated)"`, `crates/qbz/src/main.rs:7427-7438`).
pub fn label(&self) -> String {
let class = if self.discrete {
qbz_i18n::t("discrete")
} else {
qbz_i18n::t("integrated")
};
format!("{} ({})", self.name, class)
}
}
/// Enumerate the real GPUs, once per process.
///
/// Empty when libvulkan is absent, no ICD is installed, or the instance cannot
/// be created — every one of which means "we cannot honour a GPU choice", so
/// the row collapses to Auto instead of offering hardware that may not exist.
/// That is the defect this replaces: a CLASS dropdown offers "Discrete GPU" on
/// a machine that has none.
pub fn gpus() -> &'static [GpuInfo] {
static GPUS: std::sync::OnceLock<Vec<GpuInfo>> = std::sync::OnceLock::new();
GPUS.get_or_init(|| {
let list = enumerate_vulkan_gpus();
if list.is_empty() {
log::info!("[qbz-qt] gpu: no Vulkan devices enumerated — the selector stays on Auto");
} else {
for g in &list {
log::info!(
"[qbz-qt] gpu: device {} '{}' ({})",
g.index,
g.name,
if g.discrete { "discrete" } else { "integrated" }
);
}
}
list
})
}
fn enumerate_vulkan_gpus() -> Vec<GpuInfo> {
use ash::vk;
// SAFETY: `Entry::load` dlopens libvulkan; every call below is a plain
// enumeration against the instance we create and destroy here. Nothing
// escapes this function but owned `String`s and plain numbers, and the
// instance is destroyed on every path.
unsafe {
let Ok(entry) = ash::Entry::load() else {
return Vec::new();
};
let app_info = vk::ApplicationInfo::default().api_version(vk::API_VERSION_1_0);
let create_info = vk::InstanceCreateInfo::default().application_info(&app_info);
let Ok(instance) = entry.create_instance(&create_info, None) else {
return Vec::new();
};
let devices = instance.enumerate_physical_devices().unwrap_or_default();
let mut out = Vec::with_capacity(devices.len());
for (i, pd) in devices.iter().enumerate() {
let props = instance.get_physical_device_properties(*pd);
let name = props
.device_name_as_c_str()
.ok()
.and_then(|s| s.to_str().ok())
.unwrap_or("")
.trim()
.to_string();
if name.is_empty() {
continue;
}
out.push(GpuInfo {
index: i as u32,
name,
discrete: props.device_type == vk::PhysicalDeviceType::DISCRETE_GPU,
});
}
instance.destroy_instance(None);
out
}
}
/// The GPU whose index Vulkan would pick with no override — Qt's own default
/// is device 0. Selecting it needs no coupling at all.
fn default_gpu_index() -> u32 {
0
}
/// Resolve a persisted `gpu_power` value to a device. Accepts a NAME (what
/// this row and the reference both store) and the legacy CLASS keys the older
/// builds and the Slint app write, so a shared pref never reads as garbage.
///
/// `None` = Auto, or a value that matches no present device — which is exactly
/// the case that used to let you select a GPU that does not exist.
pub fn resolve_gpu(pref: &str) -> Option<&'static GpuInfo> {
let pref = pref.trim();
if pref.is_empty() || pref == "auto" {
return None;
}
let list = gpus();
if let Some(hit) = list.iter().find(|g| g.name == pref) {
return Some(hit);
}
// Legacy class keys — resolve to a device that ACTUALLY EXISTS, or to
// nothing. "discrete" on a single-GPU laptop resolves to None, and that is
// the point.
match pref {
"discrete" => list.iter().find(|g| g.discrete),
"integrated" => list.iter().find(|g| !g.discrete),
_ => None,
}
}
/// Can this machine actually honour a Preferred-GPU choice?
///
/// Two conditions, and BOTH are the owner's point that a control must never
/// offer what does not exist:
/// * the platform can select at all — false on macOS, where QRhi hardcodes
/// `MTLCreateSystemDefaultDevice` (no env, no API);
/// * there is more than one GPU to choose BETWEEN. On a single-GPU box the row
/// is a dropdown with one real answer, so it hides.
pub fn gpu_selectable() -> bool {
cfg!(target_os = "linux") && gpus().len() > 1
}
/// Apply the persisted Preferred GPU. Called from `apply_renderer_preference`'s
/// slot — BEFORE `QGuiApplication`, because an env set after the graphics
/// context exists is a silent no-op (scoping trap 2).
///
/// Deliberately class-level, exactly like the reference: it nudges the driver
/// toward the integrated or the discrete GPU rather than binding one adapter.
/// Slint has the same limitation (documented F7) and so does Chromium
/// (`--force_high_performance_gpu`) — this is the ceiling of the platform, not
/// a shortcut.
pub fn apply_gpu_preference() {
if !gpu_selectable() {
return;
}
// An explicit env always wins — someone who exported one of these meant it,
// and it is the escape hatch when this row guesses wrong.
for taken in [
"QT_VK_PHYSICAL_DEVICE_INDEX",
"DRI_PRIME",
"__NV_PRIME_RENDER_OFFLOAD",
] {
if std::env::var_os(taken).is_some() {
log::info!("[qbz-qt] gpu: {taken} already set; leaving the choice to it");
return;
}
}
// `apply_renderer_preference()` runs FIRST and may have forced a backend.
// A GPU pick needs Vulkan (see below), so it cannot also honour an explicit
// `software`/`opengl` choice — the more specific, explicitly-chosen
// RENDERER wins and this says so rather than quietly overriding it.
if let Some(forced) = std::env::var_os("QSG_RHI_BACKEND")
.or_else(|| std::env::var_os("QT_QUICK_BACKEND"))
{
log::info!(
"[qbz-qt] gpu: the renderer row already forced {forced:?}; a GPU pick needs \
Vulkan, so the explicit renderer choice wins"
);
return;
}
let pref = crate::settings_qt::pref_str("gpu_power", "auto");
let Some(gpu) = resolve_gpu(&pref) else {
if pref != "auto" && !pref.is_empty() {
log::warn!(
"[qbz-qt] gpu: '{pref}' matches no device present on this machine -> Auto"
);
}
return;
};
if gpu.index == default_gpu_index() {
// Already the default: selecting it needs no override, and forcing one
// would buy the Vulkan coupling below for nothing.
log::info!("[qbz-qt] gpu: '{}' is device 0 (the default) -> no override", gpu.name);
return;
}
// THE VULKAN COUPLING, and why it is the only honest route.
//
// MEASURED 2026-08-11 on the Intel-Arc + RTX-4070 hybrid (Wayland,
// proprietary NVIDIA), with a 6-line QML scene carrying a MultiEffect:
//
// | env | result |
// |--------------------|-----------------------------------------------|
// | (none) | Intel Arc, OpenGL 4.6 desktop — healthy |
// | `DRI_PRIME=1` | **Mesa llvmpipe** — CPU software rendering |
// | NVIDIA PRIME pair | RTX 4070, **OpenGL ES 3.2** |
// | Vulkan + index | the chosen device, ZERO shader errors |
//
// The GLES context is fatal: Qt's baked `.qsb` shaders carry SPIR-V, GLSL
// 440 (desktop) and MSL — no GLES variants — so every effect dies with
// "No GLSL shader code found (versions tried: 320, 310, 300, 100)". That
// is what killed the NPB Large visualiser when this row first shipped the
// PRIME envs. `QT_OPENGL=desktop` does not rescue it (measured).
//
// Vulkan has none of that problem: the same .qsb already carries SPIR-V,
// and `QT_VK_PHYSICAL_DEVICE_INDEX` counts the SAME order this module
// enumerated. So picking a non-default GPU implies the Vulkan backend —
// stated in the row's own description, never silent.
std::env::set_var("QSG_RHI_BACKEND", "vulkan");
std::env::set_var("QT_VK_PHYSICAL_DEVICE_INDEX", gpu.index.to_string());
log::info!(
"[qbz-qt] gpu: '{}' -> QSG_RHI_BACKEND=vulkan QT_VK_PHYSICAL_DEVICE_INDEX={}",
gpu.name,
gpu.index
);
}
#[cfg(test)]
mod tests {
use super::*;
/// Only these two api names may drop the tier. Getting this list wrong is
/// silent: the app just quietly stops offering the shader scenes.
#[test]
fn only_software_and_null_lose_the_gpu_tier() {
for api in ["opengl", "metal", "vulkan", "d3d11", "d3d12"] {
assert!(api_is_gpu(api), "{api} should carry the GPU tier");
}
for api in ["software", "null"] {
assert!(!api_is_gpu(api), "{api} must NOT carry the GPU tier");
}
}
/// "unknown" is the value GraphicsInfo reports BEFORE the scene graph
/// resolves. Latching it as "no GPU" would hide the shader scenes on every
/// launch until something happened to re-report.
#[test]
fn unknown_is_not_a_verdict() {
assert!(!api_is_gpu("unknown"));
assert!(!api_is_gpu(""));
// …and it must not be latchable.
assert!(!set_active_api("unknown"));
assert!(!set_active_api(" "));
}
/// `GPU_TIER` is a process global and cargo runs tests in PARALLEL, so any
/// test that MUTATES it takes this first. (Three tests in
/// `dac_wizard_qt` raced exactly this way on 2026-08-11.)
static TEST_LOCK: Mutex<()> = Mutex::new(());
/// Both halves compose; neither can erase the other.
#[test]
fn reduce_motion_composes_both_halves() {
let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
GPU_TIER.store(true, Ordering::SeqCst);
assert!(!reduce_motion(false), "GPU + desktop = full motion");
assert!(reduce_motion(true), "kiosk forces it on regardless of tier");
GPU_TIER.store(false, Ordering::SeqCst);
assert!(reduce_motion(false), "a software tier forces it on by itself");
assert!(reduce_motion(true));
GPU_TIER.store(true, Ordering::SeqCst);
}
}
+57 -17
View File
@@ -1149,19 +1149,36 @@ fn index_of(values: &[&str], key: &str, default: usize) -> i32 {
values.iter().position(|v| *v == key).unwrap_or(default) as i32
}
/// Preferred-GPU dropdown (AppearanceSettings.slint): "Auto (recommended)"
/// + detected adapter names built in Rust. POC-NOTE: no adapter enumeration
/// in the POC — the list is Auto + the currently persisted adapter (so the
/// owner's real value shows selected); picking it again is a no-op.
/// Preferred-GPU dropdown. CLASS-LEVEL — Auto / integrated / discrete — which
/// is the ceiling of what any of these platforms offers (Qt: "No further
/// adapter configurability is provided at this time"; Slint's wgpu path is
/// class-level too, its documented F7 limitation).
///
/// Until 2026-08-11 this was Auto + whatever happened to be persisted, and the
/// select arm silently DROPPED every index but 0 — so the control could not
/// select a GPU and did not say so. PARITY-DEBT #83.
///
/// The values are `renderer_qt::GPU_POWER_VALUES`, the same class keys the
/// shipping Slint build parses out of the SHARED ui_prefs.json.
fn gpu_power_choice() -> (Vec<String>, i32) {
let persisted = pref_str("gpu_power", "auto");
// REAL devices, enumerated with Vulkan — never classes. Offering
// "Discrete GPU" as a fixed row is what let you select hardware the
// machine does not have; this lists what is actually present, by model,
// in the same shape as the reference (`main.rs:7427-7438`).
//
// A box with no Vulkan (no libvulkan, no ICD) enumerates nothing and gets
// Auto alone — the honest answer, since no GPU choice could be applied
// there either.
let gpus = crate::renderer_qt::gpus();
let mut opts = vec![qbz_i18n::t("Auto (recommended)")];
if persisted != "auto" && !persisted.is_empty() {
opts.push(persisted);
(opts, 1)
} else {
(opts, 0)
}
opts.extend(gpus.iter().map(|g| g.label()));
// Index 0 is Auto, so a device sits at its enumeration index + 1. An
// unmatched pref (a name from another machine, or a legacy class key with
// no such device) resolves to Auto.
let index = crate::renderer_qt::resolve_gpu(&pref_str("gpu_power", "auto"))
.map(|g| g.index as i32 + 1)
.unwrap_or(0);
(opts, index)
}
#[derive(Clone, Default, Serialize)]
@@ -1328,6 +1345,11 @@ pub struct SettingsDoc {
pub gpu_powers: Vec<String>,
#[serde(rename = "gpuPowerIndex")]
pub gpu_power_index: i32,
/// Can this platform honour a Preferred-GPU choice at all? False on macOS,
/// where QRhi hardcodes the system default device — the row HIDES there
/// rather than offering a control that cannot do anything.
#[serde(rename = "gpuSelectable")]
pub gpu_selectable: bool,
// Appearance > SYSTEM TRAY (tray_settings.db)
#[serde(rename = "trayEnable")]
pub tray_enable: bool,
@@ -1741,6 +1763,7 @@ pub async fn publish_snapshot() {
renderer_index: index_of(RENDERER_VALUES, &pref_str("renderer", "auto"), 0),
gpu_powers: gpu_power_choice().0,
gpu_power_index: gpu_power_choice().1,
gpu_selectable: crate::renderer_qt::gpu_selectable(),
tray_enable: tray().get_settings().map(|t| t.enable_tray).unwrap_or(true),
// S1: the shared default is `close_to_tray: true`
// (`qbz-app/src/settings/tray.rs:61`), and the Slint glue reads it
@@ -2323,14 +2346,31 @@ pub async fn settings_select(runtime: &Arc<AppRuntime<LoggingAdapter>>, key: &st
};
save_pref("renderer", serde_json::json!(v));
log::info!("[qbz-qt] renderer -> {v} (restart to apply)");
// The reference toasts here (`crates/qbz/src/main.rs:11326-11329`)
// and this port only logged — so the row changed nothing visible
// and gave no hint that a restart was needed.
crate::toast_qt::info(qbz_i18n::t("Renderer changed — restart QBZ to apply"));
}
"gpu-power" => {
// Only "Auto" is actionable in the POC (no adapter enumeration —
// the persisted-name row is display-only).
if index == 0 {
save_pref("gpu_power", serde_json::json!("auto"));
log::info!("[qbz-qt] gpu_power -> auto (restart to apply)");
}
// Index 0 is Auto; every other index is a REAL enumerated device,
// stored by NAME — the same shape the reference persists, so the
// shared ui_prefs round-trips between the two apps. The old arm
// accepted only index 0 and silently discarded the rest
// (PARITY-DEBT #83).
let gpus = crate::renderer_qt::gpus();
let value = if index <= 0 {
"auto".to_string()
} else {
match gpus.get((index - 1) as usize) {
Some(g) => g.name.clone(),
// The list moved under the user (a GPU was unplugged, or
// the document is stale) — Auto rather than a wrong device.
None => "auto".to_string(),
}
};
save_pref("gpu_power", serde_json::json!(value));
log::info!("[qbz-qt] gpu_power -> {value} (restart to apply)");
crate::toast_qt::info(qbz_i18n::t("Preferred GPU changed — restart QBZ to apply"));
}
"tray-icon-theme" => {
let Some(v) = TRAY_ICON_VALUES.get(index) else {
+101
View File
@@ -198,6 +198,26 @@ pub mod qbz_shell {
/// KIOSK port can consume it rather than having to invent it. See
/// `set_reduce_motion` for the two halves and why one is dormant.
#[qproperty(bool, reduce_motion)]
/// The api QRhi actually gave us: "opengl" | "metal" | "vulkan" |
/// "d3d11" | "d3d12" | "software" | "null", or "unknown" before the
/// probe reports. Diagnostics only — features gate on the two
/// booleans below, never on this string.
#[qproperty(QString, renderer_api)]
/// Does the active backend carry the GPU tier? The Qt analogue of
/// Slint's `use_gpu_renderer` (`crates/qbz/src/main.rs:8448`).
#[qproperty(bool, gpu_tier)]
/// May the 6 immersive shader scenes be offered? Off the GPU tier they
/// render BLACK, which is why the reference hides them from the picker
/// and the `g` cycle key (`main.rs:8557`).
///
/// **This is the gate the immersive shader scenes were waiting on** —
/// the immersive contract's D11 records the renderer-tier half as
/// deliberately absent, and it was the reason the scenes could not
/// ship.
#[qproperty(bool, shader_scenes_available)]
/// May the app-wide dynamic background ("modo Cider") be offered?
/// Same tier, same reason (`main.rs:8563`); gates the whole picker row.
#[qproperty(bool, app_background_available)]
/// Is the kiosk touch shell the one currently mounted?
///
/// The Qt counterpart of `ShellState.kiosk-profile`
@@ -314,6 +334,29 @@ pub mod qbz_shell {
#[qinvokable]
fn boot(self: Pin<&mut QbzShell>);
/// Report the api QRhi actually resolved to. Called ONCE, by the
/// renderer probe in `Main.qml`, with `GraphicsInfo.api` mapped to a
/// name in QML — so Rust never depends on the numeric enum, whose
/// values are a Qt implementation detail.
///
/// Only QML can answer this: `apply_renderer_preference()` runs before
/// `QGuiApplication` and knows only what we ASKED for, and a driver
/// that refuses the request lands us somewhere else entirely.
/// "unknown" (the pre-resolution value) is ignored, not latched.
#[qinvokable]
fn report_renderer_api(self: Pin<&mut QbzShell>, api: QString);
/// The frame-liveness watchdog's verdict (PARITY-DEBT #104's other
/// owed half). Reported once by `Main.qml` after a settling window,
/// with the number of frames the window actually swapped in it.
///
/// Proof of frames — not merely of a window — is what disarms the
/// startup sentinel: a backend can create a window and then never
/// present, which looks identical to a healthy start until the user
/// sees a frozen pane.
#[qinvokable]
fn report_frame_liveness(self: Pin<&mut QbzShell>, frames: i32);
// --- Shell chrome -------------------------------------------------
/// Header panel-left button: cycle the sidebar open -> mini ->
/// closed -> open (Slint `ShellState.cycle-sidebar()`).
@@ -584,6 +627,10 @@ pub struct QbzShellRust {
window_min_width: f32,
window_min_height: f32,
reduce_motion: bool,
renderer_api: QString,
gpu_tier: bool,
shader_scenes_available: bool,
app_background_available: bool,
kiosk_profile: bool,
kiosk_fullscreen_boot: bool,
ambient_mode: i32,
@@ -662,6 +709,15 @@ impl Default for QbzShellRust {
window_min_width: crate::settings_qt::WINDOW_MIN_WIDTH,
window_min_height: crate::settings_qt::WINDOW_MIN_HEIGHT,
reduce_motion: reduce_motion_at_boot(),
// The tier starts GPU-capable: both platforms were MEASURED on the
// GPU (OpenGL RHI / Metal, 2026-07-29), so it is the honest prior,
// and it keeps the pre-probe frames behaving exactly as they did
// before this seam existed. `renderer_qt` explains why a `false`
// default would be the worse guess.
renderer_api: QString::from("unknown"),
gpu_tier: crate::renderer_qt::gpu_tier(),
shader_scenes_available: crate::renderer_qt::gpu_tier(),
app_background_available: crate::renderer_qt::gpu_tier(),
kiosk_profile: crate::kiosk_profile_qt::active(),
kiosk_fullscreen_boot: crate::kiosk_profile_qt::active()
&& crate::kiosk_profile_qt::fullscreen_at_boot(),
@@ -800,6 +856,51 @@ impl qbz_shell::QbzShell {
}
}
/// The renderer probe's one-shot report (see the declaration).
///
/// Writes all four derived properties from the SAME latch, so a consumer
/// can never see `gpuTier` disagree with `shaderScenesAvailable`. The
/// reduce-motion write composes both halves through
/// `renderer_qt::reduce_motion` rather than assigning the tier directly —
/// the kiosk toggle writes the same property, and a bare assignment from
/// either side would erase the other's contribution.
pub fn report_renderer_api(mut self: Pin<&mut Self>, api: QString) {
let api = api.to_string();
if !crate::renderer_qt::set_active_api(&api) {
return;
}
let tier = crate::renderer_qt::gpu_tier();
self.as_mut()
.set_renderer_api(QString::from(&crate::renderer_qt::active_api()));
self.as_mut().set_gpu_tier(tier);
self.as_mut().set_shader_scenes_available(tier);
self.as_mut().set_app_background_available(tier);
let kiosk = crate::kiosk_profile_qt::active();
self.as_mut()
.set_reduce_motion(crate::renderer_qt::reduce_motion(kiosk));
}
/// See the declaration. A window that swapped no frames is NOT liveness,
/// so it leaves the sentinel armed and the next launch reverts to auto.
pub fn report_frame_liveness(self: Pin<&mut Self>, frames: i32) {
if frames <= 0 {
// Only alarming when something is actually being protected. The
// offscreen smoke presents no frames BY DESIGN, and warning on
// every gate run would train the reader to ignore the one time it
// matters.
if crate::renderer_qt::sentinel_armed() {
log::warn!(
"[qbz-qt] renderer: the liveness window closed with NO frames rendered — \
leaving the startup sentinel armed so the next launch reverts to auto"
);
} else {
log::debug!("[qbz-qt] renderer: no frames in the liveness window (nothing armed)");
}
return;
}
crate::renderer_qt::disarm_on_liveness(frames);
}
pub fn cycle_sidebar(mut self: Pin<&mut Self>) {
let next = (self.sidebar_state() + 1) % 3;
self.as_mut().set_sidebar_state(next);