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 --layout NAME open a saved layout (save one from the command palette)
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 --update install the newest version from crates.io (needs cargo)
rustimal --update --check only say whether there is one
rustimal --open FILE[:LINE[:COL]]
open a file in your editor at that line (the shell's `open` uses this)
rustimal --review [TARGET]
what to check and how to test a change by hand: a pull
request, branch, commit or `demo` (--help for more)
in a rustimal window, `pr` and `review` open it as a panel
rustimal --t3 [-l | NUMBER | FOLDER]
open a folder's conversation in the T3 Code desktop app
(`t3` in a rustimal pane shows it inside the pane)
rustimal --browser [PAGE] run a Firefox-based browser (Zen, Firefox, ...) with a profile of its own
(`embed browser` in a rustimal pane shows it inside the pane)
rustimal --fork [FOLDER] run Fork, the Git client, on a repository
(`fork` in a rustimal pane shows it inside the pane)
rustimal --version
rustimal --help
";
use crate::platform::win32::GetStdHandle;
#[link(name = "kernel32")]
unsafe extern "system" {
fn AttachConsole(pid: u32) -> i32;
fn SetStdHandle(which: u32, handle: isize) -> i32;
fn GetConsoleMode(handle: isize, mode: *mut u32) -> i32;
fn SetConsoleMode(handle: isize, mode: u32) -> 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 enable_ansi() {
const ENABLE_VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004;
unsafe {
let out = GetStdHandle(STD_OUTPUT_HANDLE);
let mut mode = 0;
if GetConsoleMode(out, &mut mode) != 0 {
SetConsoleMode(out, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
}
}
}
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()))
}
"--update" => {
attach_console();
Some(update(&rest()))
}
"--review" => {
attach_console();
Some(crate::review::run(&rest()))
}
"--t3" => {
attach_console();
Some(crate::programs::t3::run(&rest()))
}
"--t3-server" => Some(crate::programs::t3::server::supervise()),
"--vscode-server" => Some(crate::programs::vscode::supervise()),
"--browser" => {
attach_console();
Some(crate::programs::browser::run(&rest()))
}
"--fork" => {
attach_console();
Some(crate::programs::fork::run(&rest()))
}
"--open" => {
attach_console();
Some(open_at(&rest()))
}
_ => None,
}
}
fn open_at(args: &[String]) -> i32 {
use crate::terminal::links::{Pos, open_in_editor_blocking, split_position};
let Some(first) = args.first() else {
eprintln!("usage: rustimal --open FILE[:LINE[:COL]]");
return 2;
};
let (file, pos) = match args[1..].iter().map(|a| a.parse::<u32>()).collect::<Result<Vec<_>, _>>() {
Ok(nums) if !nums.is_empty() && nums.len() <= 2 => {
(first.as_str(), Some(Pos { line: nums[0], col: nums.get(1).copied() }))
}
Ok(nums) if nums.is_empty() => split_position(first),
_ => {
eprintln!("usage: rustimal --open FILE[:LINE[:COL]]");
return 2;
}
};
let path = std::path::absolute(file).unwrap_or_else(|_| file.into());
if !path.is_file() {
eprintln!("rustimal: {file}: no such file");
return 1;
}
let editor = crate::config::Config::load().editor;
open_in_editor_blocking(&path, pos.unwrap_or(Pos { line: 1, col: None }), &editor);
0
}
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
}
}
}
fn latest_version() -> Result<String, String> {
let out = Command::new("cargo")
.args(["search", "rustimal", "--limit", "1"])
.output()
.map_err(|e| format!("could not run cargo ({e}); updating needs the Rust toolchain: https://rustup.rs"))?;
if !out.status.success() {
return Err(format!("cargo search failed: {}", String::from_utf8_lossy(&out.stderr).trim()));
}
parse_search(&String::from_utf8_lossy(&out.stdout)).ok_or_else(|| "rustimal was not found on crates.io".to_string())
}
fn parse_search(output: &str) -> Option<String> {
let line = output.lines().find(|l| l.starts_with("rustimal = \""))?;
let rest = &line["rustimal = \"".len()..];
Some(rest[..rest.find('"')?].to_string())
}
fn version_parts(v: &str) -> Vec<u64> {
v.split('-').next().unwrap_or("").split('.').map(|p| p.parse().unwrap_or(0)).collect()
}
fn is_newer(latest: &str, current: &str) -> bool {
let (mut a, mut b) = (version_parts(latest), version_parts(current));
let n = a.len().max(b.len());
a.resize(n, 0);
b.resize(n, 0);
a > b
}
fn installed_exe() -> Option<std::path::PathBuf> {
let home = std::env::var_os("CARGO_HOME")
.map(std::path::PathBuf::from)
.or_else(|| dirs::home_dir().map(|h| h.join(".cargo")))?;
Some(home.join("bin").join("rustimal.exe"))
}
fn remove_old_copies(dir: &std::path::Path) {
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let name = entry.file_name().to_string_lossy().to_lowercase();
if name.starts_with("rustimal.old") && name.ends_with(".exe") {
let _ = std::fs::remove_file(entry.path());
}
}
}
fn update(args: &[String]) -> i32 {
let (mut check, mut force) = (false, false);
for a in args {
match a.as_str() {
"--check" => check = true,
"--force" => force = true,
other => {
eprintln!("unknown option: {other}\n\n{HELP}");
return 2;
}
}
}
let current = env!("CARGO_PKG_VERSION");
println!("rustimal {current}; asking crates.io for the newest version...");
let latest = match latest_version() {
Ok(v) => v,
Err(e) => {
eprintln!("{e}");
return 1;
}
};
if !is_newer(&latest, current) && !force {
println!("rustimal {current} is up to date (the newest is {latest}).");
return 0;
}
if check {
println!("rustimal {latest} is available (this is {current}). Run `rustimal --update` to install it.");
return 0;
}
println!("Installing rustimal {latest} with cargo. This compiles it, so it takes a few minutes.");
let target = installed_exe().filter(|p| p.exists());
let moved = target.as_ref().and_then(|exe| {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
let aside = exe.with_file_name(format!("rustimal.old{stamp}.exe"));
std::fs::rename(exe, &aside).ok().map(|()| (exe.clone(), aside))
});
let status = Command::new("cargo").args(["install", "rustimal", "--locked", "--force"]).status();
let installed = matches!(status, Ok(s) if s.success());
if installed {
if let Some(dir) = target.as_ref().and_then(|p| p.parent()) {
remove_old_copies(dir);
}
println!(
"\nUpdated to rustimal {latest}. New windows use it; open windows keep running {current} until you close them."
);
return 0;
}
if let Some((exe, aside)) = moved
&& !exe.exists()
{
let _ = std::fs::rename(aside, exe);
}
match status {
Ok(_) => eprintln!("\ncargo could not install rustimal {latest}; the version you have is unchanged."),
Err(e) => eprintln!("\ncould not run cargo: {e}"),
}
1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_version_from_cargo_search() {
let out = "rustimal = \"0.4.0\" # A minimal, GPU-rendered terminal\nrustimal-extras = \"1.0.0\" # other\n";
assert_eq!(parse_search(out), Some("0.4.0".to_string()));
assert_eq!(parse_search("rustimal-extras = \"1.0.0\"\n"), None, "another crate is not ours");
assert_eq!(parse_search(""), None);
}
#[test]
fn versions_compare_by_number() {
assert!(is_newer("0.4.0", "0.3.9"));
assert!(is_newer("0.10.0", "0.9.9"), "numbers, not text");
assert!(is_newer("1.0", "0.9.9"));
assert!(!is_newer("0.4.0", "0.4.0"));
assert!(!is_newer("0.3.9", "0.4.0"));
assert!(is_newer("0.4.1", "0.4"));
}
}