aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/designer_projects.rs
blob: 1a485fee8f89b033dccbd67897d1cffe78682b88 (plain) (blame)
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
//! The original designer's named Unit DAT files under the game root.

use fparkan_runtime::{
    is_saved_factory_project_name, restore_factory_design, Engine, FactoryPartChange,
    StartingCockpit,
};
use std::{fs, io, io::Write, path::Path};

pub(super) const NAME_LIMIT: usize = 16;

pub(super) struct SavedProject {
    pub(super) name: String,
    pub(super) choice: Option<usize>,
    pub(super) scheme: usize,
    pub(super) changes: Vec<FactoryPartChange>,
}

pub(super) enum ProjectDialog {
    Save {
        name: String,
    },
    Load {
        projects: Vec<SavedProject>,
        first: usize,
    },
}

pub(super) fn name_character(value: char) -> bool {
    value.is_alphanumeric() || matches!(value, '_' | '-' | ' ')
}

pub(super) fn save_project(directory: &Path, name: &str, bytes: &[u8]) -> io::Result<String> {
    let name = name.trim();
    let folded = name.to_ascii_lowercase();
    let device = matches!(folded.as_str(), "con" | "aux" | "nul" | "prn")
        || (folded.len() == 4
            && (folded.starts_with("com") || folded.starts_with("lpt"))
            && folded.as_bytes()[3].is_ascii_digit());
    let filename = format!("{name}.dat");
    if name.is_empty()
        || name.chars().count() > NAME_LIMIT
        || !name.chars().all(name_character)
        || device
        || !is_saved_factory_project_name(&filename)
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "invalid Unit DAT name",
        ));
    }
    let path = directory.join(&filename);
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)?;
    if let Err(error) = file.write_all(bytes).and_then(|()| file.sync_all()) {
        drop(file);
        let _ = fs::remove_file(&path);
        return Err(error);
    }
    Ok(filename)
}

pub(super) fn browse_projects(
    directory: &Path,
    engine: &Engine,
    cockpit: StartingCockpit,
    choices: &[(usize, usize)],
    prepared: &[usize],
) -> io::Result<Vec<SavedProject>> {
    let mut projects = Vec::new();
    for entry in fs::read_dir(directory)? {
        let entry = entry?;
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
            continue;
        };
        if !is_saved_factory_project_name(name) || !entry.file_type()?.is_file() {
            continue;
        }
        let bytes = match fs::read(&path) {
            Ok(bytes) => bytes,
            Err(error) => {
                eprintln!("designer_project_unreadable file={name:?} {error}");
                continue;
            }
        };
        let schemes = choices
            .iter()
            .map(|&(_, scheme)| scheme)
            .chain(prepared.iter().copied());
        if let Some((scheme, changes)) = restore_factory_design(engine, cockpit, schemes, &bytes) {
            let choice = choices
                .iter()
                .find_map(|&(choice, index)| (index == scheme).then_some(choice));
            projects.push(SavedProject {
                name: name.to_owned(),
                choice,
                scheme,
                changes,
            });
        }
    }
    projects.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase()));
    Ok(projects)
}