summaryrefslogtreecommitdiff
path: root/crates/flasher-qt/src/main.rs
blob: f131bc539d7120ccfc0db7cf20114ad2e0d40eac (plain)
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
use qmetaobject::{QmlEngine, QString, QVariant};
use std::fs;

const BOARDS: &str = include_str!("../../../alt-rootfs-installer/SUPPORTED-BOARDS");
const QML: &str = include_str!("../qml/Main.qml");

fn main() {
    let mut engine = QmlEngine::new();
    engine.set_property(
        QString::from("supportedBoardsText"),
        QVariant::from(QString::from(BOARDS)),
    );
    engine.set_property(
        QString::from("availableDrivesText"),
        QVariant::from(QString::from(available_drives().join("\n"))),
    );
    engine.load_data(QML.into());
    engine.exec();
}

fn available_drives() -> Vec<String> {
    let mut drives = Vec::new();
    let Ok(entries) = fs::read_dir("/sys/block") else {
        return drives;
    };

    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().into_owned();
        if name.starts_with("loop") || name.starts_with("ram") || name.starts_with("zram") {
            continue;
        }
        let removable = fs::read_to_string(entry.path().join("removable"))
            .map(|value| value.trim() == "1")
            .unwrap_or(false);
        if !removable && !name.starts_with("mmcblk") {
            continue;
        }

        let sectors = fs::read_to_string(entry.path().join("size"))
            .ok()
            .and_then(|value| value.trim().parse::<u64>().ok())
            .unwrap_or(0);
        let model = fs::read_to_string(entry.path().join("device/model"))
            .unwrap_or_default()
            .trim()
            .to_owned();
        let description = if model.is_empty() {
            format!("/dev/{name}")
        } else {
            model
        };
        drives.push(format!(
            "{description}  ·  {}  ·  /dev/{name}",
            format_size(sectors.saturating_mul(512))
        ));
    }
    drives.sort();
    drives
}

fn format_size(bytes: u64) -> String {
    const GIB: f64 = 1024.0 * 1024.0 * 1024.0;
    const MIB: f64 = 1024.0 * 1024.0;
    if bytes as f64 >= GIB {
        format!("{:.1} GB", bytes as f64 / GIB)
    } else {
        format!("{:.0} MB", bytes as f64 / MIB)
    }
}