use std::process::Command;
const INSTALL_SCRIPT: &str = include_str!("../install.ps1");
const HELP: &str = "\
rustimal - a GPU-rendered terminal for Windows
USAGE:
rustimal [DIRECTORY] open a window, starting in DIRECTORY
rustimal --install add Start menu, Explorer right-click and Win+R entries
rustimal --install --desktop
... and a desktop shortcut
rustimal --uninstall remove those entries (the exe and your config stay)
rustimal --version
rustimal --help
";
#[link(name = "kernel32")]
unsafe extern "system" {
fn AttachConsole(pid: u32) -> i32;
fn GetStdHandle(which: u32) -> isize;
fn SetStdHandle(which: u32, handle: isize) -> i32;
}
const ATTACH_PARENT_PROCESS: u32 = u32::MAX;
const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
const STD_ERROR_HANDLE: u32 = -12i32 as u32;
fn attach_console() {
use std::os::windows::io::IntoRawHandle;
unsafe {
if AttachConsole(ATTACH_PARENT_PROCESS) == 0 {
return; }
for which in [STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
let h = GetStdHandle(which);
if (h == 0 || h == -1)
&& let Ok(f) = std::fs::OpenOptions::new().write(true).open("CONOUT$")
{
SetStdHandle(which, f.into_raw_handle() as isize);
}
}
}
}
pub fn run(arg: &str) -> Option<i32> {
let rest = || std::env::args().skip(2).collect::<Vec<_>>();
match arg {
"--version" | "-V" => {
attach_console();
println!("rustimal {}", env!("CARGO_PKG_VERSION"));
Some(0)
}
"--help" | "-h" | "/?" => {
attach_console();
print!("{HELP}");
Some(0)
}
"--install" => {
attach_console();
Some(setup(false, &rest()))
}
"--uninstall" => {
attach_console();
Some(setup(true, &rest()))
}
_ => None,
}
}
fn setup(uninstall: bool, extra: &[String]) -> i32 {
let mut args = vec!["-NoProfile".to_string(), "-ExecutionPolicy".into(), "Bypass".into(), "-File".into()];
let script = std::env::temp_dir().join(format!("rustimal-setup-{}.ps1", std::process::id()));
if let Err(e) = std::fs::write(&script, INSTALL_SCRIPT) {
eprintln!("could not write {}: {e}", script.display());
return 1;
}
args.push(script.to_string_lossy().into_owned());
match std::env::current_exe() {
Ok(exe) => {
args.push("-ExePath".into());
args.push(exe.to_string_lossy().into_owned());
}
Err(e) => {
eprintln!("could not find the rustimal executable: {e}");
let _ = std::fs::remove_file(&script);
return 1;
}
}
if uninstall {
args.push("-Uninstall".into());
}
for a in extra {
match a.to_ascii_lowercase().as_str() {
"--desktop" if !uninstall => args.push("-Desktop".into()),
other => {
eprintln!("unknown option: {other}\n\n{HELP}");
let _ = std::fs::remove_file(&script);
return 2;
}
}
}
let status = Command::new("powershell.exe").args(&args).status();
let _ = std::fs::remove_file(&script);
match status {
Ok(s) if s.success() => 0,
Ok(s) => s.code().unwrap_or(1),
Err(e) => {
eprintln!("could not run powershell.exe: {e}");
1
}
}
}