rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Running T3 Code's server without its app: no window, started when `t3` needs it.
//!
//! A hidden rustimal process (`rustimal --t3-server`) runs `t3 serve` and watches over
//! it. It is a process of its own so that closing rustimal windows leaves the server, and
//! whatever its agents are doing, running.
//!
//! T3 Code allows one server per data folder, and its desktop app gives up with an error if
//! another one holds the folder. So the watcher stops the server as soon as the app is
//! opened; the app waits about ten seconds for that, and then starts its own.

use std::net::{Ipv4Addr, TcpListener};
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

const CREATE_NO_WINDOW: u32 = 0x0800_0000;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
/// The port the desktop app uses too. T3 Code's web page keeps its sign-in per address, so
/// staying on it avoids pairing again.
const PORT: u16 = 3773;
const POLL: Duration = Duration::from_millis(250);
/// How long a server may take to be usable.
const START_TIMEOUT: Duration = Duration::from_secs(60);
/// After our own start has ended, how much longer to wait for a server someone else is
/// starting (another pane, say: only one of them gets the data folder).
const SOMEONE_ELSE: Duration = Duration::from_secs(10);

#[repr(C)]
#[derive(Default)]
struct BasicLimits {
    process_time: i64,
    job_time: i64,
    flags: u32,
    min_working_set: usize,
    max_working_set: usize,
    active_processes: u32,
    affinity: usize,
    priority: u32,
    scheduling: u32,
}

#[repr(C)]
#[derive(Default)]
struct ExtendedLimits {
    basic: BasicLimits,
    io: [u64; 6],
    process_memory: usize,
    job_memory: usize,
    peak_process_memory: usize,
    peak_job_memory: usize,
}

#[link(name = "kernel32")]
unsafe extern "system" {
    fn CreateJobObjectW(attributes: *const u8, name: *const u16) -> isize;
    fn SetInformationJobObject(job: isize, class: i32, info: *const ExtendedLimits, size: u32) -> i32;
    fn AssignProcessToJobObject(job: isize, process: isize) -> i32;
    fn CloseHandle(handle: isize) -> i32;
    fn GetStdHandle(which: u32) -> isize;
    fn SetHandleInformation(handle: isize, mask: u32, flags: u32) -> i32;
}

/// A group of processes that Windows ends together when this is dropped, or when the
/// process holding it ends for any reason, so the server can't be left behind unwatched.
struct Job(isize);

impl Job {
    fn holding(child: &Child) -> Option<Job> {
        const EXTENDED_LIMIT_INFORMATION: i32 = 9;
        const KILL_ON_JOB_CLOSE: u32 = 0x2000;
        // SAFETY: a new unnamed job; its handle is closed by `Drop`.
        let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
        if job == 0 {
            return None;
        }
        let job = Job(job);
        let mut limits = ExtendedLimits::default();
        limits.basic.flags = KILL_ON_JOB_CLOSE;
        // SAFETY: `limits` is the structure this class takes, passed with its own size,
        // and the child's handle is open for as long as `child` is borrowed.
        let done = unsafe {
            SetInformationJobObject(job.0, EXTENDED_LIMIT_INFORMATION, &limits, size_of::<ExtendedLimits>() as u32) != 0
                && AssignProcessToJobObject(job.0, child.as_raw_handle() as isize) != 0
        };
        done.then_some(job)
    }
}

impl Drop for Job {
    fn drop(&mut self) {
        // SAFETY: the handle came from `CreateJobObjectW` and is closed only here.
        unsafe { CloseHandle(self.0) };
    }
}

/// Where the desktop app keeps the lock it holds for as long as it runs.
fn desktop_lock() -> Option<PathBuf> {
    std::env::var_os("APPDATA").map(|d| PathBuf::from(d).join("t3code-v2").join("lockfile"))
}

