Skip to main content

effindom_native_packaging/
metadata.rs

1use crate::icon_encoding::encode_png;
2use crate::{Error, IconArtifact, IconRasterSet, Result};
3use std::path::PathBuf;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub struct NativeVersion {
7    pub major: u16,
8    pub minor: u16,
9    pub patch: u16,
10    pub build: u16,
11}
12
13impl NativeVersion {
14    pub const fn new(major: u16, minor: u16, patch: u16, build: u16) -> Self {
15        Self {
16            major,
17            minor,
18            patch,
19            build,
20        }
21    }
22
23    fn dotted(self) -> String {
24        format!("{}.{}.{}", self.major, self.minor, self.patch)
25    }
26}
27
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct ApplicationMetadata {
30    pub executable_name: String,
31    pub display_version: String,
32    pub native_version: NativeVersion,
33    pub caption: String,
34    pub identifier: String,
35}
36
37impl ApplicationMetadata {
38    pub fn new(
39        executable_name: impl Into<String>,
40        display_version: impl Into<String>,
41        native_version: NativeVersion,
42        caption: impl Into<String>,
43        identifier: impl Into<String>,
44    ) -> Result<Self> {
45        let metadata = Self {
46            executable_name: executable_name.into(),
47            display_version: display_version.into(),
48            native_version,
49            caption: caption.into(),
50            identifier: identifier.into(),
51        };
52        validate_metadata(&metadata)?;
53        Ok(metadata)
54    }
55}
56
57pub fn encode_application_icon_png(rasters: &IconRasterSet) -> Result<IconArtifact> {
58    let raster = rasters.get(256).ok_or(Error::MissingIconRaster(256))?;
59    Ok(IconArtifact {
60        relative_path: PathBuf::from("app/application-icon.png"),
61        bytes: encode_png(raster)?,
62    })
63}
64
65pub fn encode_macos_info_plist(
66    metadata: &ApplicationMetadata,
67    minimum_version: Option<&str>,
68) -> Result<IconArtifact> {
69    validate_metadata(metadata)?;
70    if minimum_version.is_some_and(|version| version.trim().is_empty()) {
71        return Err(invalid_metadata(
72            "macos.minimum-version",
73            "must not be empty",
74        ));
75    }
76    let mut entries = vec![
77        plist_entry("CFBundleDevelopmentRegion", "en"),
78        plist_entry("CFBundleDisplayName", &metadata.caption),
79        plist_entry("CFBundleExecutable", &metadata.executable_name),
80        plist_entry("CFBundleIconFile", "application.icns"),
81        plist_entry("CFBundleIdentifier", &metadata.identifier),
82        plist_entry("CFBundleInfoDictionaryVersion", "6.0"),
83        plist_entry("CFBundleName", &metadata.caption),
84        plist_entry("CFBundlePackageType", "APPL"),
85        plist_entry(
86            "CFBundleShortVersionString",
87            &metadata.native_version.dotted(),
88        ),
89        plist_entry("CFBundleVersion", &metadata.native_version.dotted()),
90    ];
91    if let Some(version) = minimum_version {
92        entries.push(plist_entry("LSMinimumSystemVersion", version));
93    }
94    let xml = format!(
95        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n{}</dict>\n</plist>\n",
96        entries.concat()
97    );
98    Ok(IconArtifact {
99        relative_path: PathBuf::from("Info.plist"),
100        bytes: xml.into_bytes(),
101    })
102}
103
104pub fn encode_windows_resource_script(
105    metadata: &ApplicationMetadata,
106    publisher: Option<&str>,
107) -> Result<IconArtifact> {
108    validate_metadata(metadata)?;
109    let version = metadata.native_version;
110    let mut strings = vec![
111        ("FileDescription", metadata.caption.as_str()),
112        ("FileVersion", metadata.display_version.as_str()),
113        ("InternalName", metadata.executable_name.as_str()),
114        ("OriginalFilename", metadata.executable_name.as_str()),
115        ("ProductName", metadata.caption.as_str()),
116        ("ProductVersion", metadata.display_version.as_str()),
117    ];
118    if let Some(publisher) = publisher {
119        if publisher.trim().is_empty() {
120            return Err(invalid_metadata("windows.publisher", "must not be empty"));
121        }
122        strings.push(("CompanyName", publisher));
123    }
124    let values = strings
125        .into_iter()
126        .map(|(key, value)| format!("      VALUE \"{key}\", \"{}\\0\"\n", rc_escape(value)))
127        .collect::<String>();
128    let script = format!(
129        "#pragma code_page(65001)\n1 ICON \"application.ico\"\n1 VERSIONINFO\n FILEVERSION {},{},{},{}\n PRODUCTVERSION {},{},{},{}\n FILEFLAGSMASK 0x3fL\n FILEFLAGS 0x0L\n FILEOS 0x40004L\n FILETYPE 0x1L\n FILESUBTYPE 0x0L\nBEGIN\n  BLOCK \"StringFileInfo\"\n  BEGIN\n    BLOCK \"040904B0\"\n    BEGIN\n{}    END\n  END\n  BLOCK \"VarFileInfo\"\n  BEGIN\n    VALUE \"Translation\", 0x0409, 1200\n  END\nEND\n",
130        version.major, version.minor, version.patch, version.build,
131        version.major, version.minor, version.patch, version.build, values
132    );
133    Ok(IconArtifact {
134        relative_path: PathBuf::from("application.rc"),
135        bytes: script.into_bytes(),
136    })
137}
138
139pub fn encode_linux_desktop_entry(
140    metadata: &ApplicationMetadata,
141    categories: &[String],
142) -> Result<IconArtifact> {
143    validate_metadata(metadata)?;
144    if categories.iter().any(|category| {
145        category.is_empty()
146            || !category
147                .bytes()
148                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
149    }) {
150        return Err(invalid_metadata(
151            "linux.categories",
152            "entries must use ASCII letters, digits, hyphens, or underscores",
153        ));
154    }
155    let categories_line = if categories.is_empty() {
156        String::new()
157    } else {
158        format!("Categories={};\n", categories.join(";"))
159    };
160    let desktop = format!(
161        "[Desktop Entry]\nType=Application\nVersion=1.0\nName={}\nComment={}\nExec={}\nIcon={}\nTerminal=false\n{}",
162        desktop_escape(&metadata.caption), desktop_escape(&metadata.caption),
163        metadata.executable_name, metadata.executable_name, categories_line
164    );
165    Ok(IconArtifact {
166        relative_path: PathBuf::from(format!("{}.desktop", metadata.executable_name)),
167        bytes: desktop.into_bytes(),
168    })
169}
170
171fn validate_metadata(metadata: &ApplicationMetadata) -> Result<()> {
172    if metadata.executable_name.is_empty()
173        || !metadata
174            .executable_name
175            .bytes()
176            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
177    {
178        return Err(invalid_metadata(
179            "executable-name",
180            "must use ASCII letters, digits, hyphens, or underscores",
181        ));
182    }
183    if metadata.display_version.trim().is_empty() {
184        return Err(invalid_metadata("display-version", "must not be empty"));
185    }
186    if metadata.caption.trim().is_empty() {
187        return Err(invalid_metadata("caption", "must not be empty"));
188    }
189    let parts = metadata.identifier.split('.').collect::<Vec<_>>();
190    if parts.len() < 2
191        || parts.iter().any(|part| {
192            part.is_empty()
193                || !part
194                    .bytes()
195                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
196        })
197    {
198        return Err(invalid_metadata(
199            "identifier",
200            "must contain at least two dot-separated ASCII components",
201        ));
202    }
203    Ok(())
204}
205
206fn plist_entry(key: &str, value: &str) -> String {
207    format!(
208        "  <key>{}</key>\n  <string>{}</string>\n",
209        xml_escape(key),
210        xml_escape(value)
211    )
212}
213
214fn xml_escape(value: &str) -> String {
215    value
216        .replace('&', "&amp;")
217        .replace('<', "&lt;")
218        .replace('>', "&gt;")
219        .replace('"', "&quot;")
220        .replace('\'', "&apos;")
221}
222
223fn rc_escape(value: &str) -> String {
224    value.replace('\\', "\\\\").replace('"', "\\\"")
225}
226
227fn desktop_escape(value: &str) -> String {
228    value
229        .replace('\\', "\\\\")
230        .replace('\n', "\\n")
231        .replace('\r', "\\r")
232        .replace('\t', "\\t")
233}
234
235fn invalid_metadata(field: &'static str, message: impl Into<String>) -> Error {
236    Error::InvalidApplicationMetadata {
237        field,
238        message: message.into(),
239    }
240}