1
//! The graphics-check dialog (`SysDialogType::GpuCheck`).
2
//!
3
//! For apps that NEED working video acceleration. It is a thin, honest face
4
//! on machinery that already exists: the shell's GL probe (`query_gpu_info`,
5
//! published through [`crate::appenv::gpu_status`]) says what the RENDERER
6
//! got, and the dll's provisioning check
7
//! (`VideoStartupCheck::run`/`remediate`, reached through
8
//! [`crate::appenv::gpu_provision_hooks`]) says whether hardware decode is
9
//! ready, whether the machine is SAFE TO REBOOT, and what a one-click repair
10
//! would run.
11
//!
12
//! Consent is the whole design: `run()` is inspection only and happens on a
13
//! worker thread when the dialog opens; `remediate()` — which elevates via
14
//! pkexec and can install drivers or repair an unbootable kernel — runs ONLY
15
//! after the user has read the exact command list and pressed the button.
16
//! When the remediation needs a reboot, or when the CURRENT boot path is
17
//! already unsafe, the dialog says so before anything is applied.
18

            
19
use alloc::{
20
    string::{String, ToString},
21
    vec::Vec,
22
};
23

            
24
use azul_core::{
25
    callbacks::{LayoutCallbackInfo, LayoutCallbackType, Update},
26
    dom::Dom,
27
    refany::RefAny,
28
    task::{ThreadId, ThreadReceiver},
29
};
30
use azul_css::AzString;
31

            
32
use super::{cpu_dialog_window, style};
33
use crate::{
34
    appenv::{GpuProvisionOutcome, GpuProvisionReport, GpuStatus},
35
    callbacks::CallbackInfo,
36
    thread::{
37
        Thread, ThreadCallbackType, ThreadReceiveMsg, ThreadSender, ThreadWriteBackMsg,
38
        WriteBackCallbackType,
39
    },
40
    widgets::{
41
        button::{Button, ButtonOnClickCallbackType},
42
        progressbar::ProgressBar,
43
    },
44
};
45

            
46
/// Where the dialog is in the inspect → consent → apply story.
47
#[derive(Debug, Clone)]
48
pub enum GpuPhase {
49
    /// The readiness check is running on a worker thread.
50
    Checking,
51
    /// The check came back; waiting for the user.
52
    Report(GpuProvisionReport),
53
    /// No shell published provisioning hooks (a build without the video
54
    /// stack, or a headless run) — the GL section is still shown.
55
    Unavailable(String),
56
    /// The user consented; the remediation is running (pkexec prompt).
57
    /// Carries REAL progress: commands finished / total, and the command
58
    /// currently running.
59
    Applying {
60
        /// Commands finished so far.
61
        done: usize,
62
        /// Commands the plan set out to run.
63
        total: usize,
64
        /// The command running right now.
65
        step: String,
66
    },
67
    /// The remediation finished.
68
    Applied(GpuProvisionOutcome),
69
}
70

            
71
/// Shared dialog state (window ctx + worker writebacks).
72
#[derive(Debug, Clone)]
73
pub struct GpuDialogState {
74
    /// Current phase.
75
    pub phase: GpuPhase,
76
}
77

            
78
/// Opens the dialog and starts the (inspection-only) readiness check.
79
pub fn open(info: &mut CallbackInfo) {
80
    let state = RefAny::new(GpuDialogState {
81
        phase: GpuPhase::Checking,
82
    });
83
    info.add_thread(
84
        ThreadId::unique(),
85
        Thread::create(
86
            RefAny::new(CheckTask),
87
            state.clone(),
88
            check_worker as ThreadCallbackType,
89
        ),
90
    );
91
    info.create_window(cpu_dialog_window(
92
        "Graphics Check",
93
        (560.0, 560.0),
94
        dialog_layout as LayoutCallbackType,
95
        state,
96
    ));
97
}
98

            
99
struct CheckTask;
100
struct NewPhase(GpuPhase);
101

            
102
/// Background: the provisioning readiness check. INSPECTION ONLY — it
103
/// dlopen's codec libraries and reads kernel/driver state, changes nothing.
104
extern "C" fn check_worker(mut _init: RefAny, mut sender: ThreadSender, _recv: ThreadReceiver) {
105
    let phase = match crate::appenv::gpu_provision_hooks() {
106
        Some(hooks) => GpuPhase::Report((hooks.check)()),
107
        None => GpuPhase::Unavailable(
108
            "This build has no driver-provisioning support, so only the renderer's own report is \
109
             available."
110
                .to_owned(),
111
        ),
112
    };
113
    let _ = sender.send(ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
114
        apply_phase as WriteBackCallbackType,
115
        RefAny::new(NewPhase(phase)),
116
    )));
