aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/designer_projects.rs
blob: 1b73a88016ddf9bb316ddfb96738535d6fa9724d (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
107
108
109
110
111
//! The original designer's named Unit DAT files under the game root.

use fparkan_runtime::{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: 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, '_' | '-' | ' ')
}

fn internal_name(value: &str) -> bool {
    ["temp_unit", "bld_unit_", "view_unit_"]
        .iter()
        .any(|prefix| value.starts_with(prefix))
}

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());
    if name.is_empty()
        || name.chars().count() > NAME_LIMIT
        || !name.chars().all(name_character)
        || device
        || internal_name(&folded)
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "invalid Unit DAT name",
        ));
    }
    let filename = format!("{name}.dat");
    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)],
) -> 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 path
            .extension()
            .is_none_or(|ext| !ext.eq_ignore_ascii_case("dat"))
            || internal_name(&name.to_ascii_lowercase())
            || !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;
            }
        };
        if let Some((scheme, changes)) = restore_factory_design(
            engine,
            cockpit,
            choices.iter().map(|&(_, scheme)| scheme),
            &bytes,
        ) {
            if let Some(&(choice, _)) = choices.iter().find(|&&(_, index)| index == scheme) {
                projects.push(SavedProject {
                    name: name.to_owned(),
                    choice,
                    changes,
                });
            }
        }
    }
    projects.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase()));
    Ok(projects)
}