use std::{
env,
path::{Path, PathBuf},
time::Instant,
};
use cargo_packager::{
Config, PackageFormat,
config::{Binary, MacOsConfig, Resource},
};
use image::{Rgba, RgbaImage};
use tempfile::TempDir;
use crate::{
args::{BuildArgs, BundleFormat},
cargo_progress,
error::CliError,
output::Reporter,
process::Cancellation,
project::Project,
};
pub fn plan(
project: &Project,
arguments: &BuildArgs,
target: Option<&str>,
reporter: &Reporter,
) -> Result<(), CliError> {
let Some(formats) = selected_formats(project, arguments, target)? else {
return Ok(());
};
let names = format_names(&formats);
reporter.bundle_planned(&names);
Ok(())
}
pub fn validate(
project: &Project,
arguments: &BuildArgs,
target: Option<&str>,
) -> Result<(), CliError> {
selected_formats(project, arguments, target).map(|_| ())
}
pub fn run(
project: &Project,
arguments: &BuildArgs,
executables: &[PathBuf],
target: Option<&str>,
profile: &str,
reporter: &Reporter,
cancellation: &Cancellation,
) -> Result<Vec<PathBuf>, CliError> {
let Some(formats) = selected_formats(project, arguments, target)? else {
return Ok(Vec::new());
};
let [executable] = executables else {
return Err(CliError::Packaging {
message: format!(
"expected one executable, Cargo reported {}; select one with --bin",
executables.len()
),
});
};
if cancellation.is_cancelled() {
return Err(CliError::Interrupted);
}
let package = cargo_progress::native_package(project, &arguments.cargo);
let target_platform = Platform::for_target(target)?;
let (config, _default_icon) = create_config(
project,
arguments,
executable,
target,
target_platform,
&formats,
package.as_ref(),
)?;
let names = format_names(&formats);
reporter.bundle_started(&names);
let started = Instant::now();
let outputs = cargo_packager::package(&config).map_err(|error| CliError::Packaging {
message: error.to_string(),
})?;
if cancellation.is_cancelled() {
return Err(CliError::Interrupted);
}
let mut paths = Vec::new();
for output in outputs {
let format = packager_format_name(output.format);
for path in output.paths {
reporter.bundle_artifact(&path, format, target, profile);
paths.push(path);
}
}
if paths.is_empty() {
return Err(CliError::Packaging {
message: "the packager did not produce an artifact".to_owned(),
});
}
reporter.bundle_finished(&names, started.elapsed());
Ok(paths)
}
fn create_config(
project: &Project,
arguments: &BuildArgs,
executable: &Path,
target: Option<&str>,
target_platform: Platform,
formats: &[BundleFormat],
package: Option<&cargo_progress::NativePackage>,
) -> Result<(Config, Option<TempDir>), CliError> {
let version = project
.bundle
.version
.clone()
.or_else(|| package.map(|package| package.version.clone()))
.ok_or_else(|| CliError::InvalidConfig {
field: "bundle.version",
message: "could not derive a version from the native Cargo package".to_owned(),
})?;
let executable = windows_binary_path(executable.to_owned(), target_platform);
let output_dir = arguments.bundle_dir.as_ref().map_or_else(
|| {
executable.parent().map_or_else(
|| project.root.join("target/bundle"),
|parent| parent.join("bundle"),
)
},
|path| absolute_from(&project.root, path),
);
let mut config = Config::default();
config.product_name.clone_from(&project.app_name);
config.version = version;
config.binaries = vec![Binary::new(executable).main(true)];
config.identifier = Some(project.identifier.clone());
config.formats = Some(formats.iter().copied().map(packager_format).collect());
config.out_dir = output_dir;
config.target_triple = target.map(str::to_owned);
config.description = project
.bundle
.description
.clone()
.or_else(|| package.and_then(|package| package.description.clone()));
config.authors = package
.map(|package| package.authors.clone())
.filter(|authors| !authors.is_empty());
config.publisher.clone_from(&project.bundle.publisher);
config.copyright.clone_from(&project.bundle.copyright);
let default_icon = project
.bundle
.icons
.is_empty()
.then(default_icon)
.transpose()?;
config.icons = Some(if let Some(icon) = &default_icon {
vec![icon.path().join("kayro.png").to_string_lossy().into_owned()]
} else {
project
.bundle
.icons
.iter()
.map(|path| path.to_string_lossy().into_owned())
.collect()
});
config.resources = Some(
std::iter::once(project.config_path.clone())
.chain(project.bundle.resources.iter().cloned())
.map(|path| Resource::Single(path.to_string_lossy().into_owned()))
.collect(),
);
if target_platform == Platform::MacOs {
let mut macos =
MacOsConfig::new().minimum_system_version(&project.bundle.macos_minimum_system_version);
if let Some(identity) = env::var_os("APPLE_SIGNING_IDENTITY")
.filter(|identity| !identity.is_empty())
.map(|identity| identity.to_string_lossy().into_owned())
{
macos = macos.signing_identity(identity);
}
config.macos = Some(macos);
}
Ok((config, default_icon))
}
fn selected_formats(
project: &Project,
arguments: &BuildArgs,
target: Option<&str>,
) -> Result<Option<Vec<BundleFormat>>, CliError> {
if arguments.no_bundle || (!project.bundle.active && arguments.bundles.is_empty()) {
return Ok(None);
}
let platform = Platform::for_target(target)?;
let host = Platform::host()?;
if platform != host {
return Err(CliError::InvalidArguments {
message: format!(
"{} bundles must be created on {} (current host: {}); use --no-bundle for cross-compilation",
platform.name(),
platform.name(),
host.name(),
),
});
}
let formats = if arguments.bundles.is_empty() {
platform.defaults().to_vec()
} else {
arguments.bundles.clone()
};
if let Some(format) = formats.iter().find(|format| !platform.supports(**format)) {
return Err(CliError::InvalidArguments {
message: format!(
"bundle format `{}` is not available for {}",
format_name(*format),
platform.name()
),
});
}
Ok(Some(formats))
}
fn absolute_from(root: &std::path::Path, path: &std::path::Path) -> PathBuf {
if path.is_absolute() {
path.to_owned()
} else {
root.join(path)
}
}
fn default_icon() -> Result<TempDir, CliError> {
let directory = tempfile::Builder::new()
.prefix("kayro-icon-")
.tempdir()
.map_err(|error| CliError::Packaging {
message: format!("could not prepare the default app icon: {error}"),
})?;
let path = directory.path().join("kayro.png");
let mut icon = RgbaImage::new(512, 512);
for (x, y, pixel) in icon.enumerate_pixels_mut() {
let inside = rounded_square(x, y, 48, 416, 96);
if !inside {
*pixel = Rgba([0, 0, 0, 0]);
continue;
}
let mix = x + y;
let red = u8::try_from(32 + 70 * mix / 1_022).expect("red channel is in range");
let green = u8::try_from(170 - 76 * mix / 1_022).expect("green channel is in range");
let blue = u8::try_from(235 + 18 * mix / 1_022).expect("blue channel is in range");
let mark = (132..=178).contains(&x) && (104..=408).contains(&y)
|| near_segment(x, y, 166, 263, 354, 105, 23)
|| near_segment(x, y, 166, 249, 368, 408, 23);
*pixel = if mark {
Rgba([245, 249, 255, 255])
} else {
Rgba([red, green, blue, 255])
};
}
icon.save(&path).map_err(|error| CliError::Packaging {
message: format!("could not write the default app icon: {error}"),
})?;
Ok(directory)
}
fn rounded_square(x: u32, y: u32, start: u32, end: u32, radius: u32) -> bool {
let delta_x = i64::from(x) - i64::from(x.clamp(start + radius, end - radius));
let delta_y = i64::from(y) - i64::from(y.clamp(start + radius, end - radius));
delta_x * delta_x + delta_y * delta_y <= i64::from(radius * radius)
}
fn near_segment(
x: u32,
y: u32,
start_x: i64,
start_y: i64,
end_x: i64,
end_y: i64,
radius: i64,
) -> bool {
let delta_x = end_x - start_x;
let delta_y = end_y - start_y;
let relative_x = i64::from(x) - start_x;
let relative_y = i64::from(y) - start_y;
let length_squared = delta_x * delta_x + delta_y * delta_y;
let projection = relative_x * delta_x + relative_y * delta_y;
let radius_squared = radius * radius;
if projection <= 0 {
relative_x * relative_x + relative_y * relative_y <= radius_squared
} else if projection >= length_squared {
let end_delta_x = i64::from(x) - end_x;
let end_delta_y = i64::from(y) - end_y;
end_delta_x * end_delta_x + end_delta_y * end_delta_y <= radius_squared
} else {
let cross = relative_x * delta_y - relative_y * delta_x;
cross * cross <= radius_squared * length_squared
}
}
fn windows_binary_path(mut path: PathBuf, platform: Platform) -> PathBuf {
if platform == Platform::Windows
&& path
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("exe"))
{
path.set_extension("");
}
path
}
fn format_names(formats: &[BundleFormat]) -> Vec<&'static str> {
formats.iter().copied().map(format_name).collect()
}
fn format_name(format: BundleFormat) -> &'static str {
match format {
BundleFormat::App => "app",
BundleFormat::Dmg => "dmg",
BundleFormat::Nsis => "nsis",
BundleFormat::Msi => "msi",
BundleFormat::AppImage => "appimage",
BundleFormat::Deb => "deb",
}
}
fn packager_format(format: BundleFormat) -> PackageFormat {
match format {
BundleFormat::App => PackageFormat::App,
BundleFormat::Dmg => PackageFormat::Dmg,
BundleFormat::Nsis => PackageFormat::Nsis,
BundleFormat::Msi => PackageFormat::Wix,
BundleFormat::AppImage => PackageFormat::AppImage,
BundleFormat::Deb => PackageFormat::Deb,
}
}
fn packager_format_name(format: PackageFormat) -> &'static str {
match format {
PackageFormat::App => "app",
PackageFormat::Dmg => "dmg",
PackageFormat::Nsis => "nsis",
PackageFormat::Wix => "msi",
PackageFormat::AppImage => "appimage",
PackageFormat::Deb => "deb",
_ => "bundle",
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Platform {
MacOs,
Windows,
Linux,
}
impl Platform {
fn host() -> Result<Self, CliError> {
match env::consts::OS {
"macos" => Ok(Self::MacOs),
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
os => Err(CliError::InvalidArguments {
message: format!("Kayro does not support packaging on {os}; use --no-bundle"),
}),
}
}
fn for_target(target: Option<&str>) -> Result<Self, CliError> {
let Some(target) = target else {
return Self::host();
};
if target.contains("apple-darwin") {
Ok(Self::MacOs)
} else if target.contains("windows") {
Ok(Self::Windows)
} else if target.contains("linux") {
Ok(Self::Linux)
} else {
Err(CliError::InvalidArguments {
message: format!(
"cannot select a bundle format for target `{target}`; use --no-bundle"
),
})
}
}
fn name(self) -> &'static str {
match self {
Self::MacOs => "macOS",
Self::Windows => "Windows",
Self::Linux => "Linux",
}
}
fn defaults(self) -> &'static [BundleFormat] {
match self {
Self::MacOs => &[BundleFormat::Dmg],
Self::Windows => &[BundleFormat::Nsis],
Self::Linux => &[BundleFormat::AppImage],
}
}
fn supports(self, format: BundleFormat) -> bool {
matches!(
(self, format),
(Self::MacOs, BundleFormat::App | BundleFormat::Dmg)
| (Self::Windows, BundleFormat::Nsis | BundleFormat::Msi)
| (Self::Linux, BundleFormat::AppImage | BundleFormat::Deb)
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn platform_defaults_are_native_installers() {
assert_eq!(Platform::MacOs.defaults(), [BundleFormat::Dmg]);
assert_eq!(Platform::Windows.defaults(), [BundleFormat::Nsis]);
assert_eq!(Platform::Linux.defaults(), [BundleFormat::AppImage]);
}
#[test]
fn windows_binary_paths_drop_the_exe_suffix_for_the_packager() {
assert_eq!(
windows_binary_path(PathBuf::from("target/app.exe"), Platform::Windows),
PathBuf::from("target/app")
);
}
#[test]
fn built_in_icon_is_a_square_png() {
use image::GenericImageView as _;
let icon = default_icon().unwrap();
let image = image::open(icon.path().join("kayro.png")).unwrap();
assert_eq!(image.dimensions(), (512, 512));
}
}