rustimal 0.8.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
436
437
438
439
440
441
//! VS Code in a pane: `code serve-web`, VS Code's own web server, run out of sight and
//! shown in a web view (see `app::web`).
//!
//! VS Code Server has license terms of its own, so nothing here runs it until the person
//! has accepted them (`vscode` asks, once). It listens only on this computer, and every
//! request needs a random key: whoever can use it has a terminal.
//!
//! A hidden `rustimal --vscode-server` process looks after it. All rustimal windows share
//! the one server, on a port that stays the same, as VS Code keeps its web settings per
//! address. It stops once no rustimal window that used it is left.

use std::io::{Read, Write};
use std::net::{Ipv4Addr, SocketAddr, TcpStream};
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use crate::platform::process::{self, CREATE_NO_WINDOW, Job};

/// Written by `vscode` in the shell when the person says yes.
const ACCEPTED: &str = "vscode-license-accepted";
const PORT: u16 = 38473;
const POLL: Duration = Duration::from_millis(500);
/// The first start downloads the server from Microsoft.
const START_TIMEOUT: Duration = Duration::from_secs(300);
/// How long the server outlives the last rustimal window that used it.
const LINGER: Duration = Duration::from_secs(15);

/// How VS Code starts out here: dark, and tight enough for a pane. These go in the
/// server's settings (VS Code's "Remote" tab), and only when there are none yet.
const DEFAULT_SETTINGS: &str = r#"// Written once by rustimal. Change anything you like; it is not overwritten.
{
    "workbench.colorTheme": "Dark Modern",
    "window.autoDetectColorScheme": false,

    "window.density.layout": "compact",
    "window.density.editorTabHeight": "compact",
    "workbench.activityBar.compact": true,
    "window.commandCenter": false,
    "window.menuBarVisibility": "compact",
    "workbench.layoutControl.enabled": false,
    "workbench.navigationControl.enabled": false,
    "workbench.secondarySideBar.defaultVisibility": "hidden",
    "breadcrumbs.enabled": false,
    "editor.minimap.enabled": false,
    "workbench.startupEditor": "none",
    "workbench.tips.enabled": false,

    // VS Code's own default on the web. Closing it in rustimal asks nothing, so edits
    // are only safe there if they are saved as you go.
    "files.autoSave": "afterDelay"
}
"#;

/// Give the server its starting settings, unless it has settings already. Returns whether
/// it wrote them.
fn write_default_settings(server_data: &Path) -> std::io::Result<bool> {
    let folder = server_data.join("data").join("Machine");
    std::fs::create_dir_all(&folder)?;
    let file = std::fs::OpenOptions::new().write(true).create_new(true).open(folder.join("settings.json"));
    match file {
        Ok(mut file) => file.write_all(DEFAULT_SETTINGS.as_bytes()).map(|()| true),
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
        Err(e) => Err(e),
    }
}

/// Where the server keeps its data: where `serve-web` does when it isn't told, or the
/// test's own.
fn server_data() -> Option<PathBuf> {
    test_folder().map(|d| d.join("server-data")).or_else(|| dirs::home_dir().map(|home| home.join(".vscode-server")))
}

fn give_starting_settings() {
    if let Some(data) = server_data()
        && let Err(e) = write_default_settings(&data)
    {
        log::warn!("could not write VS Code's starting settings: {e}");
    }
}

/// This window has no VS Code left in it, so it no longer holds the server up.
pub fn release() {
    if let Some(dir) = state_file("vscode-users") {
        let _ = std::fs::remove_file(dir.join(std::process::id().to_string()));
    }
}

/// A folder that, in a debug build, takes the place of rustimal's state and of the
/// server's data, so that testing never touches a VS Code that is in use.
fn test_folder() -> Option<PathBuf> {
    std::env::var_os("RUSTIMAL_VSCODE_TEST").filter(|_| cfg!(debug_assertions)).map(PathBuf::from)
}

fn state_file(name: &str) -> Option<PathBuf> {
    test_folder().map(|d| d.join(name)).or_else(|| process::state_file(name))
}

/// VS Code's command-line tool, which can serve it to a browser.
pub fn tool() -> Option<PathBuf> {
    // The PATH from the registry too: VS Code may have been installed since we started.
    let fresh = crate::platform::winenv::fresh();
    let from_registry = fresh.iter().find(|(k, _)| k.eq_ignore_ascii_case("path")).map(|(_, v)| v.clone());
    let paths = [std::env::var("PATH").ok(), from_registry];
    let on_path = paths.iter().flatten().flat_map(std::env::split_paths);
    let usual = ["LOCALAPPDATA", "ProgramFiles"].iter().filter_map(std::env::var_os).map(|base| {
        let base = PathBuf::from(base);
        let base = if base.ends_with("Local") { base.join("Programs") } else { base };
        base.join("Microsoft VS Code").join("bin")
    });
    on_path.chain(usual).map(|dir| dir.join("code-tunnel.exe")).find(|p| p.is_file())
}