/// Does anyone have this file open?
///
/// The app's lock is a file that is deleted when closed. It lets itself be opened by
/// anyone who, like Rust by default, allows the others everything, deleting included. So
/// ask to share it with no one: that fails whenever somebody else has it open.
fn is_held(path: &Path) -> bool {
    match std::fs::OpenOptions::new().read(true).share_mode(0).open(path) {
        Ok(_) => false,
        Err(e) => e.kind() != std::io::ErrorKind::NotFound,
    }
}

fn desktop_running() -> bool {
    desktop_lock().is_some_and(|lock| is_held(&lock))
}

fn state_file(name: &str) -> Option<PathBuf> {
    crate::config::state_dir().map(|d| d.join(name))
}

/// Asks the watcher to stop; it removes the file to say it heard.
fn stop_request() -> Option<PathBuf> {
    state_file("t3-server.stop")
}

/// One line about what the watcher did, for when something goes wrong out of sight.
fn note(message: &str) {
    let Some(path) = state_file("t3-server.log") else { return };
    if let Some(folder) = path.parent() {
        let _ = std::fs::create_dir_all(folder);
    }
    let when = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
    // Only the latest run is kept, so it never grows.
    let before = std::fs::read_to_string(&path).unwrap_or_default();
    let kept = if message.starts_with("starting") { String::new() } else { before };
    let _ = std::fs::write(path, format!("{kept}{when} {message}\n"));
}

/// The usual port if it is free, or else any that is.
fn free_port(preferred: u16) -> u16 {
    let bind = |port| TcpListener::bind((Ipv4Addr::LOCALHOST, port));
    if bind(preferred).is_ok() {
        return preferred;
    }
    bind(0).ok().and_then(|l| l.local_addr().ok()).map_or(preferred, |a| a.port())
}

/// A process started from here must not keep hold of this one's output: whoever reads it
/// would wait for as long as the server runs.
fn keep_own_output() {
    const HANDLE_FLAG_INHERIT: u32 = 1;
    // Standard input, output and error.
    for which in [-10i32, -11, -12] {
        // SAFETY: only changes whether this process's own handle is passed on.
        unsafe { SetHandleInformation(GetStdHandle(which as u32), HANDLE_FLAG_INHERIT, 0) };
    }
}

/// Something waiting for the server: the part [`wait_for`] needs of the process that
/// runs it.
trait Starting {
    fn ended(&mut self) -> bool;
}

impl Starting for Child {
    fn ended(&mut self) -> bool {
        self.try_wait().is_ok_and(|status| status.is_some())
    }
}

/// Ask `ready` until it has an answer. `watcher` is the process we started to run a
/// server, if we did.
fn wait_for<T>(
    ready: &mut dyn FnMut() -> Option<T>,
    watcher: Option<&mut dyn Starting>,
    app_open: &dyn Fn() -> bool,
    patience: (Duration, Duration),
    pause: Duration,
) -> Result<T, &'static str> {
    let (timeout, after_ours) = patience;
    let began = Instant::now();
    let mut watcher = watcher;
    let mut give_up_at = began + timeout;
    loop {
        if let Some(answer) = ready() {
            return Ok(answer);
        }
        // It ends by itself if the server fails, or if the app is opened meanwhile.
        if watcher.as_mut().is_some_and(|w| w.ended()) {
            watcher = None;
            if !app_open() {
                give_up_at = give_up_at.min(Instant::now() + after_ours);
            }
        }
        if Instant::now() >= give_up_at {
            return Err(if app_open() {
                "the T3 Code app is open, but its server is not answering"
            } else if watcher.is_some() {
                "T3 Code's server did not become ready in time. Run `t3 serve` to see why"
            } else {
                "T3 Code's server stopped while starting. Run `t3 serve` to see why"
            });
        }
        std::thread::sleep(pause);
    }
}

