1
//! Process-wide snapshot of the app-level configuration that ENGINE services
2
//! (updater, system dialogs) need outside any callback: the app's name and
3
//! version, where the update manifest lives, the changelog URL, the support
4
//! mailbox.
5
//!
6
//! `AppConfig` is the source of truth; `App::run` publishes it here once at
7
//! startup (same pattern as `window::set_global_system_animations`). Layout
8
//! examples and tests that never go through `App::run` call [`set_app_env`]
9
//! directly.
10

            
11
use std::sync::RwLock;
12

            
13
use azul_core::resources::UpdateMode;
14

            
15
/// The published snapshot. All fields plain owned data — this is read from
16
/// worker threads.
17
#[derive(Debug, Clone, PartialEq, Eq)]
18
pub struct AppEnv {
19
    /// Directory-safe app name (updater state dir, problem-report dir).
20
    pub app_name: String,
21
    /// The RUNNING version, the compare target for update checks.
22
    pub current_version: String,
23
    /// Requested update behaviour (clamped by install kind at check time).
24
    pub update_mode: UpdateMode,
25
    /// Update manifest URL; `None` = checks report a configuration error.
26
    pub update_manifest: Option<String>,
27
    /// App changelog (Markdown) URL, the `UpdateVersion` dialog's fallback when
28
    /// a release has no changelog link of its own.
29
    pub changelog_md: Option<String>,
30
    /// Support mailbox for problem reports; `None` = reports save to disk.
31
    pub report_problem: Option<String>,
32
    /// `AppConfig.updates.root_public_key` — the compiled-in minisign root
33
    /// key that arms the update signature chain (None = digest-only).
34
    pub update_root_public_key: Option<String>,
35
    /// `AppConfig.updates.channel` — the release channel this binary
36
    /// follows ("" = stable).
37
    pub update_channel: String,
38
}
39

            
40
impl Default for AppEnv {
41
2
    fn default() -> Self {
42
2
        Self {
43
2
            app_name: "azul-app".to_owned(),
44
2
            current_version: "0.0.0".to_owned(),
45
2
            update_mode: UpdateMode::NotifyOnly,
46
2
            update_manifest: None,
47
2
            changelog_md: None,
48
2
            report_problem: None,
49
2
            update_root_public_key: None,
50
2
            update_channel: String::new(),
51
2
        }
52
2
    }
53
}
54

            
55
impl AppEnv {
56
    /// The snapshot an [`azul_core::resources::AppConfig`] describes.
57
    #[must_use]
58
2
    pub fn from_config(config: &azul_core::resources::AppConfig) -> Self {
59
4
        let opt = |s: &azul_css::OptionString| {
60
4
            s.as_ref()
61
4
                .map(|v| v.as_str().to_owned())
62
4
                .filter(|v| !v.is_empty())
63
4
        };
64
        Self {
65
2
            app_name: config.updates.app_name.as_str().to_owned(),
66
2
            current_version: config.updates.current_version.as_str().to_owned(),
67
2
            update_mode: config.updates.mode,
68
2
            update_manifest: opt(&config.updates.manifest_url),
69
            update_root_public_key: {
70
2
                let k = config.updates.root_public_key.as_str();
71
2
                if k.is_empty() {
72
2
                    None
73
                } else {
74
                    Some(k.to_owned())
75
                }
76
            },
77
2
            update_channel: config.updates.channel.as_str().to_owned(),
78
2
            changelog_md: opt(&config.changelog_md),
79
2
            report_problem: match &config.report_problem {
80
1
                azul_core::resources::OptionEmailAddress::Some(e) => {
81
1
                    let a = e.address.as_str();
82
1
                    if a.is_empty() {
83
                        None
84
                    } else {
85
1
                        Some(a.to_owned())
86
                    }
87
                }
88
1
                azul_core::resources::OptionEmailAddress::None => None,
89
            },
90
        }
91
2
    }
92
}
93

            
94
static APP_ENV: RwLock<Option<AppEnv>> = RwLock::new(None);
95

            
96
/// Publishes the snapshot (called by `App::run`; re-callable — tests and
97
/// multi-`App` processes overwrite the previous value).
98
1
pub fn set_app_env(env: AppEnv) {
99
1
    if let Ok(mut slot) = APP_ENV.write() {
100
1
        *slot = Some(env);
101
1
    }
102
1
}
103

            
104
/// The current snapshot; a default (no manifest, no mailbox) when nothing
105
/// was published.
106
#[must_use]
107
5
pub fn app_env() -> AppEnv {
108
5
    APP_ENV
109
5
        .read()
110
5
        .ok()
111
5
        .and_then(|slot| slot.clone())
112
5
        .unwrap_or_default()
113
5
}
114

            
115
#[cfg(test)]
116
mod tests {
117
    use super::*;
118

            
119
    #[test]
120
1
    fn config_round_trips_into_the_env() {
121
1
        let mut config = azul_core::resources::AppConfig::create();
122
1
        config.updates.app_name = "testapp".into();
123
1
        config.updates.current_version = "1.2.3".into();
124
1
        config.updates.mode = UpdateMode::SelfUpdate;
125
1
        config.updates.manifest_url =
126
1
            azul_css::OptionString::Some("http://localhost:1/manifest.json".into());
127
1
        config.changelog_md =
128
1
            azul_css::OptionString::Some("http://localhost:1/CHANGELOG.md".into());
129
1
        config.report_problem = azul_core::resources::OptionEmailAddress::Some(
130
1
            azul_core::resources::EmailAddress::new("support@example.test".into()),
131
1
        );
132
1
        let env = AppEnv::from_config(&config);
133
1
        assert_eq!(env.app_name, "testapp");
134
1
        assert_eq!(env.current_version, "1.2.3");
135
1
        assert_eq!(env.update_mode, UpdateMode::SelfUpdate);
136
1
        assert_eq!(
137
1
            env.update_manifest.as_deref(),
138
            Some("http://localhost:1/manifest.json")
139
        );
140
1
        assert_eq!(
141
1
            env.changelog_md.as_deref(),
142
            Some("http://localhost:1/CHANGELOG.md")
143
        );
144
1
        assert_eq!(env.report_problem.as_deref(), Some("support@example.test"));
145
1
    }
146

            
147
    #[test]
148
1
    fn empty_strings_read_as_unset_not_as_empty_urls() {
149
        // An empty manifest URL must NOT produce Some("") — the check would
150
        // then try to fetch "" instead of reporting "not configured".
151
1
        let config = azul_core::resources::AppConfig::create();
152
1
        let env = AppEnv::from_config(&config);
153
1
        assert_eq!(env.update_manifest, None);
154
1
        assert_eq!(env.changelog_md, None);
155
1
        assert_eq!(env.report_problem, None);
156
1
    }
157
}
158

            
159
/// What the shell's GL probe found, published the moment `query_gpu_info`
160
/// runs (the chokepoint every GL-probing platform shares). `None` until a
161
/// probe runs — a CPU-only session simply never probes.
162
#[derive(Debug, Clone, Default, PartialEq, Eq)]
163
pub struct GpuStatus {
164
    /// `GL_VENDOR`.
165
    pub vendor: String,
166
    /// `GL_RENDERER`.
167
    pub renderer: String,
168
    /// `GL_VERSION`.
169
    pub version: String,
170
    /// `GL_SHADING_LANGUAGE_VERSION`.
171
    pub glsl_version: String,
172
    /// Human-readable verdict: `ok`, `blacklisted: <reason>`, or
173
    /// `query failed: <reason>`.
174
    pub verdict: String,
175
    /// Whether GPU rendering is actually usable.
176
    pub ok: bool,
177
}
178

            
179
static GPU_STATUS: RwLock<Option<GpuStatus>> = RwLock::new(None);
180

            
181
/// Publishes the probe outcome (called from the shell's GL init).
182
pub fn set_gpu_status(status: GpuStatus) {
183
    if let Ok(mut slot) = GPU_STATUS.write() {
184
        *slot = Some(status);
185
    }
186
}
187

            
188
/// The last published probe outcome, if any probe ran.
189
#[must_use]
190
pub fn gpu_status() -> Option<GpuStatus> {
191
    GPU_STATUS.read().ok().and_then(|slot| slot.clone())
192
}
193

            
194
/// A readiness report from the driver-provisioning machinery — the layout
195
/// mirror of `azul_dll::unified::video_codec::provision::VideoStartupCheck`
196
/// (the dialogs live BELOW the dll, so the dll hands them fn pointers
197
/// instead of the type).
198
// Four independent readiness flags — that IS the report.
199
#[allow(clippy::struct_excessive_bools)]
200
#[derive(Debug, Clone, Default, PartialEq, Eq)]
201
pub struct GpuProvisionReport {
202
    /// Hardware video decode is usable right now.
203
    pub hw_decode_ready: bool,
204
    /// A fresh boot reaches a usable desktop (bootable kernel AND a display
205
    /// that lights up). `false` is URGENT — the machine is one reboot away
206
    /// from an initramfs shell or a black screen.
207
    pub boot_safe: bool,
208
    /// An automatic remediation exists (driver install and/or kernel repair).
209
    pub can_remediate: bool,
210
    /// Applying the remediation will require a reboot.
211
    pub needs_reboot: bool,
212
    /// One-line status.
213
    pub summary: String,
214
    /// Full multi-line report, including the exact commands a remediation
215
    /// would run — this is what the user consents to.
216
    pub detail: String,
217
}
218

            
219
/// What a remediation did — the mirror of `VideoProvisionOutcome`.
220
#[derive(Debug, Clone, Default, PartialEq, Eq)]
221
pub struct GpuProvisionOutcome {
222
    /// Everything applied cleanly.
223
    pub ok: bool,
224
    /// A reboot is needed before the change takes effect.
225
    pub reboot_required: bool,
226
    /// Human-readable result.
227
    pub message: String,
228
}
229

            
230
/// Progress sink a remediation reports through:
231
/// `(commands_finished, total, running_command)`.
232
pub type GpuProvisionProgressFn<'a> = &'a mut dyn FnMut(usize, usize, &str);
233

            
234
/// The dll's provisioning entry points, published by `App::run`. `check` is
235
/// INSPECTION ONLY; `remediate` is side-effecting (pkexec) and must never be
236
/// called without explicit user consent.
237
#[derive(Debug, Copy, Clone)]
238
pub struct GpuProvisionHooks {
239
    /// Runs the readiness checks. Blocking — call it on a thread.
240
    pub check: fn() -> GpuProvisionReport,
241
    /// Applies what `check` found. Blocking, side-effecting, consent-gated.
242
    /// Reports progress before each command it runs:
243
    /// `on_step(commands_finished, total, running_command)`.
244
    pub remediate: fn(GpuProvisionProgressFn<'_>) -> GpuProvisionOutcome,
245
}
246

            
247
static GPU_PROVISION: RwLock<Option<GpuProvisionHooks>> = RwLock::new(None);
248

            
249
/// Publishes the provisioning hooks (called by `App::run`).
250
pub fn set_gpu_provision_hooks(hooks: GpuProvisionHooks) {
251
    if let Ok(mut slot) = GPU_PROVISION.write() {
252
        *slot = Some(hooks);
253
    }
254
}
255

            
256
/// The provisioning hooks, if a shell published them.
257
#[must_use]
258
pub fn gpu_provision_hooks() -> Option<GpuProvisionHooks> {
259
    GPU_PROVISION.read().ok().and_then(|slot| *slot)
260
}