117
}
118

            
119
/// Background: the CONSENTED remediation. Side-effecting — driver install
120
/// and/or kernel repair through pkexec.
121
extern "C" fn remediate_worker(mut _init: RefAny, mut sender: ThreadSender, _recv: ThreadReceiver) {
122
    let phase = match crate::appenv::gpu_provision_hooks() {
123
        Some(hooks) => {
124
            // One writeback per command, so the bar moves for real. (The
125
            // main-thread drain reads the queue until it is EMPTY — see the
126
            // `every_writeback_a_worker_sends_reaches_the_main_thread` law;
127
            // before that fix everything after the first step was dropped.)
128
            let mut on_step = |done: usize, total: usize, step: &str| {
129
                let _ = sender.send(ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
130
                    apply_phase as WriteBackCallbackType,
131
                    RefAny::new(NewPhase(GpuPhase::Applying {
132
                        done,
133
                        total,
134
                        step: step.to_owned(),
135
                    })),
136
                )));
137
            };
138
            GpuPhase::Applied((hooks.remediate)(&mut on_step))
139
        }
140
        None => GpuPhase::Applied(GpuProvisionOutcome {
141
            ok: false,
142
            reboot_required: false,
143
            message: "provisioning hooks disappeared between check and apply".to_owned(),
144
        }),
145
    };
146
    let _ = sender.send(ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
147
        apply_phase as WriteBackCallbackType,
148
        RefAny::new(NewPhase(phase)),
149
    )));
