1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
use super::{HardwareCapabilities, PerformanceLevel, UserOverrides};
use crate::gpu::{GpuAdapter, GpuType};
use crate::style::MenuEffects;
/// Menu system configuration with hardware-adaptive features.
#[derive(Debug, Clone)]
pub struct MenuConfig {
/// Master switch: whether this configuration is applied to the menu controls.
///
/// # Why it defaults to on
///
/// The module exists to make menus adapt to the host, so its policy is the product
/// default. The switch remains as a host escape hatch: a host that wants the exact
/// pre-adaptive rendering can turn the policy off in one call instead of resetting
/// eight effects. (Verification paths pin a deterministic policy instead; see
/// [`MenuConfig::verification`].)
enabled: bool,
/// Whether animations are enabled.
animations_enabled: bool,
/// Whether transparency effects are enabled.
transparency_enabled: bool,
/// Whether shadows are enabled.
shadows_enabled: bool,
/// Whether blur effects are enabled.
blur_enabled: bool,
/// Animation duration multiplier (1.0 = normal, 0.5 = fast, 2.0 = slow).
animation_speed: f32,
/// Maximum menu items before scrolling.
max_visible_items: u32,
/// Whether to use hardware-accelerated rendering.
hardware_acceleration: bool,
/// Whether to enable menu caching.
caching_enabled: bool,
/// User override flags.
pub(crate) user_overrides: UserOverrides,
/// Auto-detected hardware capabilities.
pub(crate) hardware_caps: HardwareCapabilities,
}
impl MenuConfig {
/// The deterministic policy used by verification paths.
///
/// # Why a pinned policy is required
///
/// [`MenuConfig::new`] adapts to the host, and the snapshot set is committed: if the
/// exported SVG depended on the exporter's GPU or battery, two contributors would
/// regenerate different bytes from the same source. The snapshot/ census paths
/// therefore install this record, whose values model a mid-range desktop.
pub fn verification() -> Self {
let mut config = Self {
enabled: true,
animations_enabled: false,
transparency_enabled: false,
shadows_enabled: false,
blur_enabled: false,
animation_speed: 1.0,
max_visible_items: 20,
hardware_acceleration: false,
caching_enabled: false,
user_overrides: UserOverrides::default(),
hardware_caps: HardwareCapabilities::verification(),
};
// Derived rather than restated: the pinned policy is exactly what the pinned
// capability record implies, so the two cannot drift apart.
config.apply_hardware_defaults();
config
}
/// Creates a new menu configuration from the host's detected capabilities.
///
/// The master switch starts **on**: the adaptive policy is the product default. Use
/// [`Self::verification`] instead wherever the result must not depend on the host
/// (snapshot export, rendering census).
pub fn new() -> Self {
let hardware_caps = Self::detect_hardware_capabilities();
let mut config = Self {
enabled: true,
animations_enabled: false,
transparency_enabled: false,
shadows_enabled: false,
blur_enabled: false,
animation_speed: 1.0,
max_visible_items: 20,
hardware_acceleration: false,
caching_enabled: false,
user_overrides: UserOverrides::default(),
hardware_caps,
};
config.apply_hardware_defaults();
config
}
fn detect_hardware_capabilities() -> HardwareCapabilities {
let gpu_type = GpuAdapter::detect_primary_gpu_type().unwrap_or(GpuType::Integrated);
// `None` means no source could report VRAM, which is the honest answer here:
// wgpu exposes no memory size and the platform backends report system RAM
// only. `assumed_gpu_memory` supplies the figure the scoring model needs
// without letting that figure pose as a measurement.
let gpu_memory_mb = Self::detect_gpu_memory();
let gpu_memory_is_measured = gpu_memory_mb.is_some();
let gpu_performance_score = Self::estimate_gpu_performance(
&gpu_type,
gpu_memory_mb.unwrap_or_else(|| Self::assumed_gpu_memory(&gpu_type)),
);
let system_ram_mb = Self::detect_system_memory();
let cpu_performance_score = Self::estimate_cpu_performance();
let on_battery = Self::detect_battery_status();
let performance_level = if gpu_performance_score >= 70 && !on_battery {
PerformanceLevel::High
} else if gpu_performance_score >= 40 {
PerformanceLevel::Medium
} else {
PerformanceLevel::Low
};
HardwareCapabilities {
gpu_type,
gpu_memory_mb,
gpu_memory_is_measured,
gpu_performance_score,
system_ram_mb,
cpu_performance_score,
on_battery,
performance_level,
}
}
/// The GPU's memory, or `None` when no source on this host can report it.
///
/// The environment override is the one real source available: a host or
/// deployment that knows its VRAM can state it without this crate pretending to
/// have probed the driver. Absent that, the answer is `None` — returning a
/// constant made the value indistinguishable from a measurement.
fn detect_gpu_memory() -> Option<u32> {
std::env::var("RUST_WIDGETS_GPU_MEMORY_MB")
.ok()
.and_then(|val| val.parse::<u32>().ok())
.filter(|mb| *mb > 0)
}
/// Test-only view of [`Self::detect_gpu_memory`], so the "unknown stays unknown"
/// contract can be asserted without making the production helper public.
#[cfg(test)]
pub(crate) fn detect_gpu_memory_for_test() -> Option<u32> {
Self::detect_gpu_memory()
}
/// The conservative VRAM assumption used only for scoring, never reported.
///
/// Separated from [`Self::detect_gpu_memory`] so the number a *score* is computed
/// from cannot leak into a user-visible description as if it had been detected.
pub(crate) fn assumed_gpu_memory(gpu_type: &GpuType) -> u32 {
match gpu_type {
GpuType::Discrete => 4096,
GpuType::Integrated => 512,
GpuType::Cpu => 0,
}
}
fn estimate_gpu_performance(gpu_type: &GpuType, memory_mb: u32) -> u32 {
match gpu_type {
GpuType::Discrete => {
let base_score = 70;
let memory_bonus = (memory_mb / 1024).min(20);
base_score + memory_bonus
}
GpuType::Integrated => {
let base_score = 40;
let memory_bonus = (memory_mb / 512).min(20);
base_score + memory_bonus
}
GpuType::Cpu => 20,
}
}
/// The machine's physical memory, or `None` when the active backend cannot
/// report it.
///
/// The probe is asked of the active platform backend rather than read from
/// `/proc` here (principles #36/#37). `None` is passed through unchanged: an
/// earlier revision substituted a `4096` constant, which made an unknown amount
/// of memory indistinguishable from a measured one — the same defect
/// [`Self::detect_gpu_memory`] had already been fixed for. The scoring model uses
/// [`Self::assumed_system_memory`] instead, which never reaches a caller.
fn detect_system_memory() -> Option<u64> {
crate::platform::platform_facts().total_memory_mb()
}
/// The conservative RAM assumption used only for scoring, never reported.
///
/// Separated from [`Self::detect_system_memory`] for the same reason
/// [`Self::assumed_gpu_memory`] is separated from `detect_gpu_memory`: the number a
/// *score* is computed from must not be publishable as if it had been measured.
pub(crate) fn assumed_system_memory() -> u64 {
4096
}
fn estimate_cpu_performance() -> u32 {
match std::thread::available_parallelism() {
Ok(count) => {
let cores = count.get();
match cores {
0..=2 => 30,
3..=4 => 50,
5..=8 => 70,
_ => 90,
}
}
Err(_) => 50,
}
}
fn detect_battery_status() -> bool {
// Whether a battery is draining is an OS fact; ask the backend instead of
// walking `/sys/class/power_supply` from this layer. The trait default is
// `false`, which selects the non-throttled defaults. See principle #36/#37.
crate::platform::platform_facts().is_on_battery()
}
fn apply_hardware_defaults(&mut self) {
match self.hardware_caps.performance_level {
PerformanceLevel::High => {
self.animations_enabled = true;
self.transparency_enabled = true;
self.shadows_enabled = true;
self.blur_enabled = true;
self.animation_speed = 1.0;
self.max_visible_items = 25;
self.hardware_acceleration = true;
self.caching_enabled = true;
}
PerformanceLevel::Medium => {
self.animations_enabled = true;
self.transparency_enabled = true;
self.shadows_enabled = false;
self.blur_enabled = false;
self.animation_speed = 0.8;
self.max_visible_items = 20;
self.hardware_acceleration = true;
self.caching_enabled = true;
}
PerformanceLevel::Low => {
self.animations_enabled = false;
self.transparency_enabled = false;
self.shadows_enabled = false;
self.blur_enabled = false;
self.animation_speed = 0.5;
self.max_visible_items = 15;
self.hardware_acceleration = false;
self.caching_enabled = false;
}
}
}
/// Applies user overrides to the configuration.
pub fn apply_user_overrides(&mut self) {
if let Some(enabled) = self.user_overrides.enabled {
self.enabled = enabled;
}
if let Some(animations) = self.user_overrides.animations {
self.animations_enabled = animations;
}
if let Some(transparency) = self.user_overrides.transparency {
self.transparency_enabled = transparency;
}
if let Some(shadows) = self.user_overrides.shadows {
self.shadows_enabled = shadows;
}
if let Some(blur) = self.user_overrides.blur {
self.blur_enabled = blur;
}
if let Some(speed) = self.user_overrides.animation_speed {
match Self::sanitize_animation_speed(speed) {
Some(sanitized) => {
self.animation_speed = sanitized;
self.user_overrides.animation_speed = Some(sanitized);
}
// A persisted NaN is not a usable preference: drop it so it cannot
// claim an override or be re-saved as a poison value.
None => self.user_overrides.animation_speed = None,
}
}
if let Some(max_items) = self.user_overrides.max_visible_items {
self.max_visible_items = max_items.max(5);
}
if let Some(hw_accel) = self.user_overrides.hardware_acceleration {
self.hardware_acceleration = hw_accel;
}
if let Some(caching) = self.user_overrides.caching {
self.caching_enabled = caching;
}
}
/// Resets to hardware defaults, clearing user overrides.
///
/// The master switch returns to its own default (**on**): resetting the policy is
/// not the same as opting out of it.
pub fn reset_to_defaults(&mut self) {
self.user_overrides = UserOverrides::default();
self.apply_hardware_defaults();
self.enabled = true;
}
/// Replaces the override set and re-applies it over a fresh hardware baseline.
///
/// Restoring the baseline first is what makes a field *removed* from the persisted
/// override set fall back to its hardware default, instead of keeping the live value
/// a previous load had set. [`Self::apply_user_overrides`] alone would only touch
/// the fields that still have an override, leaving deleted ones stuck on a stale
/// preference (the "deleted field stays reversed" defect).
pub(crate) fn reload_overrides(&mut self, overrides: UserOverrides) {
self.user_overrides = overrides;
self.apply_hardware_defaults();
self.apply_user_overrides();
}
/// Sanitizes an animation speed into `0.1 ..= 3.0`, returning `None` for NaN.
///
/// `f32::clamp` saturates finite and infinite input correctly, but returns its NaN
/// input unchanged (both bound comparisons are false for NaN). Rejecting NaN here —
/// instead of letting it through — is what keeps the getter's `0.1..=3.0` contract
/// intact no matter which entry point supplied the number.
fn sanitize_animation_speed(speed: f32) -> Option<f32> {
if speed.is_nan() {
return None;
}
Some(speed.clamp(0.1, 3.0))
}
/// Whether menu animations are enabled. Set by [`MenuConfig::new`] from the
/// detected performance level, or overridden by the user.
pub fn animations_enabled(&self) -> bool {
self.animations_enabled
}
/// Whether the adaptive configuration is applied at all.
pub fn is_enabled(&self) -> bool {
self.enabled
}
/// Turns the adaptive configuration on or off, recording it as a user override.
pub fn set_enabled(&mut self, enabled: bool) {
self.enabled = enabled;
self.user_overrides.enabled = Some(enabled);
}
/// The effect decisions a menu draw pass consumes.
///
/// When the master switch is off this is [`MenuEffects::legacy`] — the exact
/// pre-wiring rendering. When it is on, every field is the configured value.
pub fn effects(&self) -> MenuEffects {
if !self.enabled {
return MenuEffects::legacy();
}
MenuEffects {
enabled: true,
animations: self.animations_enabled,
animation_speed: self.animation_speed,
transparency: self.transparency_enabled,
shadows: self.shadows_enabled,
blur: self.blur_enabled,
max_visible_items: Some(self.max_visible_items.max(1)),
hardware_acceleration: self.hardware_acceleration,
caching: self.caching_enabled,
}
}
/// Whether transparent menu surfaces are enabled. Requires backend support;
/// the flag alone does not make a surface transparent.
pub fn transparency_enabled(&self) -> bool {
self.transparency_enabled
}
/// Whether drop shadows are enabled.
pub fn shadows_enabled(&self) -> bool {
self.shadows_enabled
}
/// Whether background blur is enabled. Blur is the most expensive of the
/// optional effects and is the first to be turned off when the detected
/// performance level drops.
pub fn blur_enabled(&self) -> bool {
self.blur_enabled
}
/// Returns the animation speed multiplier: `1.0` is normal, lower is faster
/// (for example `0.5` doubles the apparent rate). Always within
/// `0.1 ..= 3.0`.
pub fn animation_speed(&self) -> f32 {
self.animation_speed
}
/// Returns the number of menu items shown before the menu starts scrolling.
/// Always at least `5`.
pub fn max_visible_items(&self) -> u32 {
self.max_visible_items
}
/// Returns whether hardware-accelerated rendering should be used. This is a
/// request; the render backend may still fall back to software.
pub fn hardware_acceleration(&self) -> bool {
self.hardware_acceleration
}
/// Returns whether menu rendering results are cached across frames.
/// Disabled at the low performance level.
pub fn caching_enabled(&self) -> bool {
self.caching_enabled
}
/// Enables or disables the per-widget text-measurement cache.
pub fn set_caching_enabled(&mut self, enabled: bool) {
self.caching_enabled = enabled;
self.user_overrides.caching = Some(enabled);
}
/// Returns the hardware facts probed when this configuration was created.
/// These are a snapshot and are not re-probed by any setter.
pub fn hardware_caps(&self) -> &HardwareCapabilities {
&self.hardware_caps
}
/// Returns the explicit user overrides, or `None` per field where the user
/// has expressed no preference. These survive [`MenuConfig::reset_to_defaults`]
/// only until it clears them.
pub fn user_overrides(&self) -> &UserOverrides {
&self.user_overrides
}
/// Enables or disables animations and records the choice as a user
/// override, so a later [`MenuConfig::apply_user_overrides`] keeps it.
pub fn set_animations_enabled(&mut self, enabled: bool) {
self.user_overrides.animations = Some(enabled);
self.animations_enabled = enabled;
}
/// Enables or disables transparency and records the choice as a user
/// override.
pub fn set_transparency_enabled(&mut self, enabled: bool) {
self.user_overrides.transparency = Some(enabled);
self.transparency_enabled = enabled;
}
/// Enables or disables shadows and records the choice as a user override.
pub fn set_shadows_enabled(&mut self, enabled: bool) {
self.user_overrides.shadows = Some(enabled);
self.shadows_enabled = enabled;
}
/// Enables or disables background blur and records the choice as a user
/// override.
pub fn set_blur_enabled(&mut self, enabled: bool) {
self.user_overrides.blur = Some(enabled);
self.blur_enabled = enabled;
}
/// Sets the animation speed multiplier, clamped to `0.1 ..= 3.0`.
///
/// Non-finite (NaN) input is rejected rather than stored: neither the stored
/// override nor the live value changes, so the getter's `0.1..=3.0` contract
/// holds. Finite out-of-range input and ±Inf are silently saturated. Records
/// the choice as a user override.
pub fn set_animation_speed(&mut self, speed: f32) {
let Some(speed) = Self::sanitize_animation_speed(speed) else {
return;
};
self.user_overrides.animation_speed = Some(speed);
self.animation_speed = speed;
}
/// Sets how many items are shown before scrolling, floored at `5`.
///
/// An input below `5` is raised rather than rejected. Records the choice as
/// a user override.
pub fn set_max_visible_items(&mut self, max: u32) {
self.user_overrides.max_visible_items = Some(max.max(5));
self.max_visible_items = max.max(5);
}
/// Requests (or suppresses) hardware acceleration and records the choice as
/// a user override.
pub fn set_hardware_acceleration(&mut self, enabled: bool) {
self.user_overrides.hardware_acceleration = Some(enabled);
self.hardware_acceleration = enabled;
}
/// Returns a user-friendly description of current settings.
pub fn settings_summary(&self) -> String {
format!(
"Menu Settings:\n\
- Configuration: {}\n\
- Animations: {}\n\
- Transparency: {}\n\
- Shadows: {}\n\
- Blur: {}\n\
- Animation Speed: {:.1}x\n\
- Max Visible Items: {}\n\
- Hardware Acceleration: {}\n\
- Performance Level: {:?}",
if self.enabled { "On" } else { "Off" },
if self.animations_enabled { "On" } else { "Off" },
if self.transparency_enabled { "On" } else { "Off" },
if self.shadows_enabled { "On" } else { "Off" },
if self.blur_enabled { "On" } else { "Off" },
self.animation_speed,
self.max_visible_items,
if self.hardware_acceleration { "On" } else { "Off" },
self.hardware_caps.performance_level
)
}
/// Returns true if any user overrides are active.
pub fn has_user_overrides(&self) -> bool {
self.user_overrides.enabled.is_some()
|| self.user_overrides.animations.is_some()
|| self.user_overrides.transparency.is_some()
|| self.user_overrides.shadows.is_some()
|| self.user_overrides.blur.is_some()
|| self.user_overrides.animation_speed.is_some()
|| self.user_overrides.max_visible_items.is_some()
|| self.user_overrides.hardware_acceleration.is_some()
|| self.user_overrides.caching.is_some()
}
pub(crate) fn apply_battery_adaptive_reduction(&mut self) {
if self.user_overrides.animations.is_none() {
self.animations_enabled = false;
}
if self.user_overrides.transparency.is_none() {
self.transparency_enabled = false;
}
if self.user_overrides.blur.is_none() {
self.blur_enabled = false;
}
}
}
crate::impl_default_via_new!(MenuConfig);