/// Get a server running, once T3 Code's CLI has said none is: wait for the desktop app's
/// if it is open, and otherwise start one in the background. `ready` asks the CLI again,
/// and answers once it can use the server. Only that counts as ready: a port can take
/// connections before the server has said where it is, and the file where it says so can
/// be left over from an earlier one.
pub(super) fn ensure<T>(mut ready: impl FnMut() -> Option<T>) -> Result<T, String> {
    let mut watcher = if desktop_running() {
        None
    } else {
        let exe = std::env::current_exe().map_err(|e| format!("could not find rustimal itself: {e}"))?;
        keep_own_output();
        let child = Command::new(exe)
            .arg("--t3-server")
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP)
            .spawn()
            .map_err(|e| format!("could not start T3 Code's server: {e}"))?;
        Some(child)
    };
    let result = wait_for(
        &mut ready,
        watcher.as_mut().map(|w| w as &mut dyn Starting),
        &desktop_running,
        (START_TIMEOUT, SOMEONE_ELSE),
        POLL,
    );
    // A server that can't be used must not stay behind: it would keep the app from
    // opening. Ending the watcher ends its server with it.
    if result.is_err()
        && let Some(child) = watcher.as_mut()
    {
        let _ = child.kill();
        let _ = child.wait();
    }
    result.map_err(str::to_string)
}

/// `rustimal --t3-server`: run the server out of sight until it is no longer wanted.
pub fn supervise() -> i32 {
    if desktop_running() {
        return 0;
    }
    let Ok(cli) = super::cli_path() else {
        note("T3 Code's CLI was not found");
        return 1;
    };
    if let Some(stop) = stop_request() {
        let _ = std::fs::remove_file(stop);
    }
    let port = free_port(PORT);
    note(&format!("starting T3 Code's server on port {port}"));
    let mut command = Command::new(cli);
    command
        .args(["serve", "--host", "127.0.0.1", "--port", &port.to_string()])
        // PATH and friends as they are now, so the server finds the agents.
        .envs(crate::winenv::fresh())
        // The server prints a pairing code, which is not for keeping.
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .creation_flags(CREATE_NO_WINDOW);
    if let Some(home) = dirs::home_dir() {
        command.current_dir(home);
    }
    let mut server = match command.spawn() {
        Ok(child) => child,
        Err(e) => {
            note(&format!("could not start it: {e}"));
            return 1;
        }
    };
    let Some(job) = Job::holding(&server) else {
        note("could not keep hold of the server's processes, so it was not left running");
        let _ = server.kill();
        return 1;
    };
    let why = loop {
        std::thread::sleep(POLL);
        if let Ok(Some(status)) = server.try_wait() {
            break format!("the server ended ({status})");
        }
        if desktop_running() {
            break "stopped, to let the T3 Code app take over".to_string();
        }
        if let Some(stop) = stop_request().filter(|s| s.exists()) {
            let _ = std::fs::remove_file(stop);
            break "stopped, as asked".to_string();
        }
    };
    // Ends the server and everything it started.
    drop(job);
    let _ = server.wait();
    note(&why);
    0
}