pub fn license_accepted() -> bool {
    state_file(ACCEPTED).is_some_and(|f| f.is_file())
}

/// A running server.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Server {
    pub port: u16,
    pub key: String,
}

impl Server {
    pub fn origin(&self) -> String {
        format!("http://127.0.0.1:{}", self.port)
    }

    /// The address that signs in and shows `folder`, with `file` open at a line if one is
    /// given.
    pub fn url(&self, folder: &Path, file: Option<&Spot>) -> String {
        let mut url = format!("{}/?tkn={}&folder={}", self.origin(), self.key, encode(&uri_path(folder), "/"));
        if let Some(spot) = file {
            let mut target = format!("vscode-remote://127.0.0.1:{}{}", self.port, encode(&uri_path(&spot.file), "/:"));
            let mut entries = Vec::new();
            if let Some(line) = spot.line {
                target += &format!(":{line}");
                if let Some(col) = spot.col {
                    target += &format!(":{col}");
                }
                entries.push(["gotoLineMode".to_string(), "true".to_string()]);
            }
            entries.insert(0, ["openFile".to_string(), target]);
            let payload = serde_json::to_string(&entries).unwrap_or_default();
            url += &format!("&payload={}", encode(&payload, ""));
        }
        url
    }
}

/// A file to open, and where in it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Spot {
    pub file: PathBuf,
    pub line: Option<u32>,
    pub col: Option<u32>,
}

/// `C:\a\b` as VS Code's web address writes it: `/c:/a/b`.
fn uri_path(path: &Path) -> String {
    let text = path.to_string_lossy().replace('\\', "/");
    let text = text.trim_start_matches("//?/").trim_end_matches('/');
    let mut chars = text.chars();
    match (chars.next(), chars.next()) {
        (Some(drive), Some(':')) => {
            let rest = &text[2..];
            let rest = if rest.is_empty() { "/" } else { rest };
            format!("/{}:{rest}", drive.to_ascii_lowercase())
        }
        _ => format!("/{}", text.trim_start_matches('/')),
    }
}

/// Percent-encode all but letters, digits, `-_.~` and what is in `keep`.
fn encode(text: &str, keep: &str) -> String {
    text.bytes()
        .map(|b| {
            if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) || keep.as_bytes().contains(&b) {
                (b as char).to_string()
            } else {
                format!("%{b:02X}")
            }
        })
        .collect()
}

/// The folder to open around `file`: the one already open if the file is inside it, else
/// its Git checkout, else the shell's folder if the file is under it, else its own.
pub fn workspace_for(file: &Path, open: Option<&Path>, cwd: Option<&Path>) -> PathBuf {
    if let Some(open) = open.filter(|o| file.starts_with(o)) {
        return open.to_path_buf();
    }
    let parent = file.parent().unwrap_or(file);
    let home = dirs::home_dir();
    // A checkout of the whole home folder (for dotfiles, say) is no workspace.
    let checkout = parent.ancestors().find(|d| d.join(".git").exists() && Some(*d) != home.as_deref());
    checkout
        .or_else(|| cwd.filter(|c| file.starts_with(c) && Some(*c) != home.as_deref()))
        .unwrap_or(parent)
        .to_path_buf()
}

