-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontroller.rs
More file actions
407 lines (369 loc) · 14.1 KB
/
Copy pathcontroller.rs
File metadata and controls
407 lines (369 loc) · 14.1 KB
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
//! The [`Controller`] owns the single source of truth ([`AppState`]) and
//! broadcasts immutable snapshots to every subscribed frontend.
//!
//! Both the TUI and the GUI register a subscriber that marshals the snapshot
//! into their own event loop, so a change made in one frontend (e.g. selecting a
//! device via the serial console) is immediately reflected in the other (the
//! on-device screen). All mutation goes through methods on `Controller`, which
//! lock the state, apply the change and then [`Controller::notify`] subscribers.
use std::sync::{Arc, Mutex};
use crate::core::model::*;
use crate::core::{board, catalog, install, removable};
/// Runtime configuration for the installer.
#[derive(Clone, Debug)]
pub struct Config {
/// Base URL of the image server, e.g. `https://images.flipperos.example`.
pub server_url: String,
/// When true, destructive operations are logged but not executed.
pub dry_run: bool,
/// DRM/KMS device node for the on-device screen.
pub kms_device: String,
/// When true, the GUI logs each keypress to stderr (input debugging). Off by
/// default so nothing garbles the TUI on a shared serial/kernel console.
pub debug_keys: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
server_url: "https://dl-linux-images.flipp.dev".to_string(),
dry_run: true,
kms_device: "/dev/dri/by-path/platform-2acf0000.spi-cs-0-card".to_string(),
debug_keys: false,
}
}
}
/// A callback invoked with a fresh snapshot every time the state changes.
type Subscriber = Box<dyn Fn(AppState) + Send + 'static>;
pub struct Controller {
state: Mutex<AppState>,
subscribers: Mutex<Vec<Subscriber>>,
config: Config,
}
impl Controller {
pub fn new(config: Config) -> Arc<Self> {
Arc::new(Self {
state: Mutex::new(AppState::default()),
subscribers: Mutex::new(Vec::new()),
config,
})
}
pub fn config(&self) -> &Config {
&self.config
}
/// Register a frontend subscriber. It is immediately called once with the
/// current snapshot so the frontend can render its initial state.
pub fn subscribe<F>(&self, f: F)
where
F: Fn(AppState) + Send + 'static,
{
let snapshot = self.snapshot();
f(snapshot);
self.subscribers.lock().unwrap().push(Box::new(f));
}
/// Cheap immutable copy of the current state.
pub fn snapshot(&self) -> AppState {
self.state.lock().unwrap().clone()
}
/// Broadcast the current state to every subscriber.
fn notify(&self) {
let snapshot = self.state.lock().unwrap().clone();
for sub in self.subscribers.lock().unwrap().iter() {
sub(snapshot.clone());
}
}
/// Apply a mutation under the lock, then notify subscribers.
fn update<F: FnOnce(&mut AppState)>(&self, f: F) {
{
let mut state = self.state.lock().unwrap();
f(&mut state);
}
self.notify();
}
/// Append a line to the shared activity log.
pub fn log(&self, line: impl Into<String>) {
let line = line.into();
log::info!("{line}");
self.update(|s| {
s.log.push(line);
const MAX: usize = 500;
if s.log.len() > MAX {
let drop = s.log.len() - MAX;
s.log.drain(0..drop);
}
});
}
pub fn set_progress(&self, progress: f32) {
self.update(|s| s.progress = progress.clamp(0.0, 1.0));
}
pub fn set_phase(&self, phase: Phase) {
self.update(|s| s.phase = phase);
}
// --- Discovery -------------------------------------------------------
/// Probe the board and enumerate local storage. Safe to run on a worker
/// thread; it only reads sysfs / device-tree.
pub fn discover(&self) {
self.set_phase(Phase::Discovering);
self.log("discovering board identity…");
let board = board::detect();
self.log(format!(
"board: {} ({}, id={})",
board.model, board.soc, board.board_id
));
self.update(|s| s.board = board);
self.log("enumerating boot-ROM capable storage…");
let devices = storage_list();
for d in &devices {
self.log(format!(
" found {} — boot-capable: {}",
d.summary(),
d.boot_rom_capable()
));
}
self.update(|s| {
s.devices = devices;
// Auto-select a single obvious target (first boot-capable, non-removable).
if s.selection.target_device.is_none() {
if let Some(dev) = s
.devices
.iter()
.find(|d| d.boot_rom_capable() && !d.removable)
{
s.selection.target_device = Some(dev.path.clone());
}
}
});
}
/// Query the image server and any removable-media mirror for U-Boot and
/// snapshot builds, newest first.
pub fn refresh_sources(&self) {
let board_id = self.snapshot().board.board_id;
const LIMIT: usize = 100;
let server = catalog::Origin::Server {
base: self.config.server_url.clone(),
};
// Pull the list of device types the server can install from the latest
// U-Boot manifest, and choose the per-board U-Boot directory that matches
// our detected device type (falling back to the generic build otherwise).
let supported = catalog::supported_device_types(&server);
if !supported.is_empty() {
self.log(format!(
"server supports device type(s): {}",
supported.join(", ")
));
}
let board_dir: String = if supported.iter().any(|t| t == &board_id) {
board_id.clone()
} else {
if !supported.is_empty() {
self.log(format!(
"device type '{board_id}' not offered by server; using generic U-Boot"
));
}
catalog::board_dir(&board_id).to_string()
};
self.update(|s| s.supported_device_types = supported.clone());
let mut origins: Vec<catalog::Origin> = vec![server];
for (device, root) in removable::media_roots() {
origins.push(catalog::Origin::Media { device, root });
}
self.log("querying image catalog…");
let mut uboot_builds: Vec<UbootBuild> = Vec::new();
let mut snapshot_builds: Vec<SnapshotBuild> = Vec::new();
for origin in &origins {
uboot_builds.extend(catalog::uboot_builds(origin, &board_dir, LIMIT));
snapshot_builds.extend(catalog::snapshot_builds(origin, LIMIT));
}
// Newest first across all origins, then cap.
uboot_builds.sort_by(|a, b| b.mtime.cmp(&a.mtime));
snapshot_builds.sort_by(|a, b| b.mtime.cmp(&a.mtime));
uboot_builds.truncate(LIMIT);
snapshot_builds.truncate(LIMIT);
self.log(format!(
"catalog: {} u-boot build(s), {} snapshot build(s)",
uboot_builds.len(),
snapshot_builds.len()
));
self.update(|s| {
s.uboot_builds = uboot_builds;
s.snapshot_builds = snapshot_builds;
if s.selection.uboot.is_none() {
if let Some(b) = s.uboot_builds.first() {
s.selection.uboot = Some(b.id.clone());
}
}
if s.selection.snapshot_build.is_none() {
if let Some(b) = s.snapshot_builds.first() {
s.selection.snapshot_build = Some(b.id.clone());
}
}
if matches!(s.phase, Phase::Discovering) {
s.phase = Phase::Ready;
}
});
// Load the profiles of the auto-selected build so the UI can populate.
if let Some(id) = self.snapshot().selection.snapshot_build.clone() {
self.load_profiles(&id);
}
}
/// Fetch and store the per-profile packs for a snapshot build.
fn load_profiles(&self, id: &str) {
let build = match self
.snapshot()
.snapshot_builds
.iter()
.find(|b| b.id == id)
.cloned()
{
Some(b) => b,
None => return,
};
if build.loaded {
return;
}
self.log(format!("loading profiles for {}…", build.label));
match catalog::load_profiles(&build) {
Ok((number, profiles, home_pack)) => {
self.log(format!("{} profile(s) available", profiles.len()));
self.update(|s| {
if let Some(b) = s.snapshot_builds.iter_mut().find(|b| b.id == id) {
b.profiles = profiles;
b.build_number = number;
b.home_pack = home_pack;
b.loaded = true;
// The build number now surfaces via `display_name()`; no
// need to splice it into the label.
}
});
}
Err(e) => self.log(format!("failed to load profiles: {e}")),
}
}
/// Fetch the U-Boot build's manifest details for the popup. Blocking, so
/// call it from a worker thread; a no-op if already loaded or unknown.
pub fn load_uboot_details(&self, id: &str) {
let loc = {
let s = self.state.lock().unwrap();
match s.uboot_builds.iter().find(|b| b.id == id) {
Some(b) if b.details.is_none() => b.manifest_location.clone(),
_ => return,
}
};
match catalog::load_details(&loc) {
Ok(d) => self.update(|s| {
if let Some(b) = s.uboot_builds.iter_mut().find(|b| b.id == id) {
b.details = Some(d);
}
}),
Err(e) => self.log(format!("u-boot details: {e}")),
}
}
/// Fetch the snapshot build's manifest details for the popup. Blocking, so
/// call it from a worker thread; a no-op if already loaded or unknown.
pub fn load_snapshot_details(&self, id: &str) {
let loc = {
let s = self.state.lock().unwrap();
match s.snapshot_builds.iter().find(|b| b.id == id) {
Some(b) if b.details.is_none() => {
format!("{}manifest.json", b.base_location)
}
_ => return,
}
};
match catalog::load_details(&loc) {
Ok(d) => self.update(|s| {
if let Some(b) = s.snapshot_builds.iter_mut().find(|b| b.id == id) {
b.details = Some(d);
}
}),
Err(e) => self.log(format!("rootfs details: {e}")),
}
}
// --- Selection actions (shared by both frontends) --------------------
pub fn select_device(&self, path: &str) {
self.update(|s| s.selection.target_device = Some(path.to_string()));
}
pub fn select_uboot(&self, id: &str) {
self.update(|s| s.selection.uboot = Some(id.to_string()));
}
/// Select a snapshot build, resetting the extra-profile selection, and load
/// its profiles in the background if not already loaded.
pub fn select_snapshot_build(self: &Arc<Self>, id: &str) {
self.update(|s| {
s.selection.snapshot_build = Some(id.to_string());
s.selection.profiles.clear();
});
let loaded = self
.snapshot()
.snapshot_builds
.iter()
.find(|b| b.id == id)
.map(|b| b.loaded)
.unwrap_or(true);
if loaded {
return;
}
let this = Arc::clone(self);
let id = id.to_string();
std::thread::spawn(move || this.load_profiles(&id));
}
/// Toggle an extra profile on/off. Minimal is always deployed and cannot be
/// toggled.
pub fn toggle_profile(&self, name: &str, on: bool) {
if name.eq_ignore_ascii_case("minimal") {
return;
}
self.update(|s| {
s.selection.profiles.retain(|p| p != name);
if on {
s.selection.profiles.push(name.to_string());
}
});
}
/// Select all extra profiles of the current build, or none.
pub fn select_all_profiles(&self, on: bool) {
self.update(|s| {
let names: Vec<String> = if on {
s.selected_build()
.map(|b| b.extra_profiles().map(|p| p.name.clone()).collect())
.unwrap_or_default()
} else {
Vec::new()
};
s.selection.profiles = names;
});
}
// --- Installation ----------------------------------------------------
/// Kick off the installation on a background thread. Progress and log
/// updates are pushed to both frontends via the subscriber mechanism.
pub fn start_install(self: &Arc<Self>) {
{
let state = self.state.lock().unwrap();
if !state.can_install() {
drop(state);
self.log("cannot start install: incomplete selection");
return;
}
}
let this = Arc::clone(self);
std::thread::spawn(move || {
this.set_phase(Phase::Installing);
this.set_progress(0.0);
match install::run(&this) {
Ok(()) => {
this.set_progress(1.0);
this.set_phase(Phase::Done);
this.log("installation complete");
}
Err(e) => {
this.log(format!("installation failed: {e}"));
this.set_phase(Phase::Failed(e.to_string()));
}
}
});
}
}
/// Enumerate local storage; kept as a free function so tests and the
/// [`Controller`] share one implementation.
fn storage_list() -> Vec<StorageDevice> {
crate::core::storage::enumerate(crate::core::storage::MIN_TARGET_SIZE_BYTES)
}