Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(windows): cross build the app for Windows, ConPTY terminals

rokarturd910dffffad6
diff --git a/native/Cargo.lock b/native/Cargo.lock
index e62a0bb5b05..551afb933e0 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -271,6 +271,7 @@ dependencies = [
"ttf-parser",
"url",
"webkit2gtk",
+ "windows-sys 0.61.2",
"wuff",
"x11",
"x11rb",
@@ -1879,6 +1880,7 @@ dependencies = [
"serde_json",
"sha2",
"storage",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -3720,6 +3722,7 @@ version = "0.35.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f"
dependencies = [
+ "cc",
"pkg-config",
"vcpkg",
]
diff --git a/native/crates/app/Cargo.toml b/native/crates/app/Cargo.toml
index e3a14277671..65b3dd6ba99 100644
--- a/native/crates/app/Cargo.toml
+++ b/native/crates/app/Cargo.toml
@@ -50,6 +50,17 @@ objc2-foundation = { version = "0.3.2", default-features = false, features = ["N
objc2-web-kit = { version = "0.3.2", default-features = false, features = ["WKContentRuleList", "WKContentRuleListStore", "WKNavigation", "WKPreferences", "WKScriptMessage", "WKScriptMessageHandler", "WKURLSchemeHandler", "WKURLSchemeTask", "WKUserContentController", "WKUserScript", "WKWebView", "WKWebViewConfiguration", "block2", "objc2-app-kit", "objc2-core-foundation"] }
security-framework = "3"
+[target.'cfg(target_os = "windows")'.dependencies]
+windows-sys = { version = "0.61", features = [
+ "Win32_Foundation",
+ "Win32_Security",
+ "Win32_System_Console",
+ "Win32_System_Diagnostics_ToolHelp",
+ "Win32_System_Pipes",
+ "Win32_System_Threading",
+ "Win32_UI_WindowsAndMessaging",
+] }
+
[target.'cfg(target_os = "linux")'.dependencies]
# The zbus gpui_linux's ashpd and oo7 use.
zbus = { version = "5", default-features = false, features = ["async-io", "blocking-api"] }
diff --git a/native/crates/app/src/accessibility_signals.rs b/native/crates/app/src/accessibility_signals.rs
index 6f2260326da..60055d33e98 100644
--- a/native/crates/app/src/accessibility_signals.rs
+++ b/native/crates/app/src/accessibility_signals.rs
@@ -2,6 +2,7 @@
//! `checkEnabledState`, the volume, and playback of the upstream mp3 files through NSSound, on Linux through
//! PipeWire's or PulseAudio's player.
+#[cfg(unix)]
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -101,6 +102,7 @@ pub fn volume_percent(setting: &Value) -> f64 {
/// `AccessibilitySignalService.playSound`: one NSSound per file, kept and replayed from the start as the service
/// keeps its `HTMLAudioElement`s.
pub struct SoundPlayer {
+ #[cfg_attr(target_os = "windows", expect(dead_code, reason = "no player on Windows yet"))]
media: PathBuf,
#[cfg(target_os = "macos")]
sounds: HashMap<&'static str, Retained<NSSound>>,
@@ -139,6 +141,10 @@ impl SoundPlayer {
}
}
+ // shortcut: no sound on Windows yet; port/ledger.md M24 row app/src/accessibility_signals.rs:107.
+ #[cfg(target_os = "windows")]
+ pub fn play(&mut self, _file_name: &'static str, _volume_percent: f64) {}
+
#[cfg(target_os = "macos")]
pub fn play(&mut self, file_name: &'static str, volume_percent: f64) {
if !self.sounds.contains_key(file_name) {
diff --git a/native/crates/app/src/app_icon.rs b/native/crates/app/src/app_icon.rs
index 5d4d5fb4525..8b893033bc1 100644
--- a/native/crates/app/src/app_icon.rs
+++ b/native/crates/app/src/app_icon.rs
@@ -23,8 +23,8 @@ pub fn image(look: &str, dark: bool, bundled: bool) -> Option<&'static [u8]> {
}
}
-/// Linux has no Dock: the window icon is the desktop file's, as for VS Code there.
-#[cfg(target_os = "linux")]
+/// Linux and Windows have no Dock: the window icon is the desktop file's or the executable's, as for VS Code there.
+#[cfg(any(target_os = "linux", target_os = "windows"))]
pub fn image(_look: &str, _dark: bool, _bundled: bool) -> Option<&'static [u8]> {
None
}
@@ -43,5 +43,5 @@ pub fn set(image: Option<&[u8]>) {
}
/// Tests run off the main thread without an NSApplication; the workbench's `app_icon` records the swap.
-#[cfg(any(test, target_os = "linux"))]
+#[cfg(any(test, target_os = "linux", target_os = "windows"))]
pub fn set(_image: Option<&[u8]>) {}
diff --git a/native/crates/app/src/cli.rs b/native/crates/app/src/cli.rs
index 3ffed58a09a..df5a98b155a 100644
--- a/native/crates/app/src/cli.rs
+++ b/native/crates/app/src/cli.rs
@@ -4,8 +4,12 @@
//! other command line goes to the app.
use std::io::{IsTerminal, Read, Write};
+#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
+#[cfg(unix)]
use std::os::unix::process::CommandExt;
+#[cfg(windows)]
+use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;
@@ -138,7 +142,12 @@ fn spawn_app(argv: &[String], shows_output: bool) -> std::io::Result<std::proces
}
false => {
let mut command = Command::new(&exe);
- command.args(argv).env_clear().envs(env).process_group(0);
+ command.args(argv).env_clear().envs(env);
+ #[cfg(unix)]
+ command.process_group(0);
+ // Node's `detached: true` on Windows: DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP.
+ #[cfg(windows)]
+ command.creation_flags(0x8 | 0x200);
command
}
};
@@ -171,10 +180,17 @@ fn random_path(prefix: &str, length: usize) -> PathBuf {
/// stdin.ts `createStdInFile` and wait.ts `createWaitMarkerFileSync`: mode 0600 (vscode-remote-release 9048), and a
/// new file only, so a planted symlink in the temp folder is not followed.
+#[cfg(unix)]
fn create_user_only_file(path: &Path) -> std::io::Result<std::fs::File> {
std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)
}
+/// Node ignores the mode on Windows; the temp folder is the user's own.
+#[cfg(windows)]
+fn create_user_only_file(path: &Path) -> std::io::Result<std::fs::File> {
+ std::fs::OpenOptions::new().write(true).create_new(true).open(path)
+}
+
/// stdin.ts `readFromStdin`: each chunk decoded from the terminal encoding and appended as it arrives, so watchers
/// see the file grow.
fn copy_stdin(mut stdin: impl Read, mut file: std::fs::File, encoding: &str) {
@@ -207,6 +223,19 @@ fn terminal_encoding(verbose: bool) -> String {
}
encoding
}
+ #[cfg(windows)]
+ None => {
+ if verbose {
+ println!("Running \"chcp\" to detect terminal encoding...");
+ }
+ // Node's `exec` runs it through cmd.exe, which finds chcp.com; Command only adds `.exe`.
+ let stdout = Command::new("chcp.com").output().map(|output| String::from_utf8_lossy(&output.stdout).into_owned()).unwrap_or_default();
+ if verbose && !stdout.is_empty() {
+ println!("Output from \"chcp\" command is: {stdout}");
+ }
+ windows_terminal_encoding(&stdout).unwrap_or_default().to_owned()
+ }
+ #[cfg(unix)]
None => {
if verbose {
println!("Running \"locale charmap\" to detect terminal encoding...");
@@ -221,6 +250,27 @@ fn terminal_encoding(verbose: bool) -> String {
to_iconv_lite_encoding(&raw)
}
+/// terminalEncoding.ts `windowsTerminalEncodings`: the first code page, in key order, that `chcp`'s output contains.
+#[cfg(any(windows, test))]
+fn windows_terminal_encoding(chcp: &str) -> Option<&'static str> {
+ const ENCODINGS: [(&str, &str); 13] = [
+ ("437", "cp437"),
+ ("850", "cp850"),
+ ("852", "cp852"),
+ ("855", "cp855"),
+ ("857", "cp857"),
+ ("860", "cp860"),
+ ("861", "cp861"),
+ ("863", "cp863"),
+ ("865", "cp865"),
+ ("866", "cp866"),
+ ("869", "cp869"),
+ ("936", "cp936"),
+ ("1252", "cp1252"),
+ ];
+ ENCODINGS.iter().find(|(page, _)| chcp.contains(page)).map(|(_, encoding)| *encoding)
+}
+
/// `resolveTerminalEncoding`'s mapping of the raw name: empty and UTF-8 are `utf8`; others lose every character but
/// letters and digits (`toIconvLiteEncoding`).
fn to_iconv_lite_encoding(raw: &str) -> String {
@@ -236,6 +286,16 @@ fn to_iconv_lite_encoding(raw: &str) -> String {
}
/// stdin.ts `stdinDataListener`: whether a `data` event comes within `timeout`; an end of input is none.
+#[cfg(windows)]
+fn stdin_has_data_within(timeout: Duration) -> bool {
+ let (sender, receiver) = std::sync::mpsc::channel();
+ // A pipe without data blocks the read; the thread ends with the process.
+ std::thread::spawn(move || sender.send(std::io::stdin().read(&mut [0]).is_ok_and(|read| read > 0)));
+ receiver.recv_timeout(timeout).unwrap_or(false)
+}
+
+/// stdin.ts `stdinDataListener`: whether a `data` event comes within `timeout`; an end of input is none.
+#[cfg(unix)]
fn stdin_has_data_within(timeout: Duration) -> bool {
let mut poll = libc::pollfd { fd: libc::STDIN_FILENO, events: libc::POLLIN, revents: 0 };
// SAFETY: one valid pollfd for the length passed.
@@ -243,7 +303,19 @@ fn stdin_has_data_within(timeout: Duration) -> bool {
ready > 0 && std::io::stdin().read(&mut [0]).is_ok_and(|read| read > 0)
}
+/// `process.stdout.columns` on a console (libuv's visible window width), else 80 (argv.ts `buildHelpMessage`).
+#[cfg(windows)]
+fn terminal_columns() -> usize {
+ use windows_sys::Win32::System::Console::{CONSOLE_SCREEN_BUFFER_INFO, GetConsoleScreenBufferInfo, GetStdHandle, STD_OUTPUT_HANDLE};
+ let mut info: CONSOLE_SCREEN_BUFFER_INFO = unsafe { std::mem::zeroed() };
+ // SAFETY: the standard output handle and one info struct for the call to fill.
+ let ok = unsafe { GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &mut info) } != 0;
+ let columns = i32::from(info.srWindow.Right) - i32::from(info.srWindow.Left) + 1;
+ if ok && columns > 0 && std::io::stdout().is_terminal() { columns as usize } else { 80 }
+}
+
/// `process.stdout.columns` on a terminal, else 80 (argv.ts `buildHelpMessage`).
+#[cfg(unix)]
fn terminal_columns() -> usize {
let mut size = libc::winsize { ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0 };
// SAFETY: TIOCGWINSZ writes one winsize to the pointer.
@@ -255,6 +327,14 @@ fn terminal_columns() -> usize {
mod tests {
use std::path::Path;
+ #[test]
+ fn chcp_output_maps_to_the_windows_terminal_encoding() {
+ assert_eq!(super::windows_terminal_encoding("Active code page: 852\r\n"), Some("cp852"));
+ assert_eq!(super::windows_terminal_encoding("Aktywna strona kodowa: 1252"), Some("cp1252"));
+ assert_eq!(super::windows_terminal_encoding("Active code page: 65001"), None);
+ assert_eq!(super::windows_terminal_encoding(""), None);
+ }
+
#[test]
fn terminal_encodings_map_to_iconv_lite_names() {
assert_eq!(super::to_iconv_lite_encoding(""), "utf8");
diff --git a/native/crates/app/src/clipboard.rs b/native/crates/app/src/clipboard.rs
index 7b807dc2cfb..5ee2bf6e7cb 100644
--- a/native/crates/app/src/clipboard.rs
+++ b/native/crates/app/src/clipboard.rs
@@ -109,6 +109,29 @@ mod pasteboard {
pub fn write_find_text(_text: &str) {}
}
+/// shortcut: as on Linux, the file list and HTML formats are not written or read on Windows yet (port/ledger.md M24 row
+/// app/src/clipboard.rs:91); the find text is macOS-only upstream.
+#[cfg(all(not(test), target_os = "windows"))]
+mod pasteboard {
+ pub fn write_data(_format: &str, _data: &[u8]) {}
+
+ pub fn add_data(_format: &str, _data: &[u8]) {}
+
+ pub fn read_data(_format: &str) -> Option<Vec<u8>> {
+ None
+ }
+
+ pub fn has(_format: &str) -> bool {
+ false
+ }
+
+ pub fn read_find_text() -> String {
+ String::new()
+ }
+
+ pub fn write_find_text(_text: &str) {}
+}
+
/// Tests run in parallel and must not touch the machine's pasteboards: each test thread has its own.
#[cfg(test)]
mod pasteboard {
diff --git a/native/crates/app/src/diagnostics.rs b/native/crates/app/src/diagnostics.rs
index 812e238ab45..073272fb1f5 100644
--- a/native/crates/app/src/diagnostics.rs
+++ b/native/crates/app/src/diagnostics.rs
@@ -344,6 +344,25 @@ pub fn machine() -> Machine {
}
}
+/// The running machine, as Node's `os` reports it on Windows.
+// shortcut: only the type, arch and CPU count; port/ledger.md M24 row app/src/diagnostics.rs:308 (GetSystemInfo,
+// GlobalMemoryStatusEx, RtlGetVersion and the processor name from the registry, as libuv win/util.c).
+#[cfg(target_os = "windows")]
+pub fn machine() -> Machine {
+ Machine {
+ os_type: "Windows_NT".into(),
+ arch: node_arch(),
+ release: String::new(),
+ cpu_model: String::new(),
+ cpu_count: std::thread::available_parallelism().map_or(0, usize::from),
+ cpu_speed: 0,
+ total_memory: 0.,
+ free_memory: 0.,
+ load_average: load_average(),
+ vm_hint: virtual_machine_hint(),
+ }
+}
+
/// The value of the first `key: value` line of a `/proc` file.
#[cfg(any(target_os = "linux", test))]
fn proc_field<'a>(text: &'a str, key: &str) -> Option<&'a str> {
@@ -360,6 +379,13 @@ fn node_arch() -> String {
std::env::consts::ARCH.replace("aarch64", "arm64").replace("x86_64", "x64")
}
+/// Node's `os.loadavg()` is `[0, 0, 0]` on Windows.
+#[cfg(target_os = "windows")]
+fn load_average() -> [f64; 3] {
+ [0.; 3]
+}
+
+#[cfg(unix)]
fn load_average() -> [f64; 3] {
let mut load_average = [0f64; 3];
// SAFETY: getloadavg writes at most the 3 elements it is given.
@@ -381,6 +407,13 @@ fn virtual_machine_hint() -> f64 {
/// Node's `os.networkInterfaces()` flattened: one entry per IPv4 or IPv6 address with its interface's MAC and
/// whether it is a loopback (`internal`).
+// shortcut: none on Windows yet, so the hint is 0; port/ledger.md M24 row app/src/diagnostics.rs:308 (GetAdaptersAddresses).
+#[cfg(target_os = "windows")]
+fn network_interfaces() -> Vec<(String, bool)> {
+ Vec::new()
+}
+
+#[cfg(unix)]
fn network_interfaces() -> Vec<(String, bool)> {
let mut macs: HashMap<String, String> = HashMap::new();
let mut addresses: Vec<(String, bool)> = Vec::new();
diff --git a/native/crates/app/src/keyboard_layout.rs b/native/crates/app/src/keyboard_layout.rs
index 8678dc033e7..a42d9c0af87 100644
--- a/native/crates/app/src/keyboard_layout.rs
+++ b/native/crates/app/src/keyboard_layout.rs
@@ -12,6 +12,10 @@ mod macos;
pub use linux::{current_key_event, current_layout_info, current_raw_mapping, xkb_key_code};
#[cfg(target_os = "macos")]
pub use macos::{current_key_event, current_layout_info, current_raw_mapping};
+#[cfg(target_os = "windows")]
+mod windows;
+#[cfg(target_os = "windows")]
+pub use windows::{current_key_event, current_layout_info, current_raw_mapping};
/// The DOM codes with a macOS virtual key code, in the order of chromium's dom_code_data.inc that native-keymap
/// walks (and so the order of the mapping's keys).
diff --git a/native/crates/app/src/keyboard_layout/windows.rs b/native/crates/app/src/keyboard_layout/windows.rs
new file mode 100644
index 00000000000..3a4005f3054
--- /dev/null
+++ b/native/crates/app/src/keyboard_layout/windows.rs
@@ -0,0 +1,19 @@
+//! shortcut: no layout data yet, as Linux without an X display: null layout and an empty raw mapping, so the
+//! fallback keyboard mapper dispatches on key codes; port/ledger.md M24 row app/src/keyboard_layout.rs:7
+//! (native-keymap's keyboard_win.cc).
+
+use serde_json::{Map, Value};
+
+use super::KeyEvent;
+
+pub fn current_key_event() -> Option<KeyEvent> {
+ None
+}
+
+pub fn current_layout_info() -> Value {
+ Value::Null
+}
+
+pub fn current_raw_mapping() -> Value {
+ Value::Object(Map::new())
+}
diff --git a/native/crates/app/src/launch.rs b/native/crates/app/src/launch.rs
index b2c9b26fa0b..433cf2fa7bf 100644
--- a/native/crates/app/src/launch.rs
+++ b/native/crates/app/src/launch.rs
@@ -1,13 +1,18 @@
//! launchMainService.ts and main.ts `claimInstance`: the first instance listens on `<user data>/<version>-main.sock`; a
//! later start with the same user data hands its arguments and working directory to it and exits.
+#[cfg(unix)]
use std::io::{BufRead, BufReader, Write};
+#[cfg(unix)]
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use futures::StreamExt;
-use futures::channel::mpsc::{UnboundedReceiver, unbounded};
+use futures::channel::mpsc::UnboundedReceiver;
+#[cfg(unix)]
+use futures::channel::mpsc::unbounded;
use gpui::App;
+#[cfg(unix)]
use serde_json::{Value, json};
/// What a second instance sends: its command line, working directory and whether a terminal's `code` started it
@@ -24,6 +29,7 @@ pub fn socket_path(user_data: &Path) -> PathBuf {
/// A second instance: true once the running one took the arguments. False when no instance listens (a stale socket is
/// removed then, as main.ts does on `ECONNREFUSED`).
+#[cfg(unix)]
pub fn send_to_running_instance(socket: &Path, args: &[String], cwd: &Path) -> bool {
let Ok(mut stream) = UnixStream::connect(socket) else {
let _ = std::fs::remove_file(socket);
@@ -39,6 +45,7 @@ pub fn send_to_running_instance(socket: &Path, args: &[String], cwd: &Path) -> b
}
/// `diagnosticsMainService.getMainDiagnostics` of the instance listening on `socket`; None when none listens.
+#[cfg(unix)]
pub fn request_main_diagnostics(socket: &Path) -> Option<crate::diagnostics::MainDiagnostics> {
let mut stream = UnixStream::connect(socket).ok()?;
writeln!(stream, "{}", json!({ "status": true })).ok()?;
@@ -48,6 +55,7 @@ pub fn request_main_diagnostics(socket: &Path) -> Option<crate::diagnostics::Mai
}
/// The first instance: each second instance's launch, answered once it is read.
+#[cfg(unix)]
pub fn listen(socket: &Path) -> Option<UnboundedReceiver<Launch>> {
let listener = UnixListener::bind(socket).inspect_err(|error| eprintln!("[launch] listening on {}: {error}", socket.display())).ok()?;
let (sender, receiver) = unbounded();
@@ -84,6 +92,22 @@ pub fn listen(socket: &Path) -> Option<UnboundedReceiver<Launch>> {
Some(receiver)
}
+// shortcut: every start is a first instance on Windows until main.ts `mainIPCHandle`'s named pipe is ported; port/ledger.md M24 row app/src/launch.rs:5.
+#[cfg(windows)]
+pub fn send_to_running_instance(_socket: &Path, _args: &[String], _cwd: &Path) -> bool {
+ false
+}
+
+#[cfg(windows)]
+pub fn request_main_diagnostics(_socket: &Path) -> Option<crate::diagnostics::MainDiagnostics> {
+ None
+}
+
+#[cfg(windows)]
+pub fn listen(_socket: &Path) -> Option<UnboundedReceiver<Launch>> {
+ None
+}
+
/// Opens each launch until the app quits.
pub fn handle_launches(mut launches: UnboundedReceiver<Launch>, cx: &mut App) {
cx.spawn(async move |cx| {
diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rs
index 5ba43c55ebd..4d2ef6f8bea 100644
--- a/native/crates/app/src/main.rs
+++ b/native/crates/app/src/main.rs
@@ -104,6 +104,7 @@ mod ghost_text;
mod language_detection;
mod encoding_guess;
mod settings_editor;
+#[cfg(unix)]
mod shell_env;
mod settings_import;
mod smart_snippet_inserter;
@@ -127,6 +128,8 @@ mod variables;
mod webview;
mod uri;
mod user_data_profile;
+#[cfg(target_os = "windows")]
+mod win32;
mod windows_state;
mod workbench;
mod workspace_trust;
@@ -183,7 +186,7 @@ fn main() -> anyhow::Result<()> {
// checkout they are the VS Code tree (VSCODE_SRC, native/vscode_src.rs).
#[cfg(target_os = "macos")]
let bundled = std::env::current_exe()?.parent().and_then(|macos| macos.parent()).map(|contents| contents.join("Resources/app"));
- #[cfg(target_os = "linux")]
+ #[cfg(any(target_os = "linux", target_os = "windows"))]
let bundled = std::env::current_exe()?.parent().map(|root| root.join("resources/app"));
let bundled = bundled.filter(|app| app.join("product.json").is_file());
// process.ts `cwd()`: cli.rs passes its folder in `VSCODE_CWD`, `open` starts the app in `/`.
@@ -975,6 +978,7 @@ fn open_shared_storage(shared_data: Option<PathBuf>) -> anyhow::Result<storage::
/// main.ts `resolveShellEnv` merged into `process.env`: a Dock launch gets the login shell's PATH for the host,
/// terminals and tasks. Runs before any thread starts, so changing the environment is sound.
+#[cfg(unix)]
fn apply_shell_env(force_disable: bool, user_data: &Path) -> Option<String> {
let env: std::collections::HashMap<String, String> = std::env::vars_os().filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?))).collect();
let user_settings = Settings::load(Registry::with_extensions(&[]), user_data.join("User"), None);
@@ -995,6 +999,12 @@ fn apply_shell_env(force_disable: bool, user_data: &Path) -> Option<String> {
}
}
+/// shellEnv.ts `getResolvedShellEnv` skips Windows: the process environment stays as it is.
+#[cfg(windows)]
+fn apply_shell_env(_force_disable: bool, _user_data: &Path) -> Option<String> {
+ None
+}
+
/// The built-in extensions: `VSCODE_GPUI_EXTENSIONS` (a checkout's set) or `<app root>/extensions`, then the dev
/// system extensions.
pub(crate) fn scan_system_extensions(app_root: &Path) -> anyhow::Result<Vec<ScannedExtension>> {
diff --git a/native/crates/app/src/metered_connection.rs b/native/crates/app/src/metered_connection.rs
index d11cee68118..2734cbe915c 100644
--- a/native/crates/app/src/metered_connection.rs
+++ b/native/crates/app/src/metered_connection.rs
@@ -72,6 +72,10 @@ pub fn watch(updates: UnboundedSender<bool>) {
});
}
+// shortcut: never metered on Windows yet; port/ledger.md M24 row app/src/metered_connection.rs:57 (INetworkCostManager).
+#[cfg(target_os = "windows")]
+pub fn watch(_updates: UnboundedSender<bool>) {}
+
/// `AbstractMeteredConnectionService`: `on` always, `off` never, `auto` (or any other value) the OS state.
pub fn is_metered(setting: Option<&str>, os_metered: bool) -> bool {
setting == Some("on") || (setting != Some("off") && os_metered)
diff --git a/native/crates/app/src/nls.rs b/native/crates/app/src/nls.rs
index 1ec82f4d216..591e7857c6f 100644
--- a/native/crates/app/src/nls.rs
+++ b/native/crates/app/src/nls.rs
@@ -141,6 +141,12 @@ fn os_locale() -> String {
}
}
+// shortcut: en-US until the Windows UI language is read; port/ledger.md M24 row app/src/nls.rs:146 (GetUserPreferredUILanguages).
+#[cfg(target_os = "windows")]
+fn os_locale() -> String {
+ "en-US".to_owned()
+}
+
pub fn process_zh_locale(locale: &str) -> String {
if !locale.starts_with("zh") {
return locale.to_owned();
diff --git a/native/crates/app/src/policy.rs b/native/crates/app/src/policy.rs
index 83e60d33335..2e1c3dd5540 100644
--- a/native/crates/app/src/policy.rs
+++ b/native/crates/app/src/policy.rs
@@ -14,6 +14,10 @@ mod macos;
pub use linux::{WATCHED_PATH, watch_policy_changes};
#[cfg(target_os = "macos")]
pub use macos::{WATCHED_PATH, watch_policy_changes};
+#[cfg(target_os = "windows")]
+mod windows;
+#[cfg(target_os = "windows")]
+pub use windows::{WATCHED_PATH, watch_policy_changes};
/// product.json `darwinBundleIdentifier`.
pub const BUNDLE_IDENTIFIER: &str = "com.rokartur.vsrustium";
@@ -21,7 +25,7 @@ pub const BUNDLE_IDENTIFIER: &str = "com.rokartur.vsrustium";
/// `createWatcher(productName, policyDefinitions)`'s first update: the value of every policy the registry
/// defines, read as the type `PolicyConfiguration.toPolicyDefinitionType` gives its setting.
/// filePolicyService.ts on Linux reads any JSON value under a defined policy name: no bundle id, no type check.
-#[cfg_attr(target_os = "linux", allow(unused_variables))]
+#[cfg_attr(any(target_os = "linux", target_os = "windows"), allow(unused_variables))]
pub fn read_native_policies(registry: &Registry, application: &str) -> PolicyValues {
#[cfg(target_os = "linux")]
let file = linux::read_policy_file(std::path::Path::new(WATCHED_PATH));
@@ -34,6 +38,8 @@ pub fn read_native_policies(registry: &Registry, application: &str) -> PolicyVal
let value = file.get(&name).cloned();
#[cfg(target_os = "macos")]
let value = macos::read_preference(application, &name, kind);
+ #[cfg(target_os = "windows")]
+ let value: Option<Value> = None;
if let Some(value) = value {
values.insert(name, value);
}
diff --git a/native/crates/app/src/policy/windows.rs b/native/crates/app/src/policy/windows.rs
new file mode 100644
index 00000000000..53d2963a7c8
--- /dev/null
+++ b/native/crates/app/src/policy/windows.rs
@@ -0,0 +1,7 @@
+//! shortcut: no registry policies yet, so none apply; port/ledger.md M24 row app/src/policy.rs:9
+//! (@vscode/policy-watcher's Windows side, `HKLM\Software\Policies`).
+
+/// Nothing to watch until the registry is read.
+pub const WATCHED_PATH: &str = "";
+
+pub fn watch_policy_changes(_path: &str, _on_change: impl Fn() + Send + 'static) {}
diff --git a/native/crates/app/src/power.rs b/native/crates/app/src/power.rs
index 85b813a301a..c17a2b76370 100644
--- a/native/crates/app/src/power.rs
+++ b/native/crates/app/src/power.rs
@@ -18,6 +18,12 @@ pub use linux::{animations_disabled, on_battery_power, system_idle_time, thermal
use macos::{Assertion, create_assertion, release_assertion, screen_locked};
#[cfg(target_os = "macos")]
pub use macos::{on_battery_power, system_idle_time, thermal_state, watch, watch_accessibility_display};
+#[cfg(target_os = "windows")]
+mod windows;
+#[cfg(target_os = "windows")]
+use windows::{Assertion, create_assertion, release_assertion, screen_locked};
+#[cfg(target_os = "windows")]
+pub use windows::{on_battery_power, system_idle_time, thermal_state, watch, watch_accessibility_display};
/// powerMonitor.getSystemIdleState (Chromium `CalculateIdleState`): locked first, then idle past the threshold.
pub fn system_idle_state(threshold: u64) -> &'static str {
diff --git a/native/crates/app/src/power/windows.rs b/native/crates/app/src/power/windows.rs
new file mode 100644
index 00000000000..2077e5c98e5
--- /dev/null
+++ b/native/crates/app/src/power/windows.rs
@@ -0,0 +1,35 @@
+//! shortcut: no powerMonitor yet: active, on AC, no blockers and no events; port/ledger.md M24 row app/src/power.rs:9
+//! (GetLastInputInfo, GetSystemPowerStatus, PowerSetRequest, WM_POWERBROADCAST).
+
+use futures::channel::mpsc::UnboundedSender;
+
+use super::PowerEvent;
+
+pub fn system_idle_time() -> u64 {
+ 0
+}
+
+pub(super) fn screen_locked() -> bool {
+ false
+}
+
+/// Electron has a thermal state on macOS only.
+pub fn thermal_state() -> &'static str {
+ "unknown"
+}
+
+pub fn on_battery_power() -> bool {
+ false
+}
+
+pub(super) type Assertion = ();
+
+pub(super) fn create_assertion(_blocker_type: &str) -> Option<Assertion> {
+ None
+}
+
+pub(super) fn release_assertion(_assertion: Assertion) {}
+
+pub fn watch(_events: UnboundedSender<PowerEvent>) {}
+
+pub fn watch_accessibility_display(_changed: UnboundedSender<()>) {}
diff --git a/native/crates/app/src/product.rs b/native/crates/app/src/product.rs
index dc4e78d0662..48bde6f0540 100644
--- a/native/crates/app/src/product.rs
+++ b/native/crates/app/src/product.rs
@@ -8,10 +8,10 @@ use std::sync::{LazyLock, OnceLock};
use serde_json::Value;
/// Where a packaged app keeps its files: VSRustium.app/Contents/Resources/app (package-app), or
-/// resources/app beside the binary in the Linux folder (package-linux), as VS Code's builds.
+/// resources/app beside the binary in the Linux and Windows folders (package-linux, package-windows), as VS Code's builds.
#[cfg(target_os = "macos")]
pub const BUNDLED_APP: &str = "Contents/Resources/app";
-#[cfg(target_os = "linux")]
+#[cfg(any(target_os = "linux", target_os = "windows"))]
pub const BUNDLED_APP: &str = "resources/app";
/// Whether `app_root` is a packaged app's, not the VS Code tree a checkout run reads.
diff --git a/native/crates/app/src/ps.rs b/native/crates/app/src/ps.rs
index 98c5165a94d..e107ba8fb01 100644
--- a/native/crates/app/src/ps.rs
+++ b/native/crates/app/src/ps.rs
@@ -2,6 +2,7 @@
//! tree under a root pid, each process named as `findName` names it. The process explorer (processExplorerControl.ts)
//! draws this tree.
+#[cfg(unix)]
use std::process::Command;
/// `ProcessItem`: CPU load in percent, memory in bytes.
@@ -17,6 +18,7 @@ pub struct ProcessItem {
}
/// Runs `ps` (with the `LC_NUMERIC` ps.ts sets, so `.` separates decimals) and returns the tree under `root_pid`.
+#[cfg(unix)]
pub fn list_processes(root_pid: u32, total_memory: f64) -> Result<ProcessItem, String> {
let output = Command::new("/bin/ps").args(["-ax", "-o", "pid=,ppid=,pcpu=,pmem=,command="]).env("LC_NUMERIC", "en_US.UTF-8").output().map_err(|error| error.to_string())?;
let stderr = String::from_utf8_lossy(&output.stderr);
@@ -27,8 +29,76 @@ pub fn list_processes(root_pid: u32, total_memory: f64) -> Result<ProcessItem, S
process_tree(&String::from_utf8_lossy(&output.stdout), root_pid, total_memory).ok_or_else(|| format!("Root process {root_pid} not found"))
}
+/// ps.ts on Windows (@vscode/windows-process-tree): the tree under `root_pid` from a process snapshot.
+// shortcut: no CPU load, memory or command line yet; port/ledger.md M24 row app/src/workbench/process_explorer.rs:295.
+#[cfg(windows)]
+pub fn list_processes(root_pid: u32, _total_memory: f64) -> Result<ProcessItem, String> {
+ let mut items: Vec<ProcessItem> = windows::snapshot()?
+ .into_iter()
+ .map(|(pid, ppid, name)| ProcessItem { name: find_name(&name), cmd: name, pid, ppid, load: 0., mem: 0., children: Vec::new() })
+ .collect();
+ let root = items.iter().position(|item| item.pid == root_pid).ok_or_else(|| format!("Root process {root_pid} not found"))?;
+ let root = items.swap_remove(root);
+ Ok(attach_children(root, &mut items))
+}
+
+/// The pids whose parent is `pid`.
+#[cfg(windows)]
+pub fn child_pids(pid: u32) -> Option<Vec<u32>> {
+ let processes = windows::snapshot().ok()?;
+ Some(processes.into_iter().filter(|(_, ppid, _)| *ppid == pid).map(|(child, _, _)| child).collect())
+}
+
+#[cfg(windows)]
+pub use windows::kill;
+
+#[cfg(windows)]
+mod windows {
+ use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
+ use windows_sys::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS};
+ use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_TERMINATE, TerminateProcess};
+
+ /// Every process as (pid, parent pid, executable name).
+ pub fn snapshot() -> Result<Vec<(u32, u32, String)>, String> {
+ // SAFETY: a snapshot of all processes, closed below.
+ let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
+ if snapshot == INVALID_HANDLE_VALUE {
+ return Err(std::io::Error::last_os_error().to_string());
+ }
+ let mut processes = Vec::new();
+ let mut entry = PROCESSENTRY32W { dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32, ..Default::default() };
+ // SAFETY: `entry` has its size set, as Process32FirstW requires.
+ let mut more = unsafe { Process32FirstW(snapshot, &mut entry) } != 0;
+ while more {
+ let length = entry.szExeFile.iter().position(|unit| *unit == 0).unwrap_or(entry.szExeFile.len());
+ processes.push((entry.th32ProcessID, entry.th32ParentProcessID, String::from_utf16_lossy(&entry.szExeFile[..length])));
+ // SAFETY: as above.
+ more = unsafe { Process32NextW(snapshot, &mut entry) } != 0;
+ }
+ // SAFETY: the snapshot handle is closed once.
+ unsafe { CloseHandle(snapshot) };
+ Ok(processes)
+ }
+
+ /// Node's `process.kill(pid, signal)` on Windows: TerminateProcess, whatever the signal.
+ pub fn kill(pid: u32) -> std::io::Result<()> {
+ // SAFETY: the handle OpenProcess returns is closed once.
+ unsafe {
+ let process = OpenProcess(PROCESS_TERMINATE, 0, pid);
+ if process.is_null() {
+ return Err(std::io::Error::last_os_error());
+ }
+ let terminated = TerminateProcess(process, 1) != 0;
+ let error = std::io::Error::last_os_error();
+ CloseHandle(process);
+ if terminated { Ok(()) } else { Err(error) }
+ }
+ }
+}
+
/// `parsePsOutput` with `addToTree`: a process joins the tree when it is the root or its parent already joined, as
/// ps lists parents before children; children are sorted by pid.
+#[cfg(any(unix, test))]
pub fn process_tree(stdout: &str, root_pid: u32, total_memory: f64) -> Option<ProcessItem> {
let mut items: Vec<ProcessItem> = Vec::new();
for line in stdout.lines() {
diff --git a/native/crates/app/src/settings_import.rs b/native/crates/app/src/settings_import.rs
index 5d408d528e4..cb2172a1d6d 100644
--- a/native/crates/app/src/settings_import.rs
+++ b/native/crates/app/src/settings_import.rs
@@ -27,6 +27,9 @@ pub fn sources(home: &Path) -> Vec<Source> {
// shortcut: ignores XDG_CONFIG_HOME, read it when a user moves ~/.config.
#[cfg(target_os = "linux")]
let support = home.join(".config");
+ // shortcut: the default %APPDATA%, not FOLDERID_RoamingAppData; read it when a user moves AppData.
+ #[cfg(target_os = "windows")]
+ let support = home.join("AppData").join("Roaming");
let source = |name, folder: &str, extensions: &str| Source { name, user_dir: support.join(folder).join("User"), extensions_dir: home.join(extensions).join("extensions") };
let all = [source("VS Code", "Code", ".vscode"), source("Cursor", "Cursor", ".cursor"), source("VSCodium", "VSCodium", ".vscode-oss")];
all.into_iter().filter(|source| source.user_dir.is_dir() || source.extensions_dir.is_dir()).collect()
diff --git a/native/crates/app/src/system_wide_keybindings.rs b/native/crates/app/src/system_wide_keybindings.rs
index 910b7b446c5..f9337660fb3 100644
--- a/native/crates/app/src/system_wide_keybindings.rs
+++ b/native/crates/app/src/system_wide_keybindings.rs
@@ -18,6 +18,10 @@ mod macos;
pub use linux::HotKeys;
#[cfg(target_os = "macos")]
pub use macos::HotKeys;
+#[cfg(target_os = "windows")]
+mod windows;
+#[cfg(target_os = "windows")]
+pub use windows::HotKeys;
#[derive(Clone, Debug, PartialEq)]
pub struct Candidate {
diff --git a/native/crates/app/src/system_wide_keybindings/windows.rs b/native/crates/app/src/system_wide_keybindings/windows.rs
new file mode 100644
index 00000000000..ffedc455154
--- /dev/null
+++ b/native/crates/app/src/system_wide_keybindings/windows.rs
@@ -0,0 +1,26 @@
+//! shortcut: no RegisterHotKey yet, so every registration fails and the workbench reports it; port/ledger.md M24
+//! row app/src/system_wide_keybindings.rs:13.
+
+use futures::channel::mpsc::UnboundedSender;
+
+use super::{Candidate, ShortcutRegistry};
+
+pub struct HotKeys;
+
+impl HotKeys {
+ pub fn new(_presses: UnboundedSender<u32>) -> HotKeys {
+ HotKeys
+ }
+
+ pub fn accelerator(&self, _id: u32) -> Option<&str> {
+ None
+ }
+}
+
+impl ShortcutRegistry for HotKeys {
+ fn register(&mut self, _binding: &Candidate) -> bool {
+ false
+ }
+
+ fn unregister(&mut self, _accelerator: &str) {}
+}
diff --git a/native/crates/app/src/terminal/completion_service.rs b/native/crates/app/src/terminal/completion_service.rs
index 3ec7a88760d..0af580fe329 100644
--- a/native/crates/app/src/terminal/completion_service.rs
+++ b/native/crates/app/src/terminal/completion_service.rs
@@ -347,7 +347,6 @@ struct Child {
/// The children of `folder` in readdir order, as the disk provider lists them. A dangling link is neither a file nor a
/// folder and is left out.
fn read_children(folder: &str) -> Option<Vec<Child>> {
- use std::os::unix::fs::PermissionsExt;
let mut children = Vec::new();
for entry in fs::read_dir(folder).ok()?.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
@@ -357,11 +356,22 @@ fn read_children(folder: &str) -> Option<Vec<Child>> {
continue;
}
let is_symbolic_link = fs::symlink_metadata(&path).is_ok_and(|link| link.file_type().is_symlink());
- children.push(Child { name, path, is_directory: metadata.is_dir(), is_symbolic_link, executable: metadata.permissions().mode() & 0o111 != 0 });
+ children.push(Child { name, path, is_directory: metadata.is_dir(), is_symbolic_link, executable: executable(&metadata) });
}
Some(children)
}
+#[cfg(unix)]
+fn executable(metadata: &fs::Metadata) -> bool {
+ std::os::unix::fs::PermissionsExt::mode(&metadata.permissions()) & 0o111 != 0
+}
+
+/// terminalCompletionService.ts filters the command position by the executable bit only with Unix-style paths.
+#[cfg(windows)]
+fn executable(_metadata: &fs::Metadata) -> bool {
+ true
+}
+
/// `getFriendlyPath`: `getUriLabel(uri, { noPrefix: true })`, which on macOS and Linux is the normalized path
/// with the user home tildified, and a trailing `/` for folders.
fn friendly_path(path: &str, kind: TerminalCompletionItemKind) -> String {
diff --git a/native/crates/app/src/terminal/profiles.rs b/native/crates/app/src/terminal/profiles.rs
index f11f0175fff..db84dd190a4 100644
--- a/native/crates/app/src/terminal/profiles.rs
+++ b/native/crates/app/src/terminal/profiles.rs
@@ -129,6 +129,7 @@ pub fn system_shell(env: &HashMap<String, String>) -> String {
if shell == "/bin/false" { "/bin/bash".into() } else { shell }
}
+#[cfg(unix)]
fn login_shell() -> Option<String> {
let entry = unsafe { libc::getpwuid(libc::getuid()) };
if entry.is_null() || unsafe { (*entry).pw_shell.is_null() } {
@@ -137,6 +138,12 @@ fn login_shell() -> Option<String> {
Some(unsafe { std::ffi::CStr::from_ptr((*entry).pw_shell) }.to_string_lossy().into_owned())
}
+// shortcut: no PowerShell detection yet (shell.ts `getSystemShellWindows`), so $SHELL or sh; port/ledger.md M24 row app/src/terminal/profiles.rs:133.
+#[cfg(windows)]
+fn login_shell() -> Option<String> {
+ None
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/native/crates/app/src/terminal/pty.rs b/native/crates/app/src/terminal/pty.rs
index b73bc162ee3..94aa7c960f1 100644
--- a/native/crates/app/src/terminal/pty.rs
+++ b/native/crates/app/src/terminal/pty.rs
@@ -1,29 +1,44 @@
//! node-pty's unix `spawn` (pty.cc `PtyFork`): the shell runs in a new session whose controlling terminal is a fresh
//! PTY; its output is read on a thread and its exit is waited for on another.
+#[cfg(unix)]
use std::collections::HashMap;
#[cfg(target_os = "macos")]
use std::ffi::CStr;
+#[cfg(unix)]
use std::fs::File;
+#[cfg(unix)]
use std::io::{self, Read, Write};
+#[cfg(unix)]
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
+#[cfg(unix)]
use std::os::unix::process::CommandExt;
+#[cfg(unix)]
use std::path::Path;
+#[cfg(unix)]
use std::process::{Command, Stdio};
+#[cfg(unix)]
use futures::channel::mpsc::UnboundedSender;
+#[cfg(windows)]
+mod conpty;
+#[cfg(windows)]
+pub use conpty::Pty;
+
pub enum PtyEvent {
Data(Vec<u8>),
/// The process exited, with its exit code; `None` when a signal ended it.
Exit(Option<i32>),
}
+#[cfg(unix)]
pub struct Pty {
master: File,
pub pid: i32,
}
+#[cfg(unix)]
impl Pty {
pub fn spawn(executable: &Path, args: &[String], cwd: &Path, env: &HashMap<String, String>, cols: u16, rows: u16, events: UnboundedSender<PtyEvent>) -> io::Result<Pty> {
let (master, slave) = open_pty(cols, rows)?;
@@ -154,12 +169,14 @@ impl Pty {
}
}
+#[cfg(unix)]
impl Drop for Pty {
fn drop(&mut self) {
self.kill(libc::SIGHUP);
}
}
+#[cfg(unix)]
fn open_pty(cols: u16, rows: u16) -> io::Result<(OwnedFd, OwnedFd)> {
let (mut master, mut slave) = (0, 0);
let mut size = libc::winsize { ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0 };
@@ -178,3 +195,72 @@ fn open_pty(cols: u16, rows: u16) -> io::Result<(OwnedFd, OwnedFd)> {
}
Ok((master, slave))
}
+
+/// node-pty windowsPtyAgent.ts `argsToCommandLine`: the file and its arguments quoted as the MSVC runtime parses
+/// a command line.
+#[cfg(any(windows, test))]
+fn args_to_command_line(file: &str, args: &[String]) -> String {
+ let mut result = String::new();
+ for (index, arg) in std::iter::once(file).chain(args.iter().map(String::as_str)).enumerate() {
+ if index > 0 {
+ result.push(' ');
+ }
+ let (starts, ends) = (arg.starts_with('"'), arg.ends_with('"'));
+ let lopsided = starts != ends;
+ let unquoted = !starts && !ends;
+ let quote = arg.is_empty() || (arg.contains(' ') || arg.contains('\t')) && arg.chars().count() > 1 && (lopsided || unquoted);
+ if quote {
+ result.push('"');
+ }
+ let mut backslashes = 0;
+ for char in arg.chars() {
+ match char {
+ '\\' => backslashes += 1,
+ '"' => {
+ result.push_str(&"\\".repeat(backslashes * 2 + 1));
+ result.push('"');
+ backslashes = 0;
+ }
+ char => {
+ result.push_str(&"\\".repeat(backslashes));
+ backslashes = 0;
+ result.push(char);
+ }
+ }
+ }
+ if quote {
+ result.push_str(&"\\".repeat(backslashes * 2));
+ result.push('"');
+ } else {
+ result.push_str(&"\\".repeat(backslashes));
+ }
+ }
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::args_to_command_line;
+
+ fn line(file: &str, args: &[&str]) -> String {
+ args_to_command_line(file, &args.iter().map(|arg| arg.to_string()).collect::<Vec<_>>())
+ }
+
+ /// Each expected line is what node-pty 1.x lib/windowsPtyAgent.js `argsToCommandLine` returns for the same input.
+ #[test]
+ fn args_to_command_line_quotes_as_node_pty() {
+ assert_eq!(line("file", &[]), "file");
+ assert_eq!(line("file", &["foo"]), "file foo");
+ assert_eq!(line("file", &["foo", "bar"]), "file foo bar");
+ assert_eq!(line("file", &[""]), r#"file """#);
+ assert_eq!(line("file", &["foo bar"]), r#"file "foo bar""#);
+ assert_eq!(line("file", &["foo\tbar"]), "file \"foo\tbar\"");
+ assert_eq!(line("file", &[r#""foo bar""#]), r#"file \"foo bar\""#);
+ assert_eq!(line("file", &[r#"foo"bar"#]), r#"file foo\"bar"#);
+ assert_eq!(line("file", &[r#""foo bar"#]), r#"file "\"foo bar""#);
+ assert_eq!(line("file", &[r#"foo\bar"#]), r#"file foo\bar"#);
+ assert_eq!(line("file", &[r#"foo\ bar\"#]), r#"file "foo\ bar\\""#);
+ assert_eq!(line("file", &[r#"foo\"bar"#]), r#"file foo\\\"bar"#);
+ assert_eq!(line("C:\\Program Files\\pwsh.exe", &["-NoLogo"]), r#""C:\Program Files\pwsh.exe" -NoLogo"#);
+ }
+}
diff --git a/native/crates/app/src/terminal/pty/conpty.rs b/native/crates/app/src/terminal/pty/conpty.rs
new file mode 100644
index 00000000000..df4d5e522e0
--- /dev/null
+++ b/native/crates/app/src/terminal/pty/conpty.rs
@@ -0,0 +1,209 @@
+//! node-pty's Windows `spawn` (conpty.cc `PtyStartProcess` and `PtyConnect`): the shell runs attached to a fresh
+//! pseudoconsole; its output is read on a thread and its exit is waited for on another.
+
+use std::collections::HashMap;
+use std::ffi::OsStr;
+use std::fs::File;
+use std::io::{self, Read, Write};
+use std::os::windows::ffi::OsStrExt;
+use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
+use std::path::Path;
+use std::sync::Arc;
+
+use futures::channel::mpsc::UnboundedSender;
+use windows_sys::Win32::Foundation::HANDLE;
+use windows_sys::Win32::System::Console::{COORD, ClosePseudoConsole, CreatePseudoConsole, HPCON, ResizePseudoConsole};
+use windows_sys::Win32::System::Pipes::CreatePipe;
+use windows_sys::Win32::System::Threading::{
+ CREATE_UNICODE_ENVIRONMENT, CreateProcessW, DeleteProcThreadAttributeList, EXTENDED_STARTUPINFO_PRESENT, GetExitCodeProcess, INFINITE,
+ InitializeProcThreadAttributeList, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, PROCESS_INFORMATION, STARTUPINFOEXW, TerminateProcess,
+ UpdateProcThreadAttribute, WaitForSingleObject,
+};
+
+use super::{PtyEvent, args_to_command_line};
+
+pub struct Pty {
+ console: HPCON,
+ input: File,
+ process: Arc<OwnedHandle>,
+ executable: String,
+ cwd: String,
+ pub pid: i32,
+}
+
+impl Pty {
+ pub fn spawn(executable: &Path, args: &[String], cwd: &Path, env: &HashMap<String, String>, cols: u16, rows: u16, events: UnboundedSender<PtyEvent>) -> io::Result<Pty> {
+ let (console_input, input) = pipe()?;
+ let (output, console_output) = pipe()?;
+ let mut console: HPCON = 0;
+ // SAFETY: both pipe ends are open; the console duplicates them, so ours close at the end of this function.
+ check_hresult(unsafe { CreatePseudoConsole(size(cols, rows), console_input.as_raw_handle(), console_output.as_raw_handle(), 0, &mut console) })?;
+ let started = start_process(console, executable, args, cwd, env);
+ let (process, pid) = match started {
+ Ok(started) => started,
+ Err(error) => {
+ // SAFETY: the console CreatePseudoConsole returned, closed once.
+ unsafe { ClosePseudoConsole(console) };
+ return Err(error);
+ }
+ };
+ let process = Arc::new(process);
+ let mut reader = output;
+ let data_events = events.clone();
+ std::thread::Builder::new().name("pty-read".into()).spawn(move || {
+ let mut buffer = vec![0; 64 * 1024];
+ loop {
+ match reader.read(&mut buffer) {
+ Ok(0) | Err(_) => break,
+ Ok(read) => {
+ if data_events.unbounded_send(PtyEvent::Data(buffer[..read].to_vec())).is_err() {
+ break;
+ }
+ }
+ }
+ }
+ })?;
+ let waited = process.clone();
+ std::thread::Builder::new().name("pty-wait".into()).spawn(move || {
+ let mut code = 0;
+ // SAFETY: the process handle stays open while `waited` holds it.
+ let exited = unsafe { WaitForSingleObject(waited.as_raw_handle(), INFINITE) == 0 && GetExitCodeProcess(waited.as_raw_handle(), &mut code) != 0 };
+ // windowsPtyAgent.ts flushes the output for FLUSH_DATA_INTERVAL (1 s) after the shell exited.
+ std::thread::sleep(std::time::Duration::from_secs(1));
+ let _ = events.unbounded_send(PtyEvent::Exit(exited.then_some(code as i32)));
+ })?;
+ let executable = executable.to_string_lossy().into_owned();
+ Ok(Pty { console, input, process, executable, cwd: cwd.to_string_lossy().into_owned(), pid: pid as i32 })
+ }
+
+ pub fn write(&mut self, data: &[u8]) {
+ // A write after the console closed fails; node-pty drops it the same way.
+ let _ = self.input.write_all(data);
+ }
+
+ pub fn resize(&self, cols: u16, rows: u16) {
+ // SAFETY: the console stays open until drop.
+ unsafe { ResizePseudoConsole(self.console, size(cols, rows)) };
+ }
+
+ /// windowsTerminal.ts `kill(signal)` throws "Signals not supported on windows."; without a signal it ends the shell.
+ pub fn kill(&self, signal: i32) {
+ eprintln!("[terminal] signal {signal}: Signals not supported on windows.");
+ }
+
+ /// childProcessMonitor.ts `hasChildProcesses`: a process whose parent is the shell.
+ pub fn has_child_processes(&self) -> bool {
+ crate::ps::child_pids(self.pid as u32).is_some_and(|children| !children.is_empty())
+ }
+
+ /// windowsTerminal.ts `process`: the name of the file the terminal started.
+ pub fn foreground_process(&self) -> Option<String> {
+ Some(self.executable.clone())
+ }
+
+ /// terminalProcess.ts `getCwd` on Windows: the initial cwd, as no API reads another process's.
+ pub fn cwd(&self) -> Option<String> {
+ Some(self.cwd.clone())
+ }
+}
+
+impl Drop for Pty {
+ /// windowsPtyAgent.ts `kill`: the console closes, which ends the processes attached to it, then the shell ends.
+ fn drop(&mut self) {
+ // SAFETY: the process handle is open.
+ unsafe { TerminateProcess(self.process.as_raw_handle(), 1) };
+ let console = self.console;
+ // Before Windows 11 24H2 ClosePseudoConsole waits until its output is read; node-pty closes it off the main thread too.
+ // SAFETY: the console is closed only here.
+ std::thread::spawn(move || unsafe { ClosePseudoConsole(console) });
+ }
+}
+
+fn size(cols: u16, rows: u16) -> COORD {
+ COORD { X: cols as i16, Y: rows as i16 }
+}
+
+/// A read end and a write end, neither inherited.
+fn pipe() -> io::Result<(File, File)> {
+ let (mut read, mut write): (HANDLE, HANDLE) = (std::ptr::null_mut(), std::ptr::null_mut());
+ // SAFETY: both out pointers are valid; on success each handle is owned once.
+ if unsafe { CreatePipe(&mut read, &mut write, std::ptr::null(), 0) } == 0 {
+ return Err(io::Error::last_os_error());
+ }
+ // SAFETY: fresh handles CreatePipe returned.
+ Ok(unsafe { (File::from_raw_handle(read), File::from_raw_handle(write)) })
+}
+
+fn check_hresult(result: i32) -> io::Result<()> {
+ match result {
+ 0 => Ok(()),
+ error => Err(io::Error::from_raw_os_error(error)),
+ }
+}
+
+/// conpty.cc `PtyConnect`: CreateProcessW with the console in the startup attributes, the environment as a sorted
+/// UTF-16 block (libuv's `make_program_env`).
+fn start_process(console: HPCON, executable: &Path, args: &[String], cwd: &Path, env: &HashMap<String, String>) -> io::Result<(OwnedHandle, u32)> {
+ let mut command_line = wide(OsStr::new(&args_to_command_line(&executable.to_string_lossy(), args)));
+ let cwd = wide(cwd.as_os_str());
+ let mut variables: Vec<_> = env.iter().collect();
+ variables.sort_by_key(|(name, _)| name.to_uppercase());
+ let mut block: Vec<u16> = Vec::new();
+ for (name, value) in variables {
+ block.extend(OsStr::new(&format!("{name}={value}")).encode_wide());
+ block.push(0);
+ }
+ // An empty block is two NULs.
+ if block.is_empty() {
+ block.push(0);
+ }
+ block.push(0);
+
+ let mut list_size = 0;
+ // SAFETY: the size query with a null list, as documented.
+ unsafe { InitializeProcThreadAttributeList(std::ptr::null_mut(), 1, 0, &mut list_size) };
+ let mut list = vec![0u8; list_size];
+ let mut startup: STARTUPINFOEXW = unsafe { std::mem::zeroed() };
+ startup.StartupInfo.cb = std::mem::size_of::<STARTUPINFOEXW>() as u32;
+ startup.lpAttributeList = list.as_mut_ptr().cast();
+ // SAFETY: `list` has the size the query gave and outlives the attribute list, deleted below.
+ if unsafe { InitializeProcThreadAttributeList(startup.lpAttributeList, 1, 0, &mut list_size) } == 0 {
+ return Err(io::Error::last_os_error());
+ }
+ // SAFETY: the attribute value is the HPCON itself, as conpty.cc passes it.
+ let updated = unsafe {
+ UpdateProcThreadAttribute(startup.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE as usize, console as *const _, std::mem::size_of::<HPCON>(), std::ptr::null_mut(), std::ptr::null())
+ };
+ let mut info: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
+ // SAFETY: every pointer is valid for the call; the command line buffer is mutable as CreateProcessW requires.
+ let created = updated != 0
+ && unsafe {
+ CreateProcessW(
+ std::ptr::null(),
+ command_line.as_mut_ptr(),
+ std::ptr::null(),
+ std::ptr::null(),
+ 0,
+ EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT,
+ block.as_ptr().cast(),
+ cwd.as_ptr(),
+ &startup.StartupInfo,
+ &mut info,
+ )
+ } != 0;
+ let error = io::Error::last_os_error();
+ // SAFETY: initialized above.
+ unsafe { DeleteProcThreadAttributeList(startup.lpAttributeList) };
+ if !created {
+ return Err(error);
+ }
+ // SAFETY: fresh handles CreateProcessW returned; the thread handle is not needed.
+ unsafe {
+ drop(OwnedHandle::from_raw_handle(info.hThread));
+ Ok((OwnedHandle::from_raw_handle(info.hProcess), info.dwProcessId))
+ }
+}
+
+fn wide(text: &OsStr) -> Vec<u16> {
+ text.encode_wide().chain(std::iter::once(0)).collect()
+}
diff --git a/native/crates/app/src/update.rs b/native/crates/app/src/update.rs
index 202bf3f53f9..72489a746c6 100644
--- a/native/crates/app/src/update.rs
+++ b/native/crates/app/src/update.rs
@@ -364,7 +364,7 @@ impl UpdateService {
/// The connection turned metered during an automatic check: `deferAutomaticDownload`, as the darwin flow's
/// check without download (`checkForUpdateNoDownload`).
fn found_update(&mut self, update: Update, explicit: bool, cx: &mut Context<Self>) {
- if cfg!(target_os = "linux") {
+ if cfg!(any(target_os = "linux", target_os = "windows")) {
self.set_state(State::AvailableForDownload { update }, cx);
return;
}
@@ -386,7 +386,8 @@ impl UpdateService {
self.deferred = true;
return;
}
- if cfg!(target_os = "linux") {
+ // Windows as Linux until the user setup updates in place (port/ledger.md decision "Windows updates").
+ if cfg!(any(target_os = "linux", target_os = "windows")) {
// updateService.linux.ts: the package type is unknown, so product.json `downloadUrl` beats the archive.
let download_url = crate::product::get("downloadUrl").as_str().filter(|url| !url.is_empty()).unwrap_or(&update.url).to_owned();
cx.open_url(&download_url);
@@ -474,9 +475,8 @@ impl UpdateService {
/// Squirrel's read-only check (macOS), then the feed.
fn find_update(config: &Config, channel: &str) -> anyhow::Result<Option<Update>> {
- if cfg!(target_os = "macos") {
- install::check_writable(&config.bundle)?;
- }
+ #[cfg(target_os = "macos")]
+ install::check_writable(&config.bundle)?;
let url = feed_url(&config.update_url, exthost::gallery::CURRENT_TARGET_PLATFORM, channel);
let (status, body) = fetch_feed(&url)?;
if status != 200 {
diff --git a/native/crates/app/src/update/install.rs b/native/crates/app/src/update/install.rs
index 98539f917f8..cbc2e2b01ba 100644
--- a/native/crates/app/src/update/install.rs
+++ b/native/crates/app/src/update/install.rs
@@ -17,8 +17,8 @@ pub fn running_bundle() -> Option<PathBuf> {
(bundle.extension()? == "app" && executable.parent()?.ends_with("Contents/MacOS")).then(|| bundle.to_path_buf())
}
-/// The Linux archive's folder (port/tools/package-linux): the executable beside `resources/app`.
-#[cfg(target_os = "linux")]
+/// The Linux and Windows archive's folder (port/tools/package-linux): the executable beside `resources/app`.
+#[cfg(any(target_os = "linux", target_os = "windows"))]
pub fn running_bundle() -> Option<PathBuf> {
let folder = std::env::current_exe().ok()?.parent()?.to_path_buf();
folder.join("resources/app").is_dir().then_some(folder)
@@ -33,6 +33,7 @@ pub fn shipit_dir() -> PathBuf {
/// SQRLUpdater's check before it looks for updates: a bundle that cannot be replaced (a mounted disk image, App
/// Translocation's read-only mount, a folder without write access) is never updated. Its message, as Electron
/// joins the error's description and recovery suggestion.
+#[cfg(unix)]
pub fn check_writable(bundle: &Path) -> anyhow::Result<()> {
let writable = |path: &Path| {
let path = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).expect("a path without NUL");
@@ -117,6 +118,7 @@ pub const APPLY_UPDATE: &str = "--apply-update";
/// Starts the helper (ShipIt) from this executable, in its own process group so it outlives the app, logging to
/// `ShipIt_stderr.log`. With `relaunch` it starts the app again with this process's arguments.
+#[cfg(unix)]
pub fn spawn_helper(staged: &Path, installed: &Path, relaunch: bool) -> anyhow::Result<()> {
use std::os::unix::process::CommandExt;
let log = std::fs::OpenOptions::new().create(true).append(true).open(shipit_dir().join("ShipIt_stderr.log"))?;
@@ -154,6 +156,18 @@ pub fn apply_update(args: &[String]) -> anyhow::Result<()> {
swapped
}
+/// Windows updates are a download link (port/ledger.md decision "Windows updates"): no update is ever staged.
+#[cfg(windows)]
+pub fn spawn_helper(_staged: &Path, _installed: &Path, _relaunch: bool) -> anyhow::Result<()> {
+ bail!("updates are not installed in place on Windows")
+}
+
+#[cfg(windows)]
+fn wait_for_exit(_pid: u32) -> anyhow::Result<()> {
+ bail!("updates are not installed in place on Windows")
+}
+
+#[cfg(unix)]
fn wait_for_exit(pid: libc::pid_t) -> anyhow::Result<()> {
for _ in 0..3000 {
if unsafe { libc::kill(pid, 0) } != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) {
diff --git a/native/crates/app/src/webview.rs b/native/crates/app/src/webview.rs
index 3bfc2509cdc..ee41e4383f6 100644
--- a/native/crates/app/src/webview.rs
+++ b/native/crates/app/src/webview.rs
@@ -16,6 +16,10 @@ mod macos;
pub use linux::{ClipView, Retained, Webview, gpui_x_window, pump_gtk, place, supported};
#[cfg(target_os = "macos")]
pub use macos::{ClipView, Retained, Webview, place, supported};
+#[cfg(target_os = "windows")]
+mod windows;
+#[cfg(target_os = "windows")]
+pub use windows::{ClipView, Retained, Webview, place, supported};
/// common/webview.ts `webviewRootResourceAuthority`.
const RESOURCE_AUTHORITY: &str = "vscode-resource.vscode-cdn.net";
diff --git a/native/crates/app/src/webview/windows.rs b/native/crates/app/src/webview/windows.rs
new file mode 100644
index 00000000000..222c7e70137
--- /dev/null
+++ b/native/crates/app/src/webview/windows.rs
@@ -0,0 +1,106 @@
+//! shortcut: no WebView2 yet, so `supported` is false and the views show their fallback; port/ledger.md M24 row
+//! app/src/webview.rs:11 (webview2-com).
+
+use std::path::PathBuf;
+
+use futures::channel::mpsc::UnboundedSender;
+use gpui::{Bounds, Pixels, Window};
+use serde_json::Value;
+
+pub use std::rc::Rc as Retained;
+
+use super::WebviewEvent;
+
+pub enum View {}
+
+pub enum Webview {}
+
+pub enum ClipView {}
+
+pub fn supported() -> bool {
+ false
+}
+
+impl Webview {
+ pub fn new(_window: &Window, _id: &str, _origin: &str, _extension_id: &str, _pre_dir: PathBuf, _roots: Vec<files::Resource>, _events: UnboundedSender<WebviewEvent>) -> Self {
+ unreachable!("webview::supported() is false on Windows")
+ }
+
+ pub fn send(&mut self, _channel: &str, _data: Value) {
+ match *self {}
+ }
+
+ pub fn did_become_ready(&mut self) {
+ match *self {}
+ }
+
+ pub fn set_local_resource_roots(&self, _roots: Vec<files::Resource>) {
+ match *self {}
+ }
+
+ pub fn view(&self) -> View {
+ match *self {}
+ }
+
+ pub fn hide(&self) {
+ match *self {}
+ }
+
+ pub fn focus(&mut self) {
+ match *self {}
+ }
+
+ pub fn clipboard_command(&mut self, _command: &str) {
+ match *self {}
+ }
+
+ pub fn take_keyboard(&self) {
+ match *self {}
+ }
+
+ pub fn release_keyboard(&self) {
+ match *self {}
+ }
+
+ pub fn has_keyboard(&self) -> bool {
+ match *self {}
+ }
+
+ pub fn show_find(&self, _styles: &Value, _icons: [String; 3]) {
+ match *self {}
+ }
+
+ pub fn hide_find(&self) {
+ match *self {}
+ }
+
+ pub fn find(&self, _previous: bool) {
+ match *self {}
+ }
+
+ pub fn open_inspector(&self) {
+ match *self {}
+ }
+}
+
+pub fn place(view: &View, _window: &Window, _bounds: Bounds<Pixels>) {
+ match *view {}
+}
+
+impl ClipView {
+ pub fn hide(&self) {
+ match *self {}
+ }
+
+ pub fn remove(&self) {
+ match *self {}
+ }
+
+ pub fn new(_window: &Window, webview: &Webview) -> Retained<Self> {
+ match *webview {}
+ }
+
+ pub fn place(&self, _webview: &View, _window: &Window, _bounds: Bounds<Pixels>, _webview_frame: Bounds<Pixels>, _hit_rects: Vec<Bounds<Pixels>>, _hole: Option<Bounds<Pixels>>) {
+ match *self {}
+ }
+}
diff --git a/native/crates/app/src/win32.rs b/native/crates/app/src/win32.rs
new file mode 100644
index 00000000000..bd9afc306b8
--- /dev/null
+++ b/native/crates/app/src/win32.rs
@@ -0,0 +1,28 @@
+//! Win32 calls on GPUI's windows.
+
+use gpui::Window;
+use raw_window_handle::{HasWindowHandle, RawWindowHandle};
+use windows_sys::Win32::Foundation::HWND;
+use windows_sys::Win32::UI::WindowsAndMessaging::{
+ GWL_EXSTYLE, GetWindowLongPtrW, HWND_NOTOPMOST, HWND_TOPMOST, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SetWindowPos, WS_EX_TOPMOST,
+};
+
+/// The HWND of a GPUI window, which GPUI's Windows platform always has.
+pub fn hwnd(window: &Window) -> HWND {
+ match HasWindowHandle::window_handle(window).expect("a GPUI window has a handle").as_raw() {
+ RawWindowHandle::Win32(handle) => handle.hwnd.get() as HWND,
+ handle => unreachable!("GPUI's Windows platform gave {handle:?}"),
+ }
+}
+
+/// Chromium's HWNDMessageHandler `SetAlwaysOnTop` reads it back from the extended style.
+pub fn is_always_on_top(window: &Window) -> bool {
+ // SAFETY: a live window's HWND.
+ unsafe { GetWindowLongPtrW(hwnd(window), GWL_EXSTYLE) as u32 & WS_EX_TOPMOST != 0 }
+}
+
+pub fn set_always_on_top(window: &Window, on_top: bool) {
+ let after = if on_top { HWND_TOPMOST } else { HWND_NOTOPMOST };
+ // SAFETY: a live window's HWND; only the z-order changes.
+ unsafe { SetWindowPos(hwnd(window), after, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE) };
+}
diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rs
index ec142b1963e..c56166c9905 100644
--- a/native/crates/app/src/workbench.rs
+++ b/native/crates/app/src/workbench.rs
@@ -100,6 +100,7 @@ mod auto_save;
pub(crate) mod host;
mod power;
pub(crate) mod command_line;
+#[cfg(unix)]
mod shell_command;
mod relauncher;
mod update;
@@ -1112,6 +1113,7 @@ impl Workbench {
workbench.register_workspace_commands();
workbench.register_workspace_editing_commands();
workbench.register_dialog_commands();
+ #[cfg(unix)]
workbench.register_shell_command_commands();
workbench.register_lifecycle_commands();
workbench.register_banner_commands();
@@ -2231,7 +2233,7 @@ fn is_tahoe_or_newer() -> bool {
*TAHOE
}
-#[cfg(target_os = "linux")]
+#[cfg(any(target_os = "linux", target_os = "windows"))]
fn is_tahoe_or_newer() -> bool {
false
}
diff --git a/native/crates/app/src/workbench/accessibility.rs b/native/crates/app/src/workbench/accessibility.rs
index e728b0e215b..4664a314d7d 100644
--- a/native/crates/app/src/workbench/accessibility.rs
+++ b/native/crates/app/src/workbench/accessibility.rs
@@ -142,6 +142,9 @@ impl Workbench {
_ => objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion(),
#[cfg(target_os = "linux")]
_ => crate::power::animations_disabled(),
+ // shortcut: motion never reduced by the OS yet; port/ledger.md M24 row app/src/workbench/accessibility.rs:531.
+ #[cfg(target_os = "windows")]
+ _ => false,
}
}
@@ -550,6 +553,15 @@ pub(crate) fn screen_reader_running() -> bool {
SCREEN_READER_ENABLED.load(std::sync::atomic::Ordering::Relaxed)
}
+// shortcut: no screen reader detection on Windows yet; port/ledger.md M24 row app/src/workbench/accessibility.rs:531.
+#[cfg(target_os = "windows")]
+pub(crate) fn screen_reader_running() -> bool {
+ false
+}
+
+#[cfg(target_os = "windows")]
+pub(crate) fn watch_assistive_apps(_cx: &mut gpui::App) {}
+
#[cfg(target_os = "linux")]
static SCREEN_READER_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
diff --git a/native/crates/app/src/workbench/dialogs.rs b/native/crates/app/src/workbench/dialogs.rs
index 9cfa06cea79..c179175916b 100644
--- a/native/crates/app/src/workbench/dialogs.rs
+++ b/native/crates/app/src/workbench/dialogs.rs
@@ -59,6 +59,14 @@ impl Workbench {
}
/// `IOSProperties` as Node's `os` gives them: type, arch and release.
+#[cfg(windows)]
+fn os_properties() -> (String, String, String) {
+ let machine = crate::diagnostics::machine();
+ (machine.os_type, machine.arch, machine.release)
+}
+
+/// `IOSProperties` as Node's `os` gives them: type, arch and release.
+#[cfg(unix)]
fn os_properties() -> (String, String, String) {
// SAFETY: uname fills the zeroed struct with NUL-terminated strings.
let release = unsafe {
diff --git a/native/crates/app/src/workbench/host.rs b/native/crates/app/src/workbench/host.rs
index 0a92991db41..323fc4787bd 100644
--- a/native/crates/app/src/workbench/host.rs
+++ b/native/crates/app/src/workbench/host.rs
@@ -411,6 +411,11 @@ fn set_always_on_top(window: &Window, on_top: bool) {
crate::dialog::ns_window(window).setLevel(if on_top { NSFloatingWindowLevel } else { NSNormalWindowLevel });
}
+#[cfg(target_os = "windows")]
+pub(super) use crate::win32::is_always_on_top;
+#[cfg(target_os = "windows")]
+use crate::win32::set_always_on_top;
+
#[cfg(target_os = "linux")]
thread_local! {
/// The windows set always on top: Chromium's X11 and Wayland windows keep the z-order level they were given and
diff --git a/native/crates/app/src/workbench/localization.rs b/native/crates/app/src/workbench/localization.rs
index 8a1fbe5bf62..8ec9cca60b4 100644
--- a/native/crates/app/src/workbench/localization.rs
+++ b/native/crates/app/src/workbench/localization.rs
@@ -258,6 +258,7 @@ fn install_count_label(count: f64) -> String {
/// `hostService.restart`: the same binary, arguments and working folder start once this process has exited.
// Not gpui's `App::restart`: it relaunches with `open`, which loses the working folder of an unbundled binary.
+#[cfg(unix)]
fn relaunch(cx: &mut Context<Workbench>) {
use std::os::unix::process::CommandExt as _;
let script = r#"while kill -0 "$0" 2>/dev/null; do sleep 0.1; done; cd "$1"; shift; exec "$@""#;
@@ -278,5 +279,15 @@ fn relaunch(cx: &mut Context<Workbench>) {
}
}
+// shortcut: the new process starts before this one exits; wait for it once single instance runs on Windows (port/ledger.md M24 row app/src/launch.rs:5).
+#[cfg(windows)]
+fn relaunch(cx: &mut Context<Workbench>) {
+ let exe = std::env::current_exe().expect("the running binary");
+ match std::process::Command::new(exe).args(std::env::args_os().skip(1)).spawn() {
+ Ok(_) => cx.quit(),
+ Err(error) => eprintln!("[localization] restarting: {error}"),
+ }
+}
+
#[cfg(test)]
mod tests;
diff --git a/native/crates/app/src/workbench/process_explorer.rs b/native/crates/app/src/workbench/process_explorer.rs
index 7443df8d010..d496ce8096f 100644
--- a/native/crates/app/src/workbench/process_explorer.rs
+++ b/native/crates/app/src/workbench/process_explorer.rs
@@ -238,7 +238,19 @@ fn active_guide_nodes(rows: &[Row], active: &[RowId]) -> HashSet<RowId> {
nodes
}
+/// Node's `os.constants.signals.SIGKILL`, the same number on every platform.
+const SIGKILL: i32 = 9;
+
+/// nativeHostMainService.ts `killProcess`: `process.kill(pid, signal)`.
+#[cfg(windows)]
+fn kill(pid: u32, _signal: i32) {
+ if let Err(error) = crate::ps::kill(pid) {
+ eprintln!("[processExplorer] kill {pid}: {error}");
+ }
+}
+
/// nativeHostMainService.ts `killProcess`: `process.kill(pid, signal)`.
+#[cfg(unix)]
fn kill(pid: u32, signal: i32) {
if unsafe { libc::kill(pid as i32, signal) } != 0 {
eprintln!("[processExplorer] kill {pid}: {}", std::io::Error::last_os_error());
@@ -294,6 +306,9 @@ impl ProcessExplorer {
let total_memory = NSProcessInfo::processInfo().physicalMemory() as f64;
#[cfg(target_os = "linux")]
let total_memory = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) as f64 * libc::sysconf(libc::_SC_PAGESIZE) as f64 };
+ // ps::list_processes on Windows reads no memory yet.
+ #[cfg(target_os = "windows")]
+ let total_memory = 0.;
// `update`: `ps` runs off the main thread, the next run 1 s after the last one ended.
let refresh = cx.spawn(async move |explorer, cx| {
loop {
@@ -483,7 +498,7 @@ impl ProcessExplorer {
self.hide_menu(window, cx);
match command {
MenuCommand::Kill => kill(pid, libc::SIGTERM),
- MenuCommand::ForceKill => kill(pid, libc::SIGKILL),
+ MenuCommand::ForceKill => kill(pid, SIGKILL),
MenuCommand::Copy => {
let mut pids = self.selected_pids();
// A right-clicked row outside the selection is copied alone.
diff --git a/native/crates/app/src/workbench/quick_input_view.rs b/native/crates/app/src/workbench/quick_input_view.rs
index 27a099111ee..3d97740702c 100644
--- a/native/crates/app/src/workbench/quick_input_view.rs
+++ b/native/crates/app/src/workbench/quick_input_view.rs
@@ -1226,6 +1226,9 @@ fn system_reduces_transparency() -> bool {
// shortcut: the Linux desktop's reduced transparency is not read; read it when a Linux user needs it.
#[cfg(target_os = "linux")]
return false;
+ // shortcut: Windows' transparency effects setting is not read; port/ledger.md M24 row app/src/workbench/accessibility.rs:531.
+ #[cfg(target_os = "windows")]
+ return false;
}
#[cfg(test)]
diff --git a/native/crates/app/src/workbench/readonly.rs b/native/crates/app/src/workbench/readonly.rs
index a744a7c81a4..22ad0c50841 100644
--- a/native/crates/app/src/workbench/readonly.rs
+++ b/native/crates/app/src/workbench/readonly.rs
@@ -3,7 +3,6 @@
//! editor shows why it is read-only.
use std::collections::HashMap;
-use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use gpui::Context;
@@ -125,7 +124,7 @@ impl Workbench {
if self.resource_glob_matcher(&expression("files.readonlyInclude"))(path, None) {
return (!self.resource_glob_matcher(&expression("files.readonlyExclude"))(path, None)).then_some(Readonly::Configured);
}
- let locked = || std::fs::metadata(path).is_ok_and(|stat| stat.permissions().mode() & 0o200 == 0);
+ let locked = || std::fs::metadata(path).is_ok_and(|stat| files::disk::write_locked(&stat));
(scheme == "file" && self.setting("files.readonlyFromPermissions") == Value::Bool(true) && locked()).then_some(Readonly::Locked)
}
diff --git a/native/crates/app/src/workbench/terminal_contrib.rs b/native/crates/app/src/workbench/terminal_contrib.rs
index adc78c9ae3e..bcb9b3054ae 100644
--- a/native/crates/app/src/workbench/terminal_contrib.rs
+++ b/native/crates/app/src/workbench/terminal_contrib.rs
@@ -252,7 +252,31 @@ fn unescape_sequence(text: &str) -> String {
result
}
+/// Node's `os.constants.signals` on Windows: the names libuv defines there.
+#[cfg(windows)]
+fn signal_number(signal: &str) -> Option<i32> {
+ if let Ok(number) = signal.parse() {
+ return Some(number);
+ }
+ let name = signal.trim().to_ascii_uppercase();
+ let name = name.strip_prefix("SIG").unwrap_or(&name);
+ Some(match name {
+ "HUP" => 1,
+ "INT" => 2,
+ "ILL" => 4,
+ "FPE" => 8,
+ "KILL" => 9,
+ "SEGV" => 11,
+ "TERM" => 15,
+ "BREAK" => 21,
+ "ABRT" => 22,
+ "WINCH" => 28,
+ _ => return None,
+ })
+}
+
/// Node's `os.constants.signals` names (with or without `SIG`) or a number.
+#[cfg(unix)]
fn signal_number(signal: &str) -> Option<i32> {
if let Ok(number) = signal.parse() {
return Some(number);
diff --git a/native/crates/app/src/workbench/terminal_quick_fix.rs b/native/crates/app/src/workbench/terminal_quick_fix.rs
index 4b87052e277..3c98318912a 100644
--- a/native/crates/app/src/workbench/terminal_quick_fix.rs
+++ b/native/crates/app/src/workbench/terminal_quick_fix.rs
@@ -187,13 +187,21 @@ impl Workbench {
let Some(command_line) = self.terminal_view.quick_fixes.shown.get(&id).and_then(|shown| self.terminal_view.instance(id)?.commands.get(shown.command)).map(|command| command.command.clone()) else { return };
let port = port.to_owned();
let killed = cx.background_executor().spawn(async move {
+ #[cfg(unix)]
let listing = std::process::Command::new("lsof").args(["-nP", "-iTCP", "-sTCP:LISTEN"]).output().ok()?;
+ #[cfg(windows)]
+ let listing = std::process::Command::new("netstat").arg("-ano").output().ok()?;
let listing = String::from_utf8_lossy(&listing.stdout).into_owned();
let line = listing.lines().find(|line| line.contains(&port) && !line.trim().is_empty())?;
// ptyService.ts `capturePid`: the first number with blanks around it.
let pid: i32 = line.split_whitespace().find_map(|field| field.parse().ok())?;
// SAFETY: kill(2) with a pid and SIGTERM has no memory effects.
- unsafe { libc::kill(pid, libc::SIGTERM) };
+ #[cfg(unix)]
+ unsafe {
+ libc::kill(pid, libc::SIGTERM)
+ };
+ #[cfg(windows)]
+ let _ = crate::ps::kill(pid as u32);
Some(())
});
cx.spawn_in(window, async move |workbench, cx| {
diff --git a/native/crates/app/src/workbench/text_files.rs b/native/crates/app/src/workbench/text_files.rs
index 1fe84d19f59..03a8da7ff25 100644
--- a/native/crates/app/src/workbench/text_files.rs
+++ b/native/crates/app/src/workbench/text_files.rs
@@ -870,16 +870,16 @@ impl Workbench {
/// diskFileSystemProvider.ts `toFileSystemProviderWriteError`: no permission on a file without the owner's write
/// bit is `FILE_WRITE_LOCKED`.
fn write_error(path: &Path, error: std::io::Error, tried_unlock: bool) -> SaveError {
- use std::os::unix::fs::PermissionsExt;
if error.kind() != std::io::ErrorKind::PermissionDenied {
return SaveError::Other(error.to_string());
}
match std::fs::metadata(path) {
- Ok(metadata) if metadata.permissions().mode() & 0o200 == 0 => SaveError::WriteLocked { tried_unlock },
+ Ok(metadata) if files::disk::write_locked(&metadata) => SaveError::WriteLocked { tried_unlock },
_ => SaveError::PermissionDenied,
}
}
+#[cfg(unix)]
fn unlock(path: &Path) -> std::io::Result<()> {
use std::os::unix::fs::PermissionsExt;
let mut permissions = std::fs::metadata(path)?.permissions();
@@ -890,6 +890,18 @@ fn unlock(path: &Path) -> std::io::Result<()> {
Ok(())
}
+/// pfs.ts `unlock` on Windows: libuv's chmod clears the read-only attribute.
+#[cfg(windows)]
+fn unlock(path: &Path) -> std::io::Result<()> {
+ let mut permissions = std::fs::metadata(path)?.permissions();
+ if permissions.readonly() {
+ #[expect(clippy::permissions_set_readonly_false, reason = "only the read-only attribute, as libuv's chmod")]
+ permissions.set_readonly(false);
+ std::fs::set_permissions(path, permissions)?;
+ }
+ Ok(())
+}
+
/// nativeHostMainService.ts `writeElevated`: the bytes go to a temporary file the superuser copies over the
/// target (with `unlock`, after giving the owner write permission), behind the system's administrator prompt;
/// sudo-prompt's macOS applet is the same prompt as AppleScript's `with administrator privileges`.
diff --git a/native/crates/app/src/workbench/themes.rs b/native/crates/app/src/workbench/themes.rs
index 51578093dde..218bd6035ef 100644
--- a/native/crates/app/src/workbench/themes.rs
+++ b/native/crates/app/src/workbench/themes.rs
@@ -49,6 +49,14 @@ pub fn host_color_scheme(cx: &gpui::App) -> HostColorScheme {
HostColorScheme { dark, high_contrast: false }
}
+/// Electron on Windows: dark from the system's app theme, which GPUI reads and watches.
+// shortcut: never high contrast yet; port/ledger.md M24 row app/src/workbench/accessibility.rs:531 (SPI_GETHIGHCONTRAST).
+#[cfg(target_os = "windows")]
+pub fn host_color_scheme(cx: &gpui::App) -> HostColorScheme {
+ let dark = matches!(cx.window_appearance(), gpui::WindowAppearance::Dark | gpui::WindowAppearance::VibrantDark);
+ HostColorScheme { dark, high_contrast: false }
+}
+
/// themeConfiguration.ts `getColorThemeSettingId`: the setting that names the color theme for this host scheme.
pub fn color_theme_setting_id(settings: &Settings, host: HostColorScheme) -> &'static str {
let enabled = |key| settings.get_value(Some(key), &Default::default()) == Some(json!(true));
diff --git a/port/ledger.md b/port/ledger.md
index ed67d48ba94..98dc0232f58 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -66,15 +66,15 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,
| M23 Linux | app/src/workbench/menubar.rs:173 | open | [linux M] menu bar in the custom title bar. Linux shows now: no menu bar; gpui_linux `set_menus` keeps the menus and draws none. | |
| M23 Linux | .github/workflows/linux.yml:1 | done | [linux S] move actions/checkout, actions/setup-node and actions/upload-artifact from v4 to their Node 24 majors (pinned by SHA). | checkout v7.0.1, setup-node v7.1.0, upload-artifact v7.0.2 by SHA; the workflow not run yet |
| M23 Linux | port/tools/package-linux:1 | done | [linux M] Linux builds of the host's native modules (@vscode/spdlog, kerberos): package-linux rebuilds them with node-gyp; a dev run in the Studio container still loads the reference's macOS builds (its pnpm install ran on macOS), a Linux install of upstream builds them for Linux. | the extracted `VSRustium-1.147.0-linux-arm64.tar.gz` writes `logs/<session>/window1/exthost/exthost.log` (spdlog) and passes `port/tools/linux/smoke` |
-| M24 Windows | port/tools/windows-build:1 | open | [windows M] cross build on the Studio: `cargo gc xwin` with Homebrew llvm and lld on PATH, for `x86_64-pc-windows-msvc` and `aarch64-pc-windows-msvc`; the Unix-only std and libc calls (files/src/disk.rs:58, exthost/src/lib.rs:31, app/src/cli.rs:7, app/src/launch.rs:5, app/src/shell_env.rs:5, app/src/update/install.rs:39) behind `cfg(unix)` with a Windows counterpart or an M24 row naming what Windows shows meanwhile. | `port/tools/windows-build 'cargo gc xwin build -p app --target x86_64-pc-windows-msvc'` and the same for `aarch64-pc-windows-msvc` exit 0 |
-| M24 Windows | app/src/terminal/pty.rs:1 | open | [windows L] terminal through ConPTY, as node-pty's conpty.cc and windowsPtyAgent.ts: spawn with the command line `argsToCommandLine` builds, resize, kill (signals ignored, as node-pty on Windows), `hasChildProcesses` and the foreground process (windowsShellHelper.ts, a process snapshot), cwd as the initial cwd (terminalProcess.ts `getCwd` on Windows). alacritty_terminal 0.25 `tty::windows` holds the ConPTY calls. | `cargo gc test -p app pty` on the windows runner; `args_to_command_line` with windowsPtyAgent.test.ts's cases on the host |
+| M24 Windows | port/tools/windows-build:1 | done | [windows M] cross build on the Studio: `cargo gc xwin` with Homebrew llvm and lld on PATH, for `x86_64-pc-windows-msvc` and `aarch64-pc-windows-msvc`; the Unix-only std and libc calls (files/src/disk.rs:58, exthost/src/lib.rs:31, app/src/cli.rs:7, app/src/launch.rs:5, app/src/shell_env.rs:5, app/src/update/install.rs:39) behind `cfg(unix)` with a Windows counterpart or an M24 row naming what Windows shows meanwhile. | `port/tools/windows-build 'cargo gc xwin build -p app --target x86_64-pc-windows-msvc'` and the same for `aarch64-pc-windows-msvc` exit 0 |
+| M24 Windows | app/src/terminal/pty.rs:1 | in progress | [windows L] terminal through ConPTY (terminal/pty/conpty.rs, windows-sys), as node-pty's conpty.cc and windowsPtyAgent.ts: spawn with the command line `argsToCommandLine` builds, resize, kill (signals ignored, as node-pty on Windows), `hasChildProcesses` from a process snapshot, cwd as the initial cwd (terminalProcess.ts `getCwd` on Windows). Built, not yet run on Windows; the foreground process is the started file (windowsTerminal.ts `process`), not windowsShellHelper.ts's tracking. | `cargo gc test -p app pty` on the windows runner; `cargo gc test -p app args_to_command_line` on the host, with node-pty lib/windowsPtyAgent.js's output |
| M24 Windows | app/src/terminal/profiles.rs:133 | open | [windows M] Windows terminal profiles (terminalProfiles.ts `detectAvailableWindowsProfiles`): PowerShell (pwsh, then Windows PowerShell), Command Prompt, Git Bash, WSL distributions; `terminal.integrated.defaultProfile.windows`; shell integration for pwsh (shellIntegration.ps1). | `cargo gc test -p app terminal::profiles` on the windows runner |
| M24 Windows | app/src/file_dialog.rs:9 | open | [windows M] Win32 open and save dialogs (IFileOpenDialog, IFileSaveDialog) with title, filters, default path, folder pick and multi-select, as Chromium's select_file_dialog_win.cc gets them from Electron's file_dialog_win.cc (filter specs `*.ts;*.js`, `All Files (*.*)`). | `cargo gc test -p app file_dialog` on the host for the filter specs; the dialog not run on a desktop |
| M24 Windows | app/src/dialog.rs:5 | open | [windows M] native message box through TaskDialogIndirect, as Electron's message_box_win.cc: buttons in the order dialogs.ts `massageMessageBoxOptions` gives Windows, the checkbox as the verification text, owner window modal. | `cargo gc test -p app dialog` on the host for the button order; the dialog on the windows runner |
| M24 Windows | app/src/webview.rs:11 | open | [windows L] webviews through WebView2 (webview2-com, decision "Windows webview") as child windows of GPUI's HWND, with the host page, resource scheme and message bridge `webview.rs` shares with macOS and Linux: panels and views, editor insets, notebook outputs, extension details, release notes. The WebView2 runtime ships with Windows 10 and 11. | `FIXTURE=webview-tests` smoke on the windows runner; `cargo gc test -p app webview` there |
| M24 Windows | exthost/src/lib.rs:31 | open | [windows L] extension host connection over a named pipe (`\\.\pipe\vscode-ipc-<uuid>-sock`, ipc.net.ts `createRandomIPCHandle` on Windows) instead of a Unix socket; Bun's `net.connect` takes the pipe path. | `cargo gc test -p exthost` on the windows runner: the handshake test |
| M24 Windows | app/src/launch.rs:5 | open | [windows M] single instance and second-instance arguments over a named pipe (main.ts `mainIPCHandle` on Windows). | `cargo gc test -p app launch` on the windows runner |
-| M24 Windows | app/src/cli.rs:7 | open | [windows M] the command line on Windows: `bin\<applicationName>.cmd` from resources/win32/bin/code.cmd, stdin read and terminal width through the console API. | `cargo gc test -p app cli` on the windows runner |
+| M24 Windows | app/src/cli.rs:7 | in progress | [windows M] the command line on Windows: `bin\<applicationName>.cmd` from resources/win32/bin/code.cmd, stdin read and terminal width through the console API. | `cargo gc test -p app cli` on the windows runner |
| M24 Windows | exthost/src/main_thread_secret_state.rs:19 | open | [windows S] secrets in Credential Manager (keyring), with keytar's target name `<service>/<account>` so VS Code's stored secrets keep their keys. | `cargo gc test -p exthost secret` on the windows runner |
| M24 Windows | exthost/src/request.rs:9 | open | [windows M] extension and gallery HTTP with the system proxy (WinHTTP's IE proxy settings, Chromium's ProxyConfigServiceWin), `http.proxy` and the `<local>` bypass. | `cargo gc test -p exthost request` on the windows runner |
| M24 Windows | app/src/workbench/menubar.rs:173 | open | [windows L] menu bar in the custom title bar (menubarControl.ts `CustomMenubarControl`, `window.titleBarStyle: custom`, `window.menuBarVisibility`) and the window controls (minimize, maximize, close) titlebarPart.ts draws on Windows. The shared mechanism is M24's (decision "Menu bar and keybinding tables"); it unblocks the M23 Linux row app/src/workbench/menubar.rs:173. Windows shows now: no menu bar. | `cargo gc test -p app menubar` on the host; a ui-pair against the reference not possible (macOS reference) |
@@ -84,13 +84,14 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,
| M24 Windows | files/src/disk.rs:58 | open | [windows M] file system on NTFS: read-only through `FILE_ATTRIBUTE_READONLY`, file and directory symlinks, case-insensitive path compare, Recycle Bin (trash crate), ReadDirectoryChangesW (notify). | `cargo gc test -p files` on the windows runner |
| M24 Windows | app/src/editor_history.rs:59 | open | [windows L] drive-letter paths and file URIs (`file:///c%3A/...`, uri.ts `fsPath` on Windows, backslash separators in labels): the per-file `file_uri` helpers go through one conversion. | `cargo gc test -p app uri` on the host for the conversion; api-tests on the windows runner |
| M24 Windows | app/src/settings_import.rs:28 | open | [windows S] settings import from `%APPDATA%\Code`, `%APPDATA%\Cursor`, `%APPDATA%\VSCodium`, extensions from `%USERPROFILE%\.vscode\extensions` and the others. | `cargo gc test -p app settings_import` on the windows runner |
-| M24 Windows | app/src/workbench/shell_command.rs:70 | open | [windows S] no Shell Command on Windows (upstream has it on macOS only): the user setup puts `{app}\bin` on the user PATH (code.iss `addtopath`), the zip leaves PATH alone. | the commands absent from the palette on the windows runner; the installer row's check |
-| M24 Windows | app/src/update/install.rs:21 | open | [windows M] updates as a download link, as on Linux (decision "Windows updates"). | `cargo gc test -p app update::` on the host |
+| M24 Windows | app/src/workbench/shell_command.rs:70 | in progress | [windows S] no Shell Command on Windows (upstream has it on macOS only): the user setup puts `{app}\bin` on the user PATH (code.iss `addtopath`), the zip leaves PATH alone. | the commands absent from the palette on the windows runner; the installer row's check |
+| M24 Windows | app/src/update/install.rs:21 | in progress | [windows M] updates as a download link, as on Linux (decision "Windows updates"). | `cargo gc test -p app update::` on the host |
| M24 Windows | app/src/update/install.rs:22 | later | [windows M] in-place update through the user setup, as updateService.win32.ts: download the setup, run it with `/verysilent /update`, restart. | the runner's installed app updates from one feed version to the next |
-| M24 Windows | app/src/shell_env.rs:5 | open | [windows S] no shell environment resolution on Windows (shellEnv.ts returns the process environment on win32). | `cargo gc test -p app shell_env` on the windows runner |
+| M24 Windows | app/src/shell_env.rs:5 | in progress | [windows S] no shell environment resolution on Windows (shellEnv.ts returns the process environment on win32). | `cargo gc test -p app shell_env` on the windows runner |
| M24 Windows | app/src/system_wide_keybindings.rs:13 | open | [windows S] system-wide keybindings through `RegisterHotKey` (Chromium's GlobalAcceleratorListenerWin). | `cargo gc test -p app system_wide` on the windows runner |
| M24 Windows | app/src/power.rs:9 | open | [windows M] powerMonitor: idle time (`GetLastInputInfo`), battery (`GetSystemPowerStatus`), lock, sleep and resume, power save blockers (`SetThreadExecutionState`). | `cargo gc test -p app power::` on the windows runner |
| M24 Windows | app/src/accessibility_signals.rs:107 | open | [windows S] accessibility signal sounds (mp3) through the Windows media player API. | not run with audio on the runner |
+| M24 Windows | app/src/nls.rs:146 | open | [windows S] the OS locale from the Windows UI language (Electron's `app.getPreferredSystemLanguages`, `GetUserPreferredUILanguages`); Windows shows now: en-US. | `cargo gc test -p app nls` on the windows runner |
| M24 Windows | app/src/metered_connection.rs:57 | open | [windows S] metered connection (`INetworkCostManager`). | not run on a desktop |
| M24 Windows | app/src/workbench/accessibility.rs:531 | open | [windows S] screen reader, reduced motion and high contrast (`SystemParametersInfo` `SPI_GETSCREENREADER`, `SPI_GETCLIENTAREAANIMATION`, `SPI_GETHIGHCONTRAST`). | not run with a screen reader |
| M24 Windows | app/src/diagnostics.rs:308 | open | [windows S] machine info (CPU name, memory, OS release) and the network interfaces of the machine id. | `cargo gc test -p app diagnostics` on the windows runner |