/// The first line of the server's answer to a request with `key`.
fn status_line(port: u16, key: &str) -> Option<String> {
    let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
    let mut stream = TcpStream::connect_timeout(&address, Duration::from_millis(500)).ok()?;
    stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?;
    let request = format!("GET /?tkn={key} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
    stream.write_all(request.as_bytes()).ok()?;
    let mut start = [0u8; 64];
    let n = stream.read(&mut start).ok()?;
    String::from_utf8_lossy(&start[..n]).lines().next().map(str::to_string)
}

/// Ready is when it takes the key and sends the browser on. While it downloads it
/// answers 202, and a server that isn't ours says 403.
fn is_ready(status_line: &str) -> bool {
    status_line.split_whitespace().nth(1) == Some("302")
}

/// The server the watcher says it runs, if that one takes our key.
fn running() -> Option<Server> {
    let port: u16 = std::fs::read_to_string(state_file("vscode-server.port")?).ok()?.trim().parse().ok()?;
    let key = std::fs::read_to_string(state_file("vscode-server.key")?).ok()?.trim().to_string();
    (!key.is_empty() && status_line(port, &key).is_some_and(|l| is_ready(&l))).then_some(Server { port, key })
}

/// Say that this process is using the server, so that it stays while we do.
fn register_user() -> Result<(), String> {
    let dir = state_file("vscode-users").ok_or("could not find rustimal's folder")?;
    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
    std::fs::write(dir.join(std::process::id().to_string()), "").map_err(|e| e.to_string())
}

/// Whether any process that registered is still running. Forgets those that aren't.
fn has_users() -> bool {
    let Some(dir) = state_file("vscode-users") else { return false };
    let mut any = false;
    for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
        match entry.file_name().to_string_lossy().parse::<u32>() {
            Ok(id) if process::process_alive(id) => any = true,
            _ => {
                let _ = std::fs::remove_file(entry.path());
            }
        }
    }
    any
}

/// The server, started if it isn't running. Slow the first time; call it off the UI thread.
pub fn ensure() -> Result<Server, String> {
    if tool().is_none() {
        return Err("VS Code isn't installed (its `code-tunnel.exe` was not found)".to_string());
    }
    if !license_accepted() {
        return Err("run `vscode` once, to accept VS Code Server's license".to_string());
    }
    register_user()?;
    // Here too, for a server that was started before there were any.
    give_starting_settings();
    if let Some(server) = running() {
        return Ok(server);
    }
    // If another window's watcher is at work, ours sees that and leaves at once.
    let mut watcher =
        process::start_watcher("--vscode-server").map_err(|e| format!("could not start VS Code's server: {e}"))?;
    let began = Instant::now();
    let mut gone_since = None;
    while began.elapsed() < START_TIMEOUT {
        if let Some(server) = running() {
            return Ok(server);
        }
        if watcher.try_wait().is_ok_and(|s| s.is_some()) {
            let since = *gone_since.get_or_insert_with(Instant::now);
            if since.elapsed() > Duration::from_secs(60) {
                break;
            }
        }
        std::thread::sleep(POLL);
    }
    Err("VS Code's server did not become ready; see %APPDATA%\\rustimal\\state\\vscode-server.log".to_string())
}

