summaryrefslogtreecommitdiff
path: root/crates/flasher-qt/src/main.rs
blob: 243406bd73dbe7cde86e7c6dae806040b5071024 (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
70
71
72
73
74
75
76
use cxx_qt_lib::{QByteArray, QGuiApplication, QQmlApplicationEngine, QString, QUrl};
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 app = QGuiApplication::new();
    app.pin_mut()
        .set_application_name(&QString::from("ALT Image Writer"));
    app.pin_mut()
        .set_organization_name(&QString::from("ALT Linux"));
    app.pin_mut()
        .set_application_version(&QString::from(env!("CARGO_PKG_VERSION")));

    let boards = serde_json::to_string(BOARDS).expect("serialize supported boards");
    let drives = serde_json::to_string(&available_drives().join("\n"))
        .expect("serialize available drives");
    let qml = QML
        .replace("@SUPPORTED_BOARDS@", &boards)
        .replace("@AVAILABLE_DRIVES@", &drives);

    let mut engine = QQmlApplicationEngine::new();
    engine
        .pin_mut()
        .load_data(&QByteArray::from(qml.as_str()), &QUrl::default());
    app.pin_mut().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)
    }
}