use std::{
ffi::OsString,
fs,
io::Write as _,
path::Path,
process::{Command, Stdio},
};
use anyhow::Context as _;
use crate::{
package::{AppConfig, PackageOptions},
runtime::{self, Platform},
ui,
};
#[cfg(windows)]
const ICON_ID: u16 = 1;
const ICON_SIZES: [u32; 7] = [16, 20, 24, 32, 40, 48, 64];
pub(crate) fn package(
options: &PackageOptions<'_>,
config: &AppConfig,
name: &str,
id: &str,
built: &crate::build::Built,
) -> anyhow::Result<()> {
let runner = runtime::file(Platform::Windows, true)?;
let mut magic = [0; 2];
let is_pe = fs::File::open(&runner)
.and_then(|mut file| std::io::Read::read_exact(&mut file, &mut magic))
.is_ok_and(|()| magic == *b"MZ");
anyhow::ensure!(is_pe, "{} is not a Windows executable", ui::path(&runner));
let dir = options.out.join(name);
let step = ui::Step::start(format!("packaging {}", ui::path(&dir)));
if dir.exists() {
fs::remove_dir_all(&dir)
.with_context(|| format!("remove {} (is the app still running?)", ui::path(&dir)))?;
}
let resources = dir.join("nsh");
fs::create_dir_all(&resources)?;
let exe = dir.join(format!("{}.exe", file_stem(name)));
fs::copy(&runner, &exe).with_context(|| format!("copy {}", runner.display()))?;
if !built.rust_root {
fs::write(resources.join("bundle.nshc"), &built.bytecode)?;
}
if let Some(json) = built.capabilities_json() {
fs::write(resources.join("capabilities.json"), json)?;
}
for asset in &built.assets {
let dest = resources.join("assets").join(&asset.path);
if let Some(parent) = dest.parent() {
fs::create_dir_all(parent)?;
}
fs::copy(&asset.source, &dest).with_context(|| format!("copy {}", asset.path))?;
}
let version = config.version.as_deref().unwrap_or("1.0.0");
let info = crate::package::desktop_app_json(config, name, id, version);
fs::write(resources.join("app.json"), info.to_string())?;
if let Some(icon) = config.icon(crate::package::PackageTarget::Windows) {
let images = icon_images(icon)?;
fs::write(resources.join("icon.ico"), icon_file(&images))?;
set_icon(&exe, &images)
.with_context(|| format!("embed {} in {}", icon.display(), exe.display()))?;
}
let archive = options.out.join(format!("{name}.zip"));
zip_dir(&dir, name, &archive).with_context(|| format!("create {}", archive.display()))?;
crate::updater::copy_archive(config, name, &update_platform(), &archive, options.out)?;
step.done(format!(
"packaged {} and {}",
ui::path(&dir),
ui::path(&archive)
));
installer(options.out, name, id, version, &dir, &exe)?;
if options.run {
Command::new(&exe)
.current_dir(&dir)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.with_context(|| format!("launch {}", exe.display()))?;
ui::done(format!("launched {name}"));
}
Ok(())
}
fn installer(
out: &Path,
name: &str,
id: &str,
version: &str,
dir: &Path,
exe: &Path,
) -> anyhow::Result<()> {
let stem = file_stem(name);
let script_path = out.join(format!("{stem}.iss"));
let exe_name = exe
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| format!("{stem}.exe"));
let icon = dir.join("nsh").join("icon.ico");
let icon_rel = Path::new(dir.file_name().unwrap_or_default())
.join("nsh")
.join("icon.ico");
let script = inno_script(&InnoApp {
name,
id,
version,
source: &dir
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| name.to_owned()),
exe: &exe_name,
setup: &format!("{stem}-setup"),
icon: icon
.is_file()
.then(|| icon_rel.to_string_lossy().replace('/', "\\")),
});
fs::write(&script_path, script).with_context(|| format!("write {}", script_path.display()))?;
let Some(iscc) = find_iscc() else {
ui::warn(format!(
"wrote {} but not the installer: install Inno Setup 6 (https://jrsoftware.org/isinfo.php, or `winget install JRSoftware.InnoSetup`) and package again, or run ISCC.exe on it",
ui::path(&script_path)
));
return Ok(());
};
let setup = out.join(format!("{stem}-setup.exe"));
let step = ui::Step::start(format!("compiling {}", ui::path(&setup)));
let output = Command::new(&iscc)
.arg("/Q")
.arg(format!("/O{}", out.display()))
.arg(&script_path)
.stdin(Stdio::null())
.output()
.with_context(|| format!("run {}", iscc.display()))?;
anyhow::ensure!(
output.status.success(),
"Inno Setup failed on {}:\n{}{}",
script_path.display(),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
step.done(format!("built the installer {}", ui::path(&setup)));
Ok(())
}
fn find_iscc() -> Option<std::path::PathBuf> {
if let Some(path) = std::env::var_os("PATH") {
for dir in std::env::split_paths(&path) {
for file in ["ISCC.exe", "iscc.exe", "iscc"] {
let candidate = dir.join(file);
if candidate.is_file() {
return Some(candidate);
}
}
}
}
let dirs = ["ProgramFiles(x86)", "ProgramFiles", "LOCALAPPDATA"];
dirs.iter()
.filter_map(std::env::var_os)
.flat_map(|base| {
let base = std::path::PathBuf::from(base);
[
base.join("Inno Setup 6").join("ISCC.exe"),
base.join("Programs").join("Inno Setup 6").join("ISCC.exe"),
]
})
.find(|p| p.is_file())
}
struct InnoApp<'a> {
name: &'a str,
id: &'a str,
version: &'a str,
source: &'a str,
exe: &'a str,
setup: &'a str,
icon: Option<String>,
}
fn inno_script(app: &InnoApp<'_>) -> String {
fn esc(value: &str) -> String {
value.replace('{', "{{").replace('"', "\"\"")
}
let name = esc(app.name);
let dir_name = esc(&file_stem(app.name));
let id = esc(app.id);
let exe = esc(app.exe);
let mut s = String::new();
s.push_str("; Made by `nsh package --target windows`; compile with Inno Setup 6 (ISCC.exe).\n");
s.push_str("[Setup]\n");
s.push_str(&format!("AppId={id}\n"));
s.push_str(&format!("AppName={name}\n"));
s.push_str(&format!("AppVersion={}\n", esc(app.version)));
s.push_str(&format!("AppVerName={name} {}\n", esc(app.version)));
s.push_str(&format!("DefaultDirName={{autopf}}\\{dir_name}\n"));
s.push_str(&format!("DefaultGroupName={name}\n"));
s.push_str("DisableProgramGroupPage=yes\n");
s.push_str("DisableDirPage=auto\n");
s.push_str("PrivilegesRequired=lowest\n");
s.push_str("ArchitecturesAllowed=x64compatible\n");
s.push_str("ArchitecturesInstallIn64BitMode=x64compatible\n");
s.push_str("MinVersion=10.0.17763\n");
s.push_str(&format!("OutputBaseFilename={}\n", esc(app.setup)));
s.push_str("Compression=lzma2\nSolidCompression=yes\nWizardStyle=modern\n");
s.push_str("CloseApplications=force\n");
s.push_str(&format!("UninstallDisplayIcon={{app}}\\{exe}\n"));
s.push_str(&format!("UninstallDisplayName={name}\n"));
if let Some(icon) = &app.icon {
s.push_str(&format!("SetupIconFile={}\n", esc(icon)));
}
s.push_str("\n[Tasks]\n");
s.push_str("Name: \"desktopicon\"; Description: \"{cm:CreateDesktopIcon}\"; GroupDescription: \"{cm:AdditionalIcons}\"; Flags: unchecked\n");
s.push_str("\n[InstallDelete]\n");
s.push_str("Type: filesandordirs; Name: \"{app}\\nsh\"\n");
s.push_str("\n[Files]\n");
s.push_str(&format!(
"Source: \"{}\\*\"; DestDir: \"{{app}}\"; Flags: ignoreversion recursesubdirs createallsubdirs\n",
esc(app.source)
));
s.push_str("\n[Icons]\n");
s.push_str(&format!(
"Name: \"{{autoprograms}}\\{dir_name}\"; Filename: \"{{app}}\\{exe}\"; AppUserModelID: \"{id}\"\n"
));
s.push_str(&format!(
"Name: \"{{autodesktop}}\\{dir_name}\"; Filename: \"{{app}}\\{exe}\"; AppUserModelID: \"{id}\"; Tasks: desktopicon\n"
));
s.push_str("\n[Run]\n");
s.push_str(&format!(
"Filename: \"{{app}}\\{exe}\"; Description: \"{{cm:LaunchProgram,{}}}\"; Flags: nowait postinstall skipifsilent\n",
app.name
.replace('%', "%25")
.replace(',', "%2c")
.replace('{', "%7b")
.replace('}', "%7d")
.replace('"', "\"\"")
));
fn pascal(value: &str) -> String {
value.replace('\'', "''")
}
let run = r"Software\Microsoft\Windows\CurrentVersion\Run";
let (id, exe) = (pascal(app.id), pascal(app.exe));
s.push_str("\n[Code]\n");
s.push_str(concat!(
"function NshExpandEnvironmentStrings(Source: String; Target: String; Size: DWORD): DWORD;\n",
" external 'ExpandEnvironmentStringsW@kernel32.dll stdcall';\n\n",
"function NshExpand(const Value: String): String;\n",
"var\n Buffer: String;\n Size: DWORD;\nbegin\n",
" Result := Value;\n",
" Size := NshExpandEnvironmentStrings(Value, #0, 0);\n",
" if Size = 0 then\n Exit;\n",
" SetLength(Buffer, Size);\n",
" if NshExpandEnvironmentStrings(Value, Buffer, Size) > 0 then\n",
" Result := Copy(Buffer, 1, Size - 1);\n",
"end;\n\n",
));
s.push_str(concat!(
"function NshProgram(Command: String): String;\n",
"var\n Quote: Integer;\nbegin\n",
" StringChangeEx(Command, #9, ' ', True);\n",
" Result := TrimLeft(Command);\n",
" if Copy(Result, 1, 1) = '\"' then\n begin\n",
" Delete(Result, 1, 1);\n",
" Quote := Pos('\"', Result);\n",
" if Quote > 0 then\n Result := Copy(Result, 1, Quote - 1);\n",
" end\n else if Pos(' ', Result) > 0 then\n",
" Result := Copy(Result, 1, Pos(' ', Result) - 1);\n",
" StringChangeEx(Result, '/', '\\', True);\n",
" if CompareText(Copy(Result, 1, 8), '\\\\?\\UNC\\') = 0 then\n",
" Result := '\\' + Copy(Result, 8, Length(Result))\n",
" else if Copy(Result, 1, 4) = '\\\\?\\' then\n",
" Delete(Result, 1, 4);\n",
"end;\n\n",
));
s.push_str("procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);\n");
s.push_str("var\n Command, Exe: String;\nbegin\n");
s.push_str(" if CurUninstallStep <> usUninstall then\n Exit;\n");
s.push_str(&format!(
" if not RegQueryStringValue(HKEY_CURRENT_USER, '{run}', '{id}', Command) then\n Exit;\n"
));
s.push_str(&format!(
" Exe := ExpandConstant('{{app}}') + '\\{exe}';\n"
));
s.push_str(concat!(
" if (CompareText(NshProgram(Command), Exe) = 0)\n",
" or (CompareText(NshProgram(NshExpand(Command)), Exe) = 0) then\n",
));
s.push_str(&format!(
" RegDeleteValue(HKEY_CURRENT_USER, '{run}', '{id}');\nend;\n"
));
s
}
fn file_stem(name: &str) -> String {
let stem: String = name
.chars()
.filter(|c| {
!c.is_control() && !matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*')
})
.collect();
let stem = stem.trim_end_matches(['.', ' ']).trim_start();
if stem.is_empty() {
"App".to_owned()
} else {
stem.to_owned()
}
}
pub(crate) fn host_args(entry: &Path, work: &Path) -> Vec<OsString> {
let config = crate::package::read_config(entry).unwrap_or_default();
let (name, _) = crate::package::name_and_id(entry, &config);
let mut args = vec!["--name".into(), name.into()];
if let Some(icon) = config.icon(crate::package::PackageTarget::Windows) {
let ico = work.join("windows").join("icon.ico");
match host_icon(icon, &ico) {
Ok(()) => args.extend(["--icon".into(), ico.into_os_string()]),
Err(err) => ui::warn(format!("the app's icon: {err:#}")),
}
}
args
}
fn host_icon(icon: &Path, ico: &Path) -> anyhow::Result<()> {
let images = icon_images(icon)?;
if let Some(dir) = ico.parent() {
fs::create_dir_all(dir)?;
}
fs::write(ico, icon_file(&images)).with_context(|| format!("write {}", ico.display()))
}
struct IconImage {
size: u32,
data: Vec<u8>,
}
fn icon_images(icon: &Path) -> anyhow::Result<Vec<IconImage>> {
use image::imageops::FilterType;
let source = image::open(icon).with_context(|| format!("read {}", icon.display()))?;
let mut images = Vec::with_capacity(ICON_SIZES.len() + 1);
for size in ICON_SIZES {
let rgba = source
.resize_exact(size, size, FilterType::Lanczos3)
.into_rgba8();
images.push(IconImage {
size,
data: dib(&rgba),
});
}
let large = source.resize_exact(256, 256, FilterType::Lanczos3);
let mut png = Vec::new();
large
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.context("encode the icon")?;
images.push(IconImage {
size: 256,
data: png,
});
Ok(images)
}
fn dib(rgba: &image::RgbaImage) -> Vec<u8> {
let (width, height) = rgba.dimensions();
let mask_row = width.div_ceil(32) * 4;
let mut data = Vec::with_capacity((40 + width * height * 4 + mask_row * height) as usize);
data.extend_from_slice(&40u32.to_le_bytes());
data.extend_from_slice(&(width as i32).to_le_bytes());
data.extend_from_slice(&(height as i32 * 2).to_le_bytes());
data.extend_from_slice(&1u16.to_le_bytes()); data.extend_from_slice(&32u16.to_le_bytes()); data.extend_from_slice(&[0; 24]); for y in (0..height).rev() {
for x in 0..width {
let [r, g, b, a] = rgba.get_pixel(x, y).0;
data.extend_from_slice(&[b, g, r, a]);
}
}
data.resize(data.len() + (mask_row * height) as usize, 0);
data
}
fn icon_file(images: &[IconImage]) -> Vec<u8> {
let header = 6 + 16 * images.len();
let size = header + images.iter().map(|i| i.data.len()).sum::<usize>();
let mut file = Vec::with_capacity(size);
file.extend_from_slice(&0u16.to_le_bytes());
file.extend_from_slice(&1u16.to_le_bytes()); file.extend_from_slice(&(images.len() as u16).to_le_bytes());
let mut offset = header;
for image in images {
let side = if image.size >= 256 {
0
} else {
image.size as u8
};
file.extend_from_slice(&[side, side, 0, 0]);
file.extend_from_slice(&1u16.to_le_bytes()); file.extend_from_slice(&32u16.to_le_bytes()); file.extend_from_slice(&(image.data.len() as u32).to_le_bytes());
file.extend_from_slice(&(offset as u32).to_le_bytes());
offset += image.data.len();
}
for image in images {
file.extend_from_slice(&image.data);
}
file
}
#[cfg(any(windows, test))]
fn icon_group(images: &[IconImage]) -> Vec<u8> {
let mut group = Vec::with_capacity(6 + 14 * images.len());
group.extend_from_slice(&0u16.to_le_bytes());
group.extend_from_slice(&1u16.to_le_bytes()); group.extend_from_slice(&(images.len() as u16).to_le_bytes());
for (index, image) in images.iter().enumerate() {
let side = if image.size >= 256 {
0
} else {
image.size as u8
};
group.extend_from_slice(&[side, side, 0, 0]);
group.extend_from_slice(&1u16.to_le_bytes()); group.extend_from_slice(&32u16.to_le_bytes()); group.extend_from_slice(&(image.data.len() as u32).to_le_bytes());
group.extend_from_slice(&(index as u16 + 1).to_le_bytes());
}
group
}
#[cfg(windows)]
fn set_icon(exe: &Path, images: &[IconImage]) -> anyhow::Result<()> {
use std::os::windows::ffi::OsStrExt as _;
use windows_sys::Win32::{
Foundation::{FALSE, TRUE},
System::LibraryLoader::{BeginUpdateResourceW, EndUpdateResourceW, UpdateResourceW},
};
const RT_ICON: u16 = 3;
const RT_GROUP_ICON: u16 = 14;
const LANGUAGE: u16 = 0;
let path: Vec<u16> = exe.as_os_str().encode_wide().chain([0]).collect();
let update = unsafe { BeginUpdateResourceW(path.as_ptr(), FALSE) };
if update.is_null() {
return Err(std::io::Error::last_os_error()).context("BeginUpdateResourceW");
}
let resource = |kind: u16, id: u16, data: &[u8]| {
let ok = unsafe {
UpdateResourceW(
update,
kind as usize as *const u16,
id as usize as *const u16,
LANGUAGE,
data.as_ptr().cast(),
data.len() as u32,
)
};
if ok == 0 {
Err(std::io::Error::last_os_error())
} else {
Ok(())
}
};
let mut result = Ok(());
for (index, image) in images.iter().enumerate() {
result = result.and_then(|()| resource(RT_ICON, index as u16 + 1, &image.data));
}
result = result.and_then(|()| resource(RT_GROUP_ICON, ICON_ID, &icon_group(images)));
let discard = if result.is_ok() { FALSE } else { TRUE };
let ended = unsafe { EndUpdateResourceW(update, discard) } != 0;
result.context("UpdateResourceW")?;
if !ended {
return Err(std::io::Error::last_os_error()).context("EndUpdateResourceW");
}
Ok(())
}
#[cfg(not(windows))]
fn set_icon(exe: &Path, _images: &[IconImage]) -> anyhow::Result<()> {
ui::warn(format!(
"{} has the default icon in Explorer: icons are embedded when packaging on Windows (its windows and notifications show the app's)",
ui::path(exe)
));
Ok(())
}
fn zip_dir(dir: &Path, root: &str, archive: &Path) -> anyhow::Result<()> {
use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};
let _ = fs::remove_file(archive);
let mut zip = ZipWriter::new(fs::File::create(archive)?);
let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
let mut pending = vec![(dir.to_path_buf(), root.to_owned())];
while let Some((dir, prefix)) = pending.pop() {
zip.add_directory(format!("{prefix}/"), options)?;
let mut entries: Vec<_> = fs::read_dir(&dir)?.collect::<Result<_, _>>()?;
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let name = format!("{prefix}/{}", entry.file_name().to_string_lossy());
if entry.file_type()?.is_dir() {
pending.push((entry.path(), name));
} else {
zip.start_file(name, options)?;
zip.write_all(&fs::read(entry.path())?)?;
}
}
}
zip.finish()?;
Ok(())
}
fn update_platform() -> String {
if cfg!(windows) {
nsh_updater::platform()
} else {
"windows-x86_64".to_owned()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn update_archives_are_named_for_windows() {
assert!(
update_platform().starts_with("windows-"),
"{}",
update_platform()
);
}
#[test]
fn installer_scripts_install_per_user_and_upgrade_by_id() {
let script = inno_script(&InnoApp {
name: "Hopper {Lab}",
id: "com.example.hopper",
version: "1.2.0",
source: "Hopper {Lab}",
exe: "Hopper {Lab}.exe",
setup: "Hopper {Lab}-setup",
icon: None,
});
assert!(script.contains("AppId=com.example.hopper\n"));
assert!(script.contains("AppName=Hopper {{Lab}\n"));
assert!(script.contains("PrivilegesRequired=lowest\n"));
assert!(script.contains(r"DefaultDirName={autopf}\Hopper {{Lab}"));
assert!(script.contains(r#"Source: "Hopper {{Lab}\*""#));
assert!(script.contains(r#"AppUserModelID: "com.example.hopper""#));
assert!(script.contains(r#"Type: filesandordirs; Name: "{app}\nsh""#));
assert!(script.contains("{cm:LaunchProgram,Hopper %7bLab%7d}"));
assert!(!script.contains("SetupIconFile"));
}
#[test]
fn uninstalling_removes_the_login_item_that_starts_this_installation() {
let script = inno_script(&InnoApp {
name: "O'Hare {Lab}",
id: "com.example.o'hare",
version: "1.0.0",
source: "O'Hare {Lab}",
exe: "O'Hare {Lab}.exe",
setup: "O'Hare {Lab}-setup",
icon: None,
});
let code = &script[script.find("\n[Code]\n").expect("a [Code] section")..];
let run = r"Software\Microsoft\Windows\CurrentVersion\Run";
assert!(code.contains("CurUninstallStep <> usUninstall"));
assert!(code.contains(&format!(
"RegQueryStringValue(HKEY_CURRENT_USER, '{run}', 'com.example.o''hare', Command)"
)));
assert!(code.contains("external 'ExpandEnvironmentStringsW@kernel32.dll stdcall';"));
for line in [
" StringChangeEx(Command, #9, ' ', True);",
r#" if Copy(Result, 1, 1) = '"' then"#,
r#" Quote := Pos('"', Result);"#,
r" Result := Copy(Result, 1, Pos(' ', Result) - 1);",
r" StringChangeEx(Result, '/', '\', True);",
r" if CompareText(Copy(Result, 1, 8), '\\?\UNC\') = 0 then",
r" Result := '\' + Copy(Result, 8, Length(Result))",
r" else if Copy(Result, 1, 4) = '\\?\' then",
r" Exe := ExpandConstant('{app}') + '\O''Hare {Lab}.exe';",
" if (CompareText(NshProgram(Command), Exe) = 0)",
" or (CompareText(NshProgram(NshExpand(Command)), Exe) = 0) then",
] {
assert!(code.contains(line), "{line}\n{code}");
}
assert!(code.contains(&format!(
"RegDeleteValue(HKEY_CURRENT_USER, '{run}', 'com.example.o''hare');"
)));
}
#[test]
fn file_names_drop_what_windows_forbids() {
assert_eq!(file_stem("Hopper Lab"), "Hopper Lab");
assert_eq!(file_stem("A/B: C?"), "AB C");
assert_eq!(file_stem("Dots..."), "Dots");
assert_eq!(file_stem("<>"), "App");
}
#[test]
fn icon_groups_list_their_images() {
let images = [
IconImage {
size: 16,
data: vec![0; 10],
},
IconImage {
size: 256,
data: vec![0; 300],
},
];
let group = icon_group(&images);
assert_eq!(group.len(), 6 + 14 * 2);
assert_eq!(&group[..6], &[0, 0, 1, 0, 2, 0]);
assert_eq!(&group[6..10], &[16, 16, 0, 0]);
assert_eq!(&group[14..18], &10u32.to_le_bytes());
assert_eq!(&group[18..20], &1u16.to_le_bytes());
assert_eq!(&group[20..24], &[0, 0, 0, 0]);
assert_eq!(&group[28..32], &300u32.to_le_bytes());
assert_eq!(&group[32..34], &2u16.to_le_bytes());
}
#[test]
fn icon_files_point_at_their_images() {
let images = [
IconImage {
size: 16,
data: vec![1; 10],
},
IconImage {
size: 256,
data: vec![2; 300],
},
];
let file = icon_file(&images);
let header = 6 + 16 * 2;
assert_eq!(file.len(), header + 10 + 300);
assert_eq!(&file[..6], &[0, 0, 1, 0, 2, 0]);
assert_eq!(&file[6..10], &[16, 16, 0, 0]);
assert_eq!(&file[14..18], &10u32.to_le_bytes());
assert_eq!(&file[18..22], &(header as u32).to_le_bytes());
assert_eq!(&file[22..26], &[0, 0, 0, 0]);
assert_eq!(&file[34..38], &((header + 10) as u32).to_le_bytes());
assert_eq!(file[header], 1);
assert_eq!(file[header + 10], 2);
}
#[test]
fn dibs_hold_the_image_and_its_mask() {
let image = image::RgbaImage::from_pixel(16, 16, image::Rgba([1, 2, 3, 4]));
let data = dib(&image);
assert_eq!(data.len(), 40 + 16 * 16 * 4 + 16 * 4);
assert_eq!(&data[8..12], &32i32.to_le_bytes());
assert_eq!(&data[40..44], &[3, 2, 1, 4]);
}
#[test]
fn host_icon_changes_when_the_config_selects_an_older_file() {
let dir = std::env::temp_dir().join(format!("nsh-icon-switch-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let red = dir.join("red.png");
let blue = dir.join("blue.png");
image::RgbaImage::from_pixel(32, 32, image::Rgba([255, 0, 0, 255]))
.save(&red)
.unwrap();
image::RgbaImage::from_pixel(32, 32, image::Rgba([0, 0, 255, 255]))
.save(&blue)
.unwrap();
let old = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000);
for source in [&red, &blue] {
fs::File::options()
.write(true)
.open(source)
.unwrap()
.set_times(fs::FileTimes::new().set_modified(old))
.unwrap();
}
let ico = dir.join("icon.ico");
host_icon(&red, &ico).unwrap();
let first = fs::read(&ico).unwrap();
host_icon(&blue, &ico).unwrap();
let second = fs::read(&ico).unwrap();
fs::remove_dir_all(&dir).unwrap();
assert!(
first != second,
"selecting a different existing icon must regenerate the ICO"
);
}
#[test]
fn zips_hold_the_directory_under_its_name() {
let dir = std::env::temp_dir().join(format!("nsh-zip-{}", std::process::id()));
let app = dir.join("Demo");
fs::create_dir_all(app.join("nsh/assets")).unwrap();
fs::write(app.join("Demo.exe"), b"binary").unwrap();
fs::write(app.join("nsh/bundle.nshc"), b"code").unwrap();
let archive = dir.join("Demo.zip");
zip_dir(&app, "Demo", &archive).unwrap();
let mut zip = zip::ZipArchive::new(fs::File::open(&archive).unwrap()).unwrap();
let mut names: Vec<String> = zip
.file_names()
.map(|name| name.unwrap().into_owned())
.collect();
names.sort_unstable();
assert_eq!(
names,
[
"Demo/",
"Demo/Demo.exe",
"Demo/nsh/",
"Demo/nsh/assets/",
"Demo/nsh/bundle.nshc"
]
);
let mut code = String::new();
std::io::Read::read_to_string(&mut zip.by_name("Demo/nsh/bundle.nshc").unwrap(), &mut code)
.unwrap();
assert_eq!(code, "code");
fs::remove_dir_all(&dir).unwrap();
}
}