use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use anyhow::{Context, Result};
const APP_NAME: &str = "Croft";
fn launcher_script(croft_bin: &str, open_dir: &str) -> String {
let bin = applescript_lit(croft_bin);
let dir = applescript_lit(open_dir);
format!(
r#"on run
set inner to quoted form of {bin} & " " & quoted form of {dir}
do shell script "open -na Ghostty.app --args --initial-command=" & quoted form of inner
end run
on open theFiles
repeat with f in theFiles
set inner to quoted form of {bin} & " " & quoted form of (POSIX path of f) & " --zen"
do shell script "open -na Ghostty.app --args --initial-command=" & quoted form of inner
end repeat
end open
"#
)
}
fn applescript_lit(s: &str) -> String {
format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
}
fn plist_edits() -> Vec<String> {
[
"Add :CFBundleIdentifier string com.vitali87.croft-launcher",
"Set :CFBundleName Croft",
"Add :CFBundleDisplayName string Croft",
"Add :CFBundleShortVersionString string 1.0",
"Set :CFBundleIconFile croft",
"Add :CFBundleDocumentTypes array",
"Add :CFBundleDocumentTypes:0:CFBundleTypeName string \"Any File\"",
"Add :CFBundleDocumentTypes:0:CFBundleTypeRole string Editor",
"Add :CFBundleDocumentTypes:0:LSHandlerRank string Alternate",
"Add :CFBundleDocumentTypes:0:LSItemContentTypes array",
"Add :CFBundleDocumentTypes:0:LSItemContentTypes:0 string public.item",
]
.iter()
.map(|s| (*s).to_string())
.collect()
}
fn plist_cleanup_deletes() -> Vec<String> {
["Delete :CFBundleIconName", "Delete :CFBundleDocumentTypes"]
.iter()
.map(|s| (*s).to_string())
.collect()
}
pub fn applications_dir(user: bool) -> Result<PathBuf> {
if user {
let home = std::env::var_os("HOME").context("HOME is not set")?;
Ok(PathBuf::from(home).join("Applications"))
} else {
Ok(PathBuf::from("/Applications"))
}
}
fn write_icon(dest: &Path) -> Result<()> {
let tmp = std::env::temp_dir().join(format!("croft-launcher-icon-{}", std::process::id()));
let iconset = tmp.join("croft.iconset");
std::fs::create_dir_all(&iconset).with_context(|| format!("creating {}", iconset.display()))?;
let src_png = tmp.join("logo.png");
std::fs::write(&src_png, crate::iterm2_inline::APP_ICON_PNG)
.with_context(|| format!("writing {}", src_png.display()))?;
for size in [16u32, 32, 128, 256, 512] {
for (scale, name) in [
(1u32, format!("icon_{size}x{size}.png")),
(2, format!("icon_{size}x{size}@2x.png")),
] {
let px = (size * scale).to_string();
let status = Command::new("sips")
.args(["-z", &px, &px])
.arg(&src_png)
.arg("--out")
.arg(iconset.join(&name))
.stdout(Stdio::null())
.status()
.context("running sips")?;
if !status.success() {
anyhow::bail!("sips failed building {name}");
}
}
}
let status = Command::new("iconutil")
.args(["-c", "icns"])
.arg(&iconset)
.arg("-o")
.arg(dest)
.stdout(Stdio::null())
.status()
.context("running iconutil")?;
let _ = std::fs::remove_dir_all(&tmp);
if !status.success() {
anyhow::bail!("iconutil failed building the launcher icon");
}
Ok(())
}
pub fn install(app_dir: &Path, croft_bin: &str, open_dir: &str) -> Result<PathBuf> {
let app = app_dir.join(format!("{APP_NAME}.app"));
let _ = std::fs::remove_dir_all(&app);
let src =
std::env::temp_dir().join(format!("croft-launcher-{}.applescript", std::process::id()));
std::fs::write(&src, launcher_script(croft_bin, open_dir))
.with_context(|| format!("writing {}", src.display()))?;
let status = Command::new("osacompile")
.arg("-o")
.arg(&app)
.arg(&src)
.stdout(Stdio::null())
.status()
.context("running osacompile")?;
let _ = std::fs::remove_file(&src);
if !status.success() {
anyhow::bail!("osacompile failed building the launcher applet");
}
write_icon(&app.join("Contents/Resources/croft.icns")).context("building the launcher icon")?;
let plist = app.join("Contents/Info.plist");
for delete in plist_cleanup_deletes() {
let _ = Command::new("/usr/libexec/PlistBuddy")
.arg("-c")
.arg(delete)
.arg(&plist)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
let mut buddy = Command::new("/usr/libexec/PlistBuddy");
for edit in plist_edits() {
buddy.arg("-c").arg(edit);
}
let status = buddy
.arg(&plist)
.stdout(Stdio::null())
.status()
.context("running PlistBuddy")?;
if !status.success() {
anyhow::bail!("PlistBuddy failed writing {}", plist.display());
}
let status = Command::new("codesign")
.args(["--force", "--sign", "-"])
.arg(&app)
.stderr(Stdio::null())
.status()
.context("running codesign")?;
if !status.success() {
anyhow::bail!("codesign failed re-signing the launcher");
}
let _ = Command::new("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister")
.arg("-f")
.arg(&app)
.status();
Ok(app)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn script_opens_ghostty_with_initial_command_and_both_paths() {
let s = launcher_script("/Users/v/.cargo/bin/croft", "/Users/v/Documents");
assert!(s.contains("on run"));
assert!(s.contains("open -na Ghostty.app --args"));
assert!(s.contains(r#"quoted form of "/Users/v/.cargo/bin/croft""#));
assert!(s.contains(r#"quoted form of "/Users/v/Documents""#));
}
#[test]
fn script_handles_opened_documents_through_an_open_handler() {
let s = launcher_script("/Users/v/.cargo/bin/croft", "/Users/v/Documents");
assert!(s.contains("on open theFiles"));
assert!(s.contains("quoted form of (POSIX path of f)"));
}
#[test]
fn opened_documents_start_zen_but_a_plain_click_does_not() {
let s = launcher_script("/Users/v/.cargo/bin/croft", "/Users/v/Documents");
let (run, open) = s.split_once("on open theFiles").unwrap();
assert!(open.contains("--zen"));
assert!(!run.contains("--zen"));
}
#[test]
fn an_apostrophe_in_a_path_survives_both_shell_layers() {
let s = launcher_script("/Users/v/my tools/croft", "/Users/v/Vitali's Docs");
assert!(
s.contains(r#"quoted form of "/Users/v/Vitali's Docs""#),
"the workspace dir must be quoted as its own component: {s}"
);
assert!(
s.contains(r#"quoted form of "/Users/v/my tools/croft""#),
"the binary path must be quoted as its own component: {s}"
);
assert!(
!s.contains("croft '"),
"no hand-rolled single quotes may remain: {s}"
);
}
#[test]
fn quotes_and_backslashes_cannot_break_the_applescript_source() {
let s = launcher_script("/Users/v/.cargo/bin/croft", r#"/Users/v/say "hi"\now"#);
assert!(
s.contains(r#""/Users/v/say \"hi\"\\now""#),
"the literal must escape quotes and backslashes: {s}"
);
}
#[test]
fn every_dropped_file_opens_not_just_the_first() {
let s = launcher_script("/Users/v/.cargo/bin/croft", "/Users/v/Documents");
assert!(
s.contains("repeat with"),
"the open handler must loop over theFiles: {s}"
);
assert!(
!s.contains("item 1 of theFiles"),
"no file may be silently dropped: {s}"
);
}
#[test]
fn cleanup_deletes_are_best_effort_and_never_in_the_fatal_batch() {
let edits = plist_edits();
assert!(
edits.iter().all(|e| !e.starts_with("Delete ")),
"a Delete on an absent key fails the whole fatal batch: {edits:?}"
);
let cleanup = plist_cleanup_deletes();
assert!(cleanup.contains(&"Delete :CFBundleIconName".to_string()));
assert!(cleanup.contains(&"Delete :CFBundleDocumentTypes".to_string()));
assert!(edits.contains(&"Add :CFBundleDocumentTypes array".to_string()));
}
#[test]
fn plist_edits_claim_every_file_type_and_set_the_bundle_id() {
let e = plist_edits().join(" ");
assert!(e.contains("CFBundleIdentifier string com.vitali87.croft-launcher"));
assert!(e.contains("LSItemContentTypes:0 string public.item"));
assert!(e.contains("CFBundleTypeRole string Editor"));
assert!(e.contains("Set :CFBundleIconFile croft"));
}
#[test]
fn applications_dir_picks_system_or_user() {
assert_eq!(
applications_dir(false).unwrap(),
PathBuf::from("/Applications")
);
assert!(applications_dir(true).unwrap().ends_with("Applications"));
}
}