/// `t3 stop`: end the server rustimal started. The desktop app's own is left alone.
pub(super) fn stop() -> Result<&'static str, String> {
    let request = stop_request().ok_or("could not find rustimal's folder")?;
    if let Some(folder) = request.parent() {
        std::fs::create_dir_all(folder).map_err(|e| e.to_string())?;
    }
    std::fs::write(&request, "").map_err(|e| e.to_string())?;
    let began = Instant::now();
    while began.elapsed() < Duration::from_secs(3) {
        if !request.exists() {
            return Ok("Stopped the T3 Code server that was running in the background");
        }
        std::thread::sleep(POLL);
    }
    let _ = std::fs::remove_file(request);
    Ok("rustimal has no T3 Code server running in the background (the app's own is left alone)")
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Against the real thing, which a stand-in can get wrong: run it with the app open.
    #[test]
    #[ignore]
    fn the_open_t3_app_is_noticed() {
        let lock = desktop_lock().unwrap();
        assert!(lock.exists(), "open the T3 Code app first");
        assert!(desktop_running(), "the app holds {} but was not noticed", lock.display());
    }

    #[test]
    fn a_lock_counts_only_while_it_is_held() {
        let path = std::env::temp_dir().join(format!("rustimal-t3-lock-{}", std::process::id()));
        let _ = std::fs::remove_file(&path);
        assert!(!is_held(&path), "no file");
        std::fs::write(&path, "").unwrap();
        assert!(!is_held(&path), "left over from before");
        // As Chromium holds the app's: for writing, deleted when closed, shared for reading.
        const DELETE_ON_CLOSE: u32 = 0x0400_0000;
        const SHARE_READ: u32 = 1;
        let held = std::fs::OpenOptions::new()
            .write(true)
            .share_mode(SHARE_READ)
            .custom_flags(DELETE_ON_CLOSE)
            .open(&path)
            .unwrap();
        assert!(is_held(&path));
        drop(held);
        assert!(!path.exists() && !is_held(&path), "gone with its holder");
        // Held and shared with nobody counts too.
        let held =
            std::fs::OpenOptions::new().write(true).create(true).truncate(true).share_mode(0).open(&path).unwrap();
        assert!(is_held(&path));
        drop(held);
        std::fs::remove_file(path).unwrap();
    }

    /// A watcher that has ended, or not, from the start.
    struct Fake(bool);

    impl Starting for Fake {
        fn ended(&mut self) -> bool {
            self.0
        }
    }

    fn wait(ready_after: u32, watcher: Option<&mut dyn Starting>, app: bool) -> Result<u32, &'static str> {
        let mut asked = 0;
        let mut ready = || {
            asked += 1;
            (asked > ready_after).then_some(asked)
        };
        let patience = (Duration::from_millis(400), Duration::from_millis(120));
        wait_for(&mut ready, watcher, &|| app, patience, Duration::from_millis(5))
    }

    #[test]
    fn it_keeps_asking_until_the_server_can_be_used() {
        assert_eq!(wait(3, Some(&mut Fake(false)), false), Ok(4), "not ready at first is no failure");
        // Ours lost to someone else's start, which is a little behind.
        assert_eq!(wait(3, Some(&mut Fake(true)), false), Ok(4));
        assert_eq!(wait(3, None, true), Ok(4), "the app's own server");
    }

    #[test]
    fn it_gives_up_and_says_which_way_it_failed() {
        let never = u32::MAX;
        assert!(wait(never, Some(&mut Fake(false)), false).unwrap_err().contains("did not become ready"));
        let began = Instant::now();
        assert!(wait(never, Some(&mut Fake(true)), false).unwrap_err().contains("stopped while starting"));
        assert!(began.elapsed() < Duration::from_millis(350), "sooner once ours has ended");
        assert!(wait(never, None, true).unwrap_err().contains("app is open"));
    }

    #[test]
    fn a_taken_port_is_stepped_around() {
        let taken = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let port = taken.local_addr().unwrap().port();
        assert_ne!(free_port(port), port);
        drop(taken);
        assert_eq!(free_port(port), port);
    }

    #[test]
    fn the_job_structure_is_the_size_windows_expects() {
        assert_eq!(size_of::<ExtendedLimits>(), if cfg!(target_pointer_width = "64") { 144 } else { 112 });
    }

    #[test]
    fn closing_the_job_ends_what_it_holds() {
        let mut child = Command::new("cmd.exe")
            .args(["/d", "/c", "ping -n 30 127.0.0.1"])
            .stdout(Stdio::null())
            .creation_flags(CREATE_NO_WINDOW)
            .spawn()
            .unwrap();
        let job = Job::holding(&child).expect("a job");
        assert!(child.try_wait().unwrap().is_none(), "still running");
        drop(job);
        let began = Instant::now();
        while child.try_wait().unwrap().is_none() {
            assert!(began.elapsed() < Duration::from_secs(5), "it should have ended");
            std::thread::sleep(POLL);
        }
    }
}