150
}
151

            
152
/// Main thread: move the shared state to the worker's phase.
153
extern "C" fn apply_phase(mut state: RefAny, mut msg: RefAny, _info: CallbackInfo) -> Update {
154
    let Some(new_phase) = msg.downcast_ref::<NewPhase>().map(|p| p.0.clone()) else {
155
        return Update::DoNothing;
156
    };
157
    if let Some(mut s) = state.downcast_mut::<GpuDialogState>() {
158
        s.phase = new_phase;
159
    }
160
    Update::RefreshDomAllWindows
161
}
162

            
163
// --- buttons ---------------------------------------------------------------
164

            
165
/// The consent button. Everything before this point was inspection.
166
extern "C" fn on_repair_now(mut state: RefAny, mut info: CallbackInfo) -> Update {
167
    {
168
        let Some(mut s) = state.downcast_mut::<GpuDialogState>() else {
169
            return Update::DoNothing;
170
        };
171
        let GpuPhase::Report(report) = &s.phase else {
172
            return Update::DoNothing;
173
        };
174
        if !report.can_remediate {
175
            return Update::DoNothing;
176
        }
177
        s.phase = GpuPhase::Applying {
178
            done: 0,
179
            total: 0,
180
            step: String::new(),
181
        };
182
    }
183
    info.add_thread(
184
        ThreadId::unique(),
185
        Thread::create(
186
            RefAny::new(CheckTask),
187
            state.clone(),
188
            remediate_worker as ThreadCallbackType,
189
        ),
190
    );
191
    Update::RefreshDomAllWindows
192
}
193

            
194
extern "C" fn on_close(mut _state: RefAny, mut info: CallbackInfo) -> Update {
195
    info.close_window();
196
    Update::DoNothing
197
}
198

            
199
// --- layout ----------------------------------------------------------------
200

            
201
extern "C" fn dialog_layout(_data: RefAny, info: LayoutCallbackInfo) -> Dom {
202
    let Some(mut ctx) = info.get_ctx().into_option() else {
203
        return Dom::create_body();
204
    };
205
    let phase = match ctx.downcast_ref::<GpuDialogState>() {
206
        Some(s) => s.phase.clone(),
207
        None => return Dom::create_body(),
208
    };
209
    drop(ctx);
210
    let state = info
211
        .get_ctx()
212
        .into_option()
213
        .unwrap_or_else(|| RefAny::new(()));
214

            
215
    use azul_css::props::{
216
        basic::pixel::PixelValue,
217
        layout::{LayoutPaddingBottom, LayoutPaddingLeft, LayoutPaddingRight, LayoutPaddingTop},
218
    };
219
    let pad = style(vec![
220
        azul_css::props::property::CssProperty::padding_left(LayoutPaddingLeft {
221
            inner: PixelValue::px(16.0),
222
        }),
223
        azul_css::props::property::CssProperty::padding_right(LayoutPaddingRight {
224
            inner: PixelValue::px(16.0),
225
        }),
226
        azul_css::props::property::CssProperty::padding_top(LayoutPaddingTop {
227
            inner: PixelValue::px(16.0),
228
        }),
229
        azul_css::props::property::CssProperty::padding_bottom(LayoutPaddingBottom {
230
            inner: PixelValue::px(16.0),
231
        }),
232
    ]);
233

            
234
    let mut children: Vec<Dom> = vec![Dom::create_h2_with_text("Graphics check")];
235
    let mut buttons: Vec<(&str, ButtonOnClickCallbackType, RefAny)> = Vec::new();
236

            
237
    match &phase {
238
        GpuPhase::Checking => {
239
            children.push(Dom::create_p_with_text(
240
                "Checking the graphics drivers and the boot path...",
241
            ));
242
        }
243
        GpuPhase::Report(report) => {
244
            children.push(Dom::create_p_with_text(report.summary.as_str()));
245
            children.push(Dom::create_p_with_text(alloc::format!(
246
                "Hardware video decode: {}",
247
                yes_no(report.hw_decode_ready)
248
            )));
249
            children.push(Dom::create_p_with_text(alloc::format!(
250
                "Safe to reboot: {}",
251
                yes_no(report.boot_safe)
252
            )));
253
            if !report.boot_safe {
254
                children.push(Dom::create_p_with_text(
255
                    "WARNING: as things stand, the next reboot may not reach a usable desktop. \
256
                     Apply the repair below BEFORE rebooting.",
257
                ));
258
            }
259
            children.extend(detail_lines(&report.detail));
260
            if report.can_remediate {
261
                children.push(Dom::create_p_with_text(
262
                    "The repair runs the commands listed above and will ask for your password.",
263
                ));
264
                if report.needs_reboot {
265
                    children.push(Dom::create_p_with_text(
266
                        "It takes effect after a restart - nothing reboots on its own.",
267
                    ));
268
                }
269
                buttons.push((
270
                    "Repair now",
271
                    on_repair_now as ButtonOnClickCallbackType,
272
                    state.clone(),
273
                ));
274
            }
275
        }
276
        GpuPhase::Unavailable(reason) => {
277
            children.push(Dom::create_p_with_text(reason.as_str()));
278
        }
279
        GpuPhase::Applying { done, total, step } => {
280
            children.push(Dom::create_p_with_text(
281
                "Applying... you may be asked for your password. Do not close this window.",
282
            ));
283
            // A real fraction or nothing: an indeterminate bar drawn as if it
284
            // measured something is worse than no bar. `total == 0` is the
285
            // window between consent and the first command report.
286
            if *total > 0 {
287
                #[allow(clippy::cast_precision_loss)]
288
                let percent = (*done as f32 / *total as f32) * 100.0;
289
                children.push(ProgressBar::create(percent).dom());
290
                children.push(Dom::create_p_with_text(alloc::format!(
291
                    "Step {} of {}: {}",
292
                    done + 1,
293
                    total,
294
                    step
295
                )));
296
            } else {
297
                children.push(Dom::create_p_with_text("Starting..."));
298
            }
299
        }
300
        GpuPhase::Applied(outcome) => {
301
            children.push(Dom::create_p_with_text(if outcome.ok {
302
                "The repair finished."
303
            } else {
304
                "The repair did not finish."
305
            }));
306
            children.push(Dom::create_p_with_text(outcome.message.as_str()));
307
            if outcome.reboot_required {
308
                children.push(Dom::create_p_with_text(
309
                    "Restart the machine to finish - the change is staged, not live.",
310
                ));
311
            }
312
        }
313
    }
314

            
315
    children.extend(gl_section(crate::appenv::gpu_status().as_ref()));
316
    buttons.push(("Close", on_close as ButtonOnClickCallbackType, state));
317
    children.push(button_row(buttons));
318

            
319
    Dom::create_body()
320
        .with_css_props(pad)
321
        .with_children(children.into())
322
}
323

            
324
/// What the RENDERER actually got, as opposed to what the machine could do.
325
/// Always shown: it is the answer to "why is this app slow/soft-rendered".
326
fn gl_section(status: Option<&GpuStatus>) -> Vec<Dom> {
327
    let mut out = vec![Dom::create_h2_with_text("This window's renderer")];
328
    match status {
329
        Some(s) if s.ok => {
330
            out.push(Dom::create_p_with_text(alloc::format!(
331
                "GPU rendering, on {} ({})",
332
                s.renderer,
333
                s.vendor
334
            )));
335
            out.push(Dom::create_p_with_text(alloc::format!(
336
                "OpenGL {} - GLSL {}",
337
                s.version,
338
                s.glsl_version
339
            )));
340
        }
341
        Some(s) => {
342
            out.push(Dom::create_p_with_text(
343
                "CPU rendering - the GPU path was rejected.",
344
            ));
345
            if !s.renderer.is_empty() {
346
                out.push(Dom::create_p_with_text(alloc::format!(
347
                    "Detected: {} ({}) - OpenGL {}",
348
                    s.renderer,
349
                    s.vendor,
350
                    s.version
351
                )));
352
            }
353
            out.push(Dom::create_p_with_text(alloc::format!(
354
                "Why: {}", s.verdict
355
            )));
356
        }
357
        None => out.push(Dom::create_p_with_text(
358
            "CPU rendering - no GPU probe ran in this session.",
359
        )),
360
    }
361
    out
362
}
363

            
364
/// The provisioning report's multi-line detail, one paragraph per line, so
365
/// the exact command list the user is consenting to stays readable.
366
fn detail_lines(detail: &str) -> Vec<Dom> {
367
    detail
368
        .lines()
369
        .filter(|l| !l.trim().is_empty())
370
        .map(Dom::create_p_with_text)
371
        .collect()
372
}
373

            
374
const fn yes_no(v: bool) -> &'static str {
375
    if v {
376
        "yes"
377
    } else {
378
        "no"
379
    }
380
}
381

            
382
/// Buttons on one line (same shape as the other dialogs' rows).
383
fn button_row(buttons: Vec<(&str, ButtonOnClickCallbackType, RefAny)>) -> Dom {
384
    let children: Vec<Dom> = buttons
385
        .into_iter()
386
        .map(|(label, cb, state)| {
387
            Button::create(AzString::from(label))
388
                .with_on_click(state, cb)
389
                .dom()
390
        })
391
        .collect();
392
    Dom::create_div().with_children(children.into())
393
}