/// `rustimal --vscode-server`: run the server out of sight while rustimal windows use it.
pub fn supervise() -> i32 {
    let (Some(tool), true) = (tool(), license_accepted()) else { return 1 };
    let (Some(lock), Some(port_file), Some(key_file), Some(log)) = (
        state_file("vscode-server.lock"),
        state_file("vscode-server.port"),
        state_file("vscode-server.key"),
        state_file("vscode-server.log"),
    ) else {
        return 1;
    };
    // Held for as long as we run, shared with nobody: there is only ever one watcher.
    let Ok(_lock) = std::fs::OpenOptions::new().write(true).create(true).truncate(false).share_mode(0).open(lock)
    else {
        return 0;
    };
    let _ = std::fs::remove_file(&port_file);
    give_starting_settings();
    let Some(key) = process::secret_key() else { return 1 };
    // The key goes in a file in the user's profile, never on a command line.
    if std::fs::write(&key_file, &key).is_err() {
        return 1;
    }
    let port = process::free_port(PORT);
    let output = std::fs::File::create(&log).ok();
    let mut command = Command::new(tool);
    command
        .args(["serve-web", "--host", "127.0.0.1", "--port", &port.to_string(), "--connection-token-file"])
        .arg(&key_file)
        // Only reached once the person has accepted them; see `license_accepted`.
        .arg("--accept-server-license-terms")
        .envs(crate::platform::winenv::fresh())
        .stdin(Stdio::null())
        .creation_flags(CREATE_NO_WINDOW);
    if test_folder().is_some()
        && let Some(data) = server_data()
    {
        command.arg("--server-data-dir").arg(data);
    }
    // What it prints is kept to explain a failure. It shows the address with the key in
    // it, which is no more than the key file beside it holds.
    match output.and_then(|f| Some((f.try_clone().ok()?, f))) {
        Some((out, err)) => command.stdout(out).stderr(err),
        None => command.stdout(Stdio::null()).stderr(Stdio::null()),
    };
    let Ok(mut server) = command.spawn() else { return 1 };
    let Some(job) = Job::holding(&server) else {
        let _ = server.kill();
        return 1;
    };
    let _ = std::fs::write(&port_file, port.to_string());
    let mut unused_since: Option<Instant> = None;
    loop {
        std::thread::sleep(POLL);
        if !matches!(server.try_wait(), Ok(None)) {
            break;
        }
        if has_users() {
            unused_since = None;
        } else if unused_since.get_or_insert_with(Instant::now).elapsed() >= LINGER {
            break;
        }
    }
    drop(job);
    let _ = server.wait();
    let _ = std::fs::remove_file(port_file);
    let _ = std::fs::remove_file(key_file);
    0
}

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

    fn server() -> Server {
        Server { port: 38473, key: "k3y".into() }
    }

    #[test]
    fn folders_and_files_become_addresses() {
        assert_eq!(uri_path(Path::new(r"C:\Users\me\app")), "/c:/Users/me/app");
        assert_eq!(uri_path(Path::new(r"D:\")), "/d:/");
        assert_eq!(uri_path(Path::new(r"\\?\C:\x\")), "/c:/x");
        let folder = server().url(Path::new(r"C:\my app & co"), None);
        assert_eq!(folder, "http://127.0.0.1:38473/?tkn=k3y&folder=/c%3A/my%20app%20%26%20co");
        let spot = Spot { file: r"C:\p\árvíz #1.rs".into(), line: Some(12), col: Some(5) };
        let url = server().url(Path::new(r"C:\p"), Some(&spot));
        let payload = url.split_once("&payload=").unwrap().1;
        assert!(!payload.contains(['&', '#', ' ', '"']), "{payload}");
        let decoded = percent_decode(payload);
        assert_eq!(
            decoded,
            r#"[["openFile","vscode-remote://127.0.0.1:38473/c:/p/%C3%A1rv%C3%ADz%20%231.rs:12:5"],["gotoLineMode","true"]]"#
        );
        let plain = server().url(Path::new(r"C:\p"), Some(&Spot { file: r"C:\p\a".into(), line: None, col: None }));
        assert!(!percent_decode(&plain).contains("gotoLineMode"));
    }

    fn percent_decode(text: &str) -> String {
        let mut out = Vec::new();
        let bytes = text.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            if bytes[i] == b'%' {
                out.push(u8::from_str_radix(&text[i + 1..i + 3], 16).unwrap());
                i += 3;
            } else {
                out.push(bytes[i]);
                i += 1;
            }
        }
        String::from_utf8(out).unwrap()
    }

    #[test]
    fn a_file_opens_in_the_folder_it_belongs_to() {
        let root = std::env::temp_dir().join(format!("rustimal-ws-{}", std::process::id()));
        std::fs::create_dir_all(root.join("repo/.git")).unwrap();
        std::fs::create_dir_all(root.join("repo/src")).unwrap();
        std::fs::create_dir_all(root.join("loose/sub")).unwrap();
        let in_repo = root.join("repo/src/a.rs");
        let loose = root.join("loose/sub/b.txt");
        assert_eq!(workspace_for(&in_repo, None, None), root.join("repo"));
        assert_eq!(workspace_for(&in_repo, Some(&root), None), root, "what is open stays open");
        assert_eq!(workspace_for(&in_repo, Some(&root.join("loose")), None), root.join("repo"));
        assert_eq!(workspace_for(&loose, None, Some(&root.join("loose"))), root.join("loose"));
        assert_eq!(workspace_for(&loose, None, None), root.join("loose/sub"));
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn starting_settings_never_replace_any() {
        let data = std::env::temp_dir().join(format!("rustimal-vsdata-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&data);
        assert!(write_default_settings(&data).unwrap());
        let file = data.join("data/Machine/settings.json");
        let written = std::fs::read_to_string(&file).unwrap();
        let json: String = written.lines().filter(|l| !l.trim_start().starts_with("//")).collect();
        let settings: serde_json::Value = serde_json::from_str(&json).expect("valid settings");
        assert_eq!(settings["workbench.colorTheme"], "Dark Modern");
        assert_eq!(settings["window.density.layout"], "compact");
        std::fs::write(&file, "{}").unwrap();
        assert!(!write_default_settings(&data).unwrap());
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "{}", "what was there stays");
        std::fs::remove_dir_all(data).unwrap();
    }

    #[test]
    fn only_a_redirect_means_ready() {
        assert!(is_ready("HTTP/1.1 302 Found"));
        for not in ["HTTP/1.1 202 Accepted", "HTTP/1.1 403 Forbidden", "HTTP/1.1 200 OK", "", "302"] {
            assert!(!is_ready(not), "{not}");
        }
    }
}