diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml new file mode 100644 index 0000000..670f440 --- /dev/null +++ b/.github/workflows/ci-windows.yml @@ -0,0 +1,40 @@ +# Builds and tests the Windows app on every change to the code, so a release +# never finds out about a Windows break. The zip is kept as an artifact for +# trying a change before it is released. +# +# Separate from ci.yml so the Windows and Linux CI can evolve independently. +name: CI Windows + +on: + push: + branches: [main] + paths: ["src/**", "assets/**", "extensions/**", "Cargo.*", "rust-toolchain.toml", "script/bundle-windows.ps1", "script/third-party-licenses.sh", "resources/**", ".github/workflows/ci-windows.yml"] + pull_request: + paths: ["src/**", "assets/**", "extensions/**", "Cargo.*", "rust-toolchain.toml", "script/bundle-windows.ps1", "script/third-party-licenses.sh", "resources/**", ".github/workflows/ci-windows.yml"] + workflow_dispatch: + +permissions: + contents: read + +jobs: + windows: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - uses: Swatinem/rust-cache@v2 + + - name: Test + run: cargo test --locked + + - name: Install cargo-about + run: cargo install cargo-about --locked --features cli --version 0.9.3 + + - name: Build the zip + run: pwsh -File script/bundle-windows.ps1 + + - uses: actions/upload-artifact@v4 + with: + name: pi-gpui-windows-${{ runner.arch }} + path: target/release/pi-gpui-*-windows-*.zip + retention-days: 14 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7169f44..f2e456d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -129,3 +129,37 @@ jobs: env: GH_TOKEN: ${{ github.token }} run: gh release upload "$GITHUB_REF_NAME" target/release/pi-gpui-*-linux-*.tar.gz --clobber + + # Added by the Windows port: joins the release the macOS job created, as + # the Linux builds do. Windows builds are not code-signed yet. + windows: + needs: macos + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - name: Check that the tag matches Cargo.toml + shell: bash + run: | + version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) + if [ "v$version" != "$GITHUB_REF_NAME" ]; then + echo "Tag $GITHUB_REF_NAME does not match Cargo.toml version $version" >&2 + exit 1 + fi + + - uses: Swatinem/rust-cache@v2 + + - name: Test + run: cargo test --locked + + # Writes THIRD_PARTY_LICENSES.txt into the build (script/third-party-licenses.sh). + - name: Install cargo-about + run: cargo install cargo-about --locked --features cli --version 0.9.3 + + - name: Build the zip + run: pwsh -File script/bundle-windows.ps1 + + - name: Add it to the release + env: + GH_TOKEN: ${{ github.token }} + run: gh release upload "$GITHUB_REF_NAME" target/release/pi-gpui-*-windows-*.zip --clobber diff --git a/AGENTS.md b/AGENTS.md index 9256dab..6963dfe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ Types and where they end up: Scopes are optional; use the area of the app when there is a clear one: `chat`, `tabs`, `sidebar`, `files`, `diff`, `theme`, `settings`, `plugins`, -`updater`, `linux`, `site`, `examples`, `dev`. +`updater`, `linux`, `windows`, `site`, `examples`, `dev`. A change that breaks something users rely on (settings keys, plugin API, supported pi versions) gets a `!` after the type and a `BREAKING CHANGE:` line diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6824950..bb2ba21 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,7 +9,7 @@ cargo run [-- /path/to/project] cargo test && cargo clippy --all-targets ``` -You need pi 1.4 or newer and either a Mac with Xcode or Linux with the build libraries (`script/linux-deps.sh` installs them on Debian and Ubuntu). Rust is pinned in `rust-toolchain.toml`. Changes to shared code should keep both systems working: CI builds and tests the Linux app, and [docs/LINUX_VM.md](docs/LINUX_VM.md) sets up a Linux desktop VM on a Mac. +You need pi 1.4 or newer and either a Mac with Xcode, Linux with the build libraries (`script/linux-deps.sh` installs them on Debian and Ubuntu), or Windows with Visual Studio Build Tools (the C++ workload and the Windows SDK). Rust is pinned in `rust-toolchain.toml`. Changes to shared code should keep macOS, Linux and Windows working. CI builds and tests Linux and Windows; [docs/LINUX_VM.md](docs/LINUX_VM.md) sets up a Linux desktop VM on a Mac. ## Before you write code diff --git a/Cargo.lock b/Cargo.lock index b90fa95..dac9b1a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3588,6 +3588,7 @@ dependencies = [ "syntect", "two-face", "unicode-segmentation", + "windows 0.61.3", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index f3e0a47..565f04a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,13 +24,32 @@ regex = "1" # Already comes with gpui; local time for message timestamps. libc = "0.2" # Already comes with gpui; decodes plugin view frames without the async asset cache. -image = { version = "0.25", default-features = false, features = ["jpeg", "png"] } +# BMP and TIFF are what Windows and macOS screenshots put on the clipboard. +image = { version = "0.25", default-features = false, features = ["bmp", "jpeg", "png", "tiff"] } [target.'cfg(target_os = "macos")'.dependencies] objc = "0.2" # Already comes with gpui; Objective-C blocks for the folder picker's completion handler. block = "0.1" +[target.'cfg(target_os = "windows")'.dependencies] +# Already comes with gpui; the Win32 calls gpui 0.2.2 does not wrap: the trash, +# the clipboard's file list, process liveness, local time and ConPTY. +windows = { version = "0.61", features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_Storage_FileSystem", + "Win32_System_Console", + "Win32_System_DataExchange", + "Win32_System_Ole", + "Win32_System_Pipes", + "Win32_System_Threading", + "Win32_System_Time", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_Shell", + "Win32_UI_WindowsAndMessaging", +] } + [profile.dev] # GPUI is slow in unoptimized builds; optimize dependencies, keep our code debuggable. opt-level = 1 diff --git a/README.md b/README.md index bebe0b8..82af768 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,12 @@ # Pi GPUI -A native GUI for the [pi](https://github.com/earendil-works/pi) coding agent, written in Rust with [GPUI](https://www.gpui.rs), the UI framework behind Zed. No Electron, no webview. It runs the pi you already have over RPC, with the same models, extensions, skills and sessions you use in the terminal. For macOS and Linux. +A native GUI for the [pi](https://github.com/earendil-works/pi) coding agent, written in Rust with [GPUI](https://www.gpui.rs), the UI framework behind Zed. No Electron, no webview. It runs the pi you already have over RPC, with the same models, extensions, skills and sessions you use in the terminal. For macOS, Linux and Windows. The app is 16 MB, its window is up in about 0.4 s, and it uses about 75 MB of memory at idle. Electron clients for pi take 0.5 to 1.1 s and 190 to 430 MB. Measured on an M1 Pro with no projects open, counting each app's own processes ([method and script](docs/BENCHMARKS.md)). [![macOS 13+, Apple silicon](https://img.shields.io/badge/macOS-13%2B%20Apple%20silicon-111?logo=apple&logoColor=white)](#install) [![Linux x86_64 and arm64](https://img.shields.io/badge/Linux-x86__64%20%C2%B7%20arm64%20(beta)-111?logo=linux&logoColor=white)](#install) +[![Windows x86_64](https://img.shields.io/badge/Windows-x86__64%20(beta)-111?logo=windows&logoColor=white)](#install) [![MIT](https://img.shields.io/badge/license-MIT-111)](LICENSE) [Website](https://pi-gpui.dev) · [Download](https://github.com/bytesbay/pi-gpui/releases/latest) · [Plugins](docs/PLUGINS.md) · [中文](docs/README.zh-CN.md) @@ -32,7 +33,11 @@ curl -fsSL https://pi-gpui.dev/install.sh | sh The [script](site/install.sh) puts the app in `~/.local/pi-gpui.app`, links `~/.local/bin/pi-gpui` and adds a launcher entry. It needs no root. Or unpack `pi-gpui-*-linux-*.tar.gz` from [Releases](https://github.com/bytesbay/pi-gpui/releases) yourself. It runs on X11 and Wayland and needs glibc 2.35 or newer (Ubuntu 22.04, Debian 12, Fedora 36) and a Vulkan driver. See [Linux](#linux) for what differs from the Mac app. -On both systems the app updates itself: when a new version is downloaded, "Restart to update" appears in the title bar. Windows isn't supported. +**Windows** (x86_64, Windows 10 or newer, beta) + +Download `pi-gpui-*-windows-x86_64.zip` from [Releases](https://github.com/bytesbay/pi-gpui/releases) and unpack it anywhere you can write, then run `pi-gpui.app\bin\pi-gpui.exe`. The build is not code-signed yet, so SmartScreen asks once; "More info" → "Run anyway". See [Windows](#windows) for what differs from the Mac app. + +On every system the app updates itself: when a new version is downloaded, "Restart to update" appears in the title bar. Needs pi 1.4 or newer within pi 1.x. The app finds pi in `PI_EXECUTABLE`, `PATH` or your login shell (so nvm installs work). @@ -42,7 +47,7 @@ To move a session you started in the terminal into the app, add the `/gpui` comm pi install npm:pi-gpui ``` -`/gpui` closes that pi and opens the same session in Pi GPUI. Other tools can do the same with a link: `open "pi-gpui://open?workspace=/path/to/project&session=/path/to/session.jsonl"` (the session is optional). On Linux pass the link to the app: `pi-gpui "pi-gpui://open?..."`, or just a folder: `pi-gpui /path/to/project`. +`/gpui` closes that pi and opens the same session in Pi GPUI. Other tools can do the same with a link: `open "pi-gpui://open?workspace=/path/to/project&session=/path/to/session.jsonl"` (the session is optional). On Linux and Windows pass the link to the app: `pi-gpui "pi-gpui://open?..."`, or just a folder: `pi-gpui /path/to/project`. ## It runs DOOM @@ -93,11 +98,11 @@ Plugins can draw live views inside tool calls, in any language. [This one](examp In the tree: `↑↓` move, `←→` jump between branches, `↩` go there, `⌥↩` go there and summarize the branch you leave, `⌘↩` fork from your message. -On Linux `⌘` is `Ctrl` and `⌥` is `Alt`, with one exception: compact is `Ctrl+Alt+C`, because `Ctrl+Shift+C` copies the selection as it does in a terminal. +On Linux and Windows `⌘` is `Ctrl` and `⌥` is `Alt`, with one exception: compact is `Ctrl+Alt+C`, because `Ctrl+Shift+C` copies the selection as it does in a terminal. On Windows `Alt+F4` quits. ## Settings -`~/Library/Application Support/pi-gpui/settings.json` (on Linux `~/.config/pi-gpui/settings.json`) is the source of truth. The app applies it as soon as it is saved, so you or a pi agent can edit it directly; the Settings page (`⌘,`) writes the same file and keeps its comments. +`~/Library/Application Support/pi-gpui/settings.json` (on Linux `~/.config/pi-gpui/settings.json`, on Windows `%APPDATA%\pi-gpui\settings.json`) is the source of truth. The app applies it as soon as it is saved, so you or a pi agent can edit it directly; the Settings page (`⌘,`) writes the same file and keeps its comments. ```jsonc { @@ -147,6 +152,21 @@ The Linux app is the same code as the Mac app. What differs: So far it was tested on Ubuntu 24.04 on arm64 in a VM (GNOME on X11, and Wayland under Weston). Other desktops, real GPUs and the x86_64 build have not been tried yet, hence beta: please report what you see in [#5](https://github.com/bytesbay/pi-gpui/issues/5). +## Windows + +The Windows app is the same code as the Mac app. What differs: + +- The window hides the native title bar and draws its own, like the Linux app; the buttons are on the right. +- There is no menu bar. Settings, Check for Updates and Quit are under `…` in the title bar. +- Shortcuts use `Ctrl` and `Alt` (see [Keys](#keys)). +- Settings, projects and plugins live in `%APPDATA%\pi-gpui`; downloads in `%LOCALAPPDATA%\pi-gpui\cache`. +- Deleted sessions go to the Recycle Bin. +- Only one app runs per user: starting `pi-gpui` again, with a folder or a `pi-gpui://` link, hands it to the running app (a named pipe). +- The build is not code-signed yet, so SmartScreen warns the first time. +- `pi` installed with npm is found through `PATHEXT` (it is `pi.cmd`), and `pi auth login` runs in a ConPTY, the Windows pseudo-terminal. + +It has not been tried outside the CI build yet, hence beta: please report what you see in a new issue. + ## Known limits - A pi running in a terminal on the same session is not detected. @@ -157,12 +177,13 @@ So far it was tested on Ubuntu 24.04 on arm64 in a VM (GNOME on X11, and Wayland ```sh cargo run [-- /path/to/project] cargo test && cargo clippy --all-targets -script/bundle.sh # macOS: target/release/Pi GPUI.app -script/bundle-linux.sh # Linux: target/release/pi-gpui.app and the release tarball +script/bundle.sh # macOS: target/release/Pi GPUI.app +script/bundle-linux.sh # Linux: target/release/pi-gpui.app and the release tarball +script/bundle-windows.ps1 # Windows: target/release/pi-gpui.app and the release zip script/release.sh # tag the Cargo.toml version; CI builds and publishes the release ``` -Rust 1.90 (pinned). On macOS you need Xcode; shaders compile at startup, so the Metal Toolchain is not needed. On Debian and Ubuntu `script/linux-deps.sh` installs the libraries the build needs (xkbcommon, Wayland, XCB, fontconfig, freetype); other distributions have the same ones under their own names. The bundle scripts write `THIRD_PARTY_LICENSES.txt` with [cargo-about](https://github.com/EmbarkStudios/cargo-about) (`cargo install cargo-about --locked --features cli`); without it they skip that file outside CI. Set `PI_GPUI_PRETEND_VERSION=` to try the update flow against a real release. +Rust 1.90 (pinned). On macOS you need Xcode; shaders compile at startup, so the Metal Toolchain is not needed. On Debian and Ubuntu `script/linux-deps.sh` installs the libraries the build needs (xkbcommon, Wayland, XCB, fontconfig, freetype); other distributions have the same ones under their own names. On Windows the "Desktop development with C++" workload of Visual Studio Build Tools and the Windows SDK are enough; release builds compile the HLSL shaders with the SDK's `fxc.exe`. The bundle scripts write `THIRD_PARTY_LICENSES.txt` with [cargo-about](https://github.com/EmbarkStudios/cargo-about) (`cargo install cargo-about --locked --features cli`); without it they skip that file outside CI. Set `PI_GPUI_PRETEND_VERSION=` to try the update flow against a real release. Working on the Linux app from a Mac: [docs/LINUX_VM.md](docs/LINUX_VM.md) describes a local VM with a desktop that can be built in, clicked and screenshotted from the command line. diff --git a/script/bundle-windows.ps1 b/script/bundle-windows.ps1 new file mode 100644 index 0000000..3aa37fe --- /dev/null +++ b/script/bundle-windows.ps1 @@ -0,0 +1,41 @@ +# Builds the Windows release in target/release: +# pi-gpui.app\ +# bin\pi-gpui.exe +# share\pi-gpui\ plugins and licenses +# pi-gpui--windows-.zip +# The updater replaces the whole pi-gpui.app folder, as on Linux. +$ErrorActionPreference = 'Stop' +Set-Location (Split-Path $PSScriptRoot -Parent) + +cargo build --release --locked +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + +$version = [regex]::Match( + (Get-Content Cargo.toml -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value +$hostLine = (& rustc -vV | Select-String '^host:').ToString() +$arch = ($hostLine -replace '^host: ', '') -replace '-.*$', '' +$target = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { 'target' } +$release = Join-Path $target 'release' +$app = Join-Path $release 'pi-gpui.app' + +if (Test-Path $app) { Remove-Item $app -Recurse -Force } +New-Item -ItemType Directory -Force -Path ` + (Join-Path $app 'bin'), (Join-Path $app 'share\pi-gpui') | Out-Null +Copy-Item (Join-Path $release 'pi-gpui.exe') (Join-Path $app 'bin\pi-gpui.exe') +if (Test-Path plugins) { + Copy-Item plugins (Join-Path $app 'share\pi-gpui\plugins') -Recurse +} +Copy-Item LICENSE (Join-Path $app 'share\pi-gpui\LICENSE') +# The bundled JetBrains Mono font is distributed under this license. +Copy-Item assets\fonts\OFL.txt (Join-Path $app 'share\pi-gpui\JetBrainsMono-OFL.txt') + +# Writes the Rust crates' licenses and appends the syntax definitions' ones. +& bash script/third-party-licenses.sh ` + (Join-Path $app 'bin\pi-gpui.exe') ` + (Join-Path $app 'share\pi-gpui\THIRD_PARTY_LICENSES.txt') +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + +$asset = Join-Path $release "pi-gpui-$version-windows-$arch.zip" +if (Test-Path $asset) { Remove-Item $asset -Force } +Compress-Archive -Path $app -DestinationPath $asset +Write-Output $asset diff --git a/src/attachments.rs b/src/attachments.rs index ba6697b..8cd8f7e 100644 --- a/src/attachments.rs +++ b/src/attachments.rs @@ -3,9 +3,10 @@ //! //! - A pasted image is written to `$TMPDIR/pi-clipboard-.`, exactly //! where pi's terminal UI puts it. -//! - A pasted or dropped file gets a temporary symlink, +//! - A pasted or dropped file gets a temporary link, //! `$TMPDIR/pi-gpui-attachments//`, so the path in the message is -//! short and stable while the original stays where it is. +//! short and stable while the original stays where it is. Windows cannot +//! make symlinks without extra privileges, so there the file is copied. use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -42,7 +43,7 @@ pub fn is_image(path: &Path) -> bool { }) } -/// A temporary symlink to `original`, keeping its file name. +/// A temporary link to `original`, keeping its file name. pub fn link_file(original: &Path) -> std::io::Result { let name = original .file_name() @@ -52,10 +53,37 @@ pub fn link_file(original: &Path) -> std::io::Result { .join(unique_id()); std::fs::create_dir_all(&directory)?; let link = directory.join(name); + #[cfg(unix)] std::os::unix::fs::symlink(original, &link)?; + #[cfg(target_os = "windows")] + { + let linked = if original.is_dir() { + std::os::windows::fs::symlink_dir(original, &link) + } else { + std::os::windows::fs::symlink_file(original, &link) + }; + if linked.is_err() { + // Developer mode is off: copy instead, so the message still works. + copy_path(original, &link)?; + } + } Ok(link) } +#[cfg(target_os = "windows")] +fn copy_path(original: &Path, destination: &Path) -> std::io::Result<()> { + if original.is_dir() { + std::fs::create_dir_all(destination)?; + for entry in std::fs::read_dir(original)? { + let entry = entry?; + copy_path(&entry.path(), &destination.join(entry.file_name()))?; + } + Ok(()) + } else { + std::fs::copy(original, destination).map(drop) + } +} + /// Writes a clipboard image where pi's terminal UI writes it. TIFF and BMP /// (what macOS screenshots often put on the clipboard) become PNG, which /// every model and pi's `read` tool understand. @@ -71,22 +99,17 @@ pub fn save_clipboard_image(image: &gpui::Image) -> std::io::Result { let path = std::env::temp_dir().join(format!("pi-clipboard-{}.{extension}", unique_id())); match image.format { ImageFormat::Tiff | ImageFormat::Bmp => { - let source = path.with_extension(if image.format == ImageFormat::Tiff { - "tiff" + let format = if image.format == ImageFormat::Tiff { + image::ImageFormat::Tiff } else { - "bmp" - }); - std::fs::write(&source, &image.bytes)?; - let converted = std::process::Command::new("sips") - .args(["-s", "format", "png"]) - .arg(&source) - .arg("--out") - .arg(&path) - .output()?; - let _ = std::fs::remove_file(&source); - if !converted.status.success() { - return Err(std::io::Error::other("could not convert the image to PNG")); - } + image::ImageFormat::Bmp + }; + let decoded = image::load_from_memory_with_format(&image.bytes, format) + .map_err(|error| std::io::Error::other(error.to_string()))?; + let file = std::fs::File::create(&path)?; + decoded + .write_to(&mut std::io::BufWriter::new(file), image::ImageFormat::Png) + .map_err(|error| std::io::Error::other(error.to_string()))?; } _ => std::fs::write(&path, &image.bytes)?, } @@ -94,21 +117,13 @@ pub fn save_clipboard_image(image: &gpui::Image) -> std::io::Result { } /// Absolute paths of existing image files mentioned in `text`, in order. -/// Paths may contain spaces, so every `/` that starts a word is tried -/// against every image extension that follows it. +/// Paths may contain spaces, so every path start (`/`, and `C:\` or `C:/` on +/// Windows) that begins a word is tried against every image extension after it. pub fn image_paths_in(text: &str) -> Vec { let mut found = Vec::new(); let mut search_from = 0; - while let Some(relative) = text[search_from..].find('/') { - let start = search_from + relative; + while let Some(start) = next_path_start(text, search_from) { search_from = start + 1; - let starts_word = text[..start] - .chars() - .next_back() - .is_none_or(|character| character.is_whitespace() || "\"'(`".contains(character)); - if !starts_word { - continue; - } let rest = &text[start..]; let mut best = None; for (index, _) in rest.match_indices('.') { @@ -142,6 +157,31 @@ pub fn image_paths_in(text: &str) -> Vec { found } +/// The next index where an absolute path starts a word: `/…` anywhere, and +/// `C:\…` or `C:/…` on Windows. +fn next_path_start(text: &str, from: usize) -> Option { + let bytes = text.as_bytes(); + for index in from..bytes.len() { + let starts_word = text[..index] + .chars() + .next_back() + .is_none_or(|character| character.is_whitespace() || "\"'(`".contains(character)); + if !starts_word { + continue; + } + if bytes[index] == b'/' { + return Some(index); + } + if bytes[index].is_ascii_alphabetic() + && bytes.get(index + 1) == Some(&b':') + && matches!(bytes.get(index + 2), Some(b'\\' | b'/')) + { + return Some(index); + } + } + None +} + fn unique_id() -> String { static COUNTER: AtomicU64 = AtomicU64::new(0); let nanos = SystemTime::now() diff --git a/src/chat.rs b/src/chat.rs index 150e10f..c2a0389 100644 --- a/src/chat.rs +++ b/src/chat.rs @@ -3581,29 +3581,19 @@ fn format_time(at: i64, full: bool) -> String { const MONTHS: [&str; 12] = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; - let local = |ms: i64| { - let seconds = (ms / 1000) as libc::time_t; - // SAFETY: localtime_r only writes into the struct we pass. - unsafe { - let mut tm: libc::tm = std::mem::zeroed(); - libc::localtime_r(&seconds, &mut tm); - tm - } - }; - let tm = local(at); - let today = local(now_ms()); - let time = format!("{:02}:{:02}", tm.tm_hour, tm.tm_min); - let month = MONTHS[tm.tm_mon.clamp(0, 11) as usize]; - let year = 1900 + tm.tm_year; + let at = crate::platform::local_time(at); + let today = crate::platform::local_time(now_ms()); + let time = format!("{:02}:{:02}", at.hour, at.minute); + let month = MONTHS[(at.month as usize).clamp(1, 12) - 1]; if full { - return format!("{} {month} {year}, {time}:{:02}", tm.tm_mday, tm.tm_sec); + return format!("{} {month} {}, {time}:{:02}", at.day, at.year, at.second); } - if (tm.tm_year, tm.tm_yday) == (today.tm_year, today.tm_yday) { + if (at.year, at.month, at.day) == (today.year, today.month, today.day) { time - } else if tm.tm_year == today.tm_year { - format!("{} {month} {time}", tm.tm_mday) + } else if at.year == today.year { + format!("{} {month} {time}", at.day) } else { - format!("{} {month} {year} {time}", tm.tm_mday) + format!("{} {month} {} {time}", at.day, at.year) } } diff --git a/src/diff.rs b/src/diff.rs index 428e13b..d16a878 100644 --- a/src/diff.rs +++ b/src/diff.rs @@ -531,11 +531,14 @@ impl GitError { } fn git(directory: &Path, arguments: &[&str]) -> Result { - let output = Command::new("git") + let mut command = Command::new("git"); + command .arg("-C") .arg(directory) .args(arguments) - .stdin(Stdio::null()) + .stdin(Stdio::null()); + crate::platform::hide_console(&mut command); + let output = command .output() .map_err(|error| GitError::Spawn(format!("could not run git: {error}")))?; if !output.status.success() { diff --git a/src/file_tree.rs b/src/file_tree.rs index 286df88..ff05407 100644 --- a/src/file_tree.rs +++ b/src/file_tree.rs @@ -690,14 +690,15 @@ fn read_directory(directory: &Path) -> Result, String> { /// Empty outside a git work tree or when git is missing. fn git_state(workspace: &Path) -> GitState { let run = |arguments: &[&str]| -> Option> { - let output = Command::new("git") + let mut command = Command::new("git"); + command .arg("-C") .arg(workspace) .args(arguments) .stdin(Stdio::null()) - .stderr(Stdio::null()) - .output() - .ok()?; + .stderr(Stdio::null()); + crate::platform::hide_console(&mut command); + let output = command.output().ok()?; output.status.success().then_some(output.stdout) }; let Some(root) = run(&["rev-parse", "--show-toplevel"]) else { diff --git a/src/hub.rs b/src/hub.rs index 3e90cd1..71c1c64 100644 --- a/src/hub.rs +++ b/src/hub.rs @@ -4591,7 +4591,11 @@ impl HubView { }) .border_b_1() .border_color(colors.border_variant) - .window_control_area(WindowControlArea::Drag) + // Windows gets the drag from the mouse handlers below instead; a + // drag hit test there would swallow the buttons in the title bar. + .when(!cfg!(target_os = "windows"), |this| { + this.window_control_area(WindowControlArea::Drag) + }) .on_mouse_down( MouseButton::Left, cx.listener(|this, event: &MouseDownEvent, _, _| { @@ -5003,12 +5007,14 @@ impl Render for HubView { } /// Minimize, maximize and close, when the app draws its own frame (Linux -/// without server-side decorations). The window manager draws them otherwise. +/// without server-side decorations, and Windows, where gpui always hides the +/// native title bar). The window manager draws them otherwise. fn render_window_controls(window: &Window) -> Option { - if !matches!( + let client_side = matches!( window.window_decorations(), gpui::Decorations::Client { .. } - ) { + ) || cfg!(target_os = "windows"); + if !client_side { return None; } let controls = window.window_controls(); diff --git a/src/jsonl.rs b/src/jsonl.rs index d305f5f..a680898 100644 --- a/src/jsonl.rs +++ b/src/jsonl.rs @@ -109,7 +109,7 @@ impl Drop for JsonlProcess { } } if let Ok(mut child) = child.lock() - && let Err(error) = child.kill() + && let Err(error) = crate::platform::kill_process_tree(&mut child) { eprintln!("pi-gpui: failed to stop a child process: {error}"); } diff --git a/src/main.rs b/src/main.rs index 9c997c3..a18cfd5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,6 +16,7 @@ mod pi_auth; mod pi_updates; mod platform; mod plugins; +mod pty; mod selectable; mod session_links; mod session_search; @@ -117,6 +118,10 @@ fn main() { file_tree::bind_keys(cx); hub::bind_keys(cx); cx.bind_keys([KeyBinding::new(&crate::keys::binding("cmd-q"), Quit, None)]); + // Windows users close a window with Alt+F4; the custom title bar does + // not leave that to the system. + #[cfg(target_os = "windows")] + cx.bind_keys([KeyBinding::new("alt-f4", Quit, None)]); #[cfg(target_os = "macos")] cx.bind_keys([ KeyBinding::new("cmd-h", Hide, None), diff --git a/src/open_url.rs b/src/open_url.rs index 1d5a7c8..736ea48 100644 --- a/src/open_url.rs +++ b/src/open_url.rs @@ -37,11 +37,9 @@ pub fn parse(url: &str) -> Option { /// Linux only: a second launch hands its folder to the running app. #[cfg_attr(target_os = "macos", allow(dead_code))] pub fn workspace_link(workspace: &std::path::Path) -> String { - use std::os::unix::ffi::OsStrExt as _; - let mut link = String::from("pi-gpui://open?workspace="); - for &byte in workspace.as_os_str().as_bytes() { - if byte.is_ascii_alphanumeric() || b"/-._~".contains(&byte) { + for &byte in path_bytes(workspace).iter() { + if byte.is_ascii_alphanumeric() || b"/-._~:".contains(&byte) { link.push(byte as char); } else { link.push_str(&format!("%{byte:02X}")); @@ -50,6 +48,19 @@ pub fn workspace_link(workspace: &std::path::Path) -> String { link } +/// The path as bytes: its exact bytes on Unix, its UTF-8 on Windows (where +/// paths are UTF-16 anyway). +#[cfg(unix)] +fn path_bytes(path: &std::path::Path) -> std::borrow::Cow<'_, [u8]> { + use std::os::unix::ffi::OsStrExt as _; + std::borrow::Cow::Borrowed(path.as_os_str().as_bytes()) +} + +#[cfg(target_os = "windows")] +fn path_bytes(path: &std::path::Path) -> std::borrow::Cow<'_, [u8]> { + std::borrow::Cow::Owned(path.to_string_lossy().into_owned().into_bytes()) +} + fn percent_decode(value: &str) -> String { let bytes = value.as_bytes(); let mut decoded = Vec::with_capacity(bytes.len()); diff --git a/src/pi.rs b/src/pi.rs index 0e501e5..635c980 100644 --- a/src/pi.rs +++ b/src/pi.rs @@ -169,12 +169,38 @@ impl fmt::Display for CheckError { } } +/// A `Command` that runs pi the way a terminal would. +/// +/// On Windows pi is usually the npm shim `pi.cmd`, which `CreateProcess` +/// cannot start directly, so it goes through `cmd /c`. +pub fn command(executable: &Path) -> Command { + #[cfg(target_os = "windows")] + let mut command = if executable + .extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| { + extension.eq_ignore_ascii_case("cmd") || extension.eq_ignore_ascii_case("bat") + }) { + let mut command = + Command::new(std::env::var_os("ComSpec").unwrap_or_else(|| OsString::from("cmd.exe"))); + command.args(["/d", "/c"]).arg(executable); + command + } else { + Command::new(executable) + }; + #[cfg(not(target_os = "windows"))] + let mut command = Command::new(executable); + crate::platform::hide_console(&mut command); + command +} + /// Finds pi, reads its version and checks that the app supports it. pub fn check_installation() -> Result { let executable = discover().ok_or(CheckError::NotFound)?; remember_node_directory(&executable); + let mut version_command = command(&executable); let output = run_with_timeout( - Command::new(&executable) + version_command .arg("--version") .env("PATH", path_with_executable_dir(&executable)), COMMAND_TIMEOUT, @@ -216,12 +242,54 @@ pub fn find_executable(name: &str) -> Option { find_on_path(name).or_else(|| find_in_login_shell(name)) } -fn find_on_path(name: &str) -> Option { - std::env::split_paths(&std::env::var_os("PATH")?) - .map(|directory| directory.join(name)) - .find(|candidate| candidate.is_file()) +pub fn find_on_path(name: &str) -> Option { + let path = std::env::var_os("PATH")?; + let extensions = executable_extensions(name); + std::env::split_paths(&path).find_map(|directory| { + extensions + .iter() + .map(|extension| directory.join(format!("{name}{extension}"))) + .find(|candidate| candidate.is_file()) + }) } +/// Windows runs programs through one of the extensions in `PATHEXT` (`pi` is +/// really `pi.cmd`); other systems have no extension to add. +#[cfg(target_os = "windows")] +fn executable_extensions(name: &str) -> Vec { + if Path::new(name).extension().is_some() { + return vec![String::new()]; + } + let mut extensions: Vec = Vec::new(); + if let Ok(pathext) = std::env::var("PATHEXT") { + extensions.extend( + pathext + .split(';') + .filter(|extension| !extension.is_empty()) + .map(str::to_string), + ); + } + if extensions.is_empty() { + extensions.extend([".COM", ".EXE", ".BAT", ".CMD"].map(str::to_string)); + } + // npm also writes an extensionless `pi` shell script next to `pi.cmd`; + // Windows cannot start that, so it is only the last resort. + extensions.push(String::new()); + extensions +} + +#[cfg(not(target_os = "windows"))] +fn executable_extensions(_name: &str) -> Vec { + vec![String::new()] +} + +#[cfg(target_os = "windows")] +fn find_in_login_shell(_name: &str) -> Option { + // There is no login shell; a windowed app inherits the user's PATH. + None +} + +#[cfg(not(target_os = "windows"))] fn find_in_login_shell(name: &str) -> Option { // `name` comes from our code or a plugin manifest: only plain names are looked up. if !name @@ -253,13 +321,23 @@ fn find_in_login_shell(name: &str) -> Option { .filter(|path| path.is_file()) } +#[cfg(target_os = "windows")] +fn node_executable_name() -> &'static str { + "node.exe" +} + +#[cfg(not(target_os = "windows"))] +fn node_executable_name() -> &'static str { + "node" +} + /// Finds `node` for a pi that has none next to it and keeps its directory for /// `path_with_executable_dir`. Every check looks again, so "Check again" picks /// up a node installed or switched since. Blocking. fn remember_node_directory(executable: &Path) { let beside_pi = executable .parent() - .is_some_and(|directory| directory.join("node").is_file()); + .is_some_and(|directory| directory.join(node_executable_name()).is_file()); let node_directory = if beside_pi { None } else { @@ -419,7 +497,7 @@ pub fn spawn_pi( session: Option<&Path>, extensions: &[PathBuf], ) -> std::io::Result<(JsonlProcess, mpsc::Receiver)> { - let mut command = Command::new(&installation.executable); + let mut command = command(&installation.executable); command.args(["--mode", "rpc"]); if let Some(bridge) = bridge_extension() { command.arg("--extension").arg(bridge); @@ -551,17 +629,28 @@ mod tests { } } + /// A PATH the way this system writes it, so the tests run everywhere. + fn joined(parts: &[&str]) -> OsString { + std::env::join_paths(parts.iter().map(Path::new)).unwrap() + } + #[test] fn node_directory_goes_before_the_node_it_must_beat() { // Finder's PATH has Homebrew's node; the shell picked mise's. let path = child_path( Path::new("/pi/bin/pi"), - Some(OsStr::new("/pyenv/shims:/opt/homebrew/bin:/usr/bin")), + Some(&joined(&["/pyenv/shims", "/opt/homebrew/bin", "/usr/bin"])), Some(&node("/mise/node/bin", Some("/opt/homebrew/bin"))), ); assert_eq!( path, - OsString::from("/pi/bin:/pyenv/shims:/mise/node/bin:/opt/homebrew/bin:/usr/bin") + joined(&[ + "/pi/bin", + "/pyenv/shims", + "/mise/node/bin", + "/opt/homebrew/bin", + "/usr/bin", + ]) ); } @@ -569,12 +658,16 @@ mod tests { fn node_directory_behind_another_node_moves_before_it() { let path = child_path( Path::new("/pi/bin/pi"), - Some(OsStr::new("/opt/homebrew/bin:/usr/local/bin:/usr/bin")), + Some(&joined(&[ + "/opt/homebrew/bin", + "/usr/local/bin", + "/usr/bin", + ])), Some(&node("/usr/local/bin", Some("/opt/homebrew/bin"))), ); assert_eq!( path, - OsString::from("/pi/bin:/usr/local/bin:/opt/homebrew/bin:/usr/bin") + joined(&["/pi/bin", "/usr/local/bin", "/opt/homebrew/bin", "/usr/bin",]) ); } @@ -582,25 +675,28 @@ mod tests { fn node_directory_fills_a_gap_at_the_end() { let path = child_path( Path::new("/pi/bin/pi"), - Some(OsStr::new("/usr/bin:/bin")), + Some(&joined(&["/usr/bin", "/bin"])), Some(&node("/mise/node/bin", None)), ); - assert_eq!(path, OsString::from("/pi/bin:/usr/bin:/bin:/mise/node/bin")); + assert_eq!( + path, + joined(&["/pi/bin", "/usr/bin", "/bin", "/mise/node/bin"]) + ); } #[test] fn node_directory_that_already_wins_keeps_its_place() { let path = child_path( Path::new("/pi/bin/pi"), - Some(OsStr::new("/pyenv/shims:/usr/bin")), + Some(&joined(&["/pyenv/shims", "/usr/bin"])), Some(&node("/usr/bin", None)), ); - assert_eq!(path, OsString::from("/pi/bin:/pyenv/shims:/usr/bin")); + assert_eq!(path, joined(&["/pi/bin", "/pyenv/shims", "/usr/bin"])); } #[test] fn path_without_a_remembered_node_is_unchanged() { - let path = child_path(Path::new("/pi/bin/pi"), Some(OsStr::new("/usr/bin")), None); - assert_eq!(path, OsString::from("/pi/bin:/usr/bin")); + let path = child_path(Path::new("/pi/bin/pi"), Some(&joined(&["/usr/bin"])), None); + assert_eq!(path, joined(&["/pi/bin", "/usr/bin"])); } } diff --git a/src/pi_auth.rs b/src/pi_auth.rs index 4765c3e..e224de7 100644 --- a/src/pi_auth.rs +++ b/src/pi_auth.rs @@ -5,11 +5,10 @@ //! itself (it opens the browser and saves the credential in its auth.json); //! the app never sees a token, only an API key the user types for pi. +use std::ffi::OsString; use std::fs::File; use std::io::{Read, Write}; -use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; -use std::os::unix::process::CommandExt; -use std::process::{Child, Command, Stdio}; +use std::process::{Command, Stdio}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -38,7 +37,7 @@ pub struct ProviderStatus { } fn command(installation: &Installation) -> Command { - let mut command = Command::new(&installation.executable); + let mut command = pi::command(&installation.executable); command.env( "PATH", pi::path_with_executable_dir(&installation.executable), @@ -164,7 +163,9 @@ pub enum LoginEvent { /// A running `pi auth login`. pub struct LoginProcess { input: File, - child: Arc>, + child: Arc>, + /// The pseudo-terminal; on Windows its console must stay open. + _pty: crate::pty::KeepAlive, } impl LoginProcess { @@ -175,43 +176,30 @@ impl LoginProcess { provider: &str, api_key: bool, ) -> std::io::Result<(Self, mpsc::UnboundedReceiver)> { - let (master, slave) = open_pty()?; - let mut command = command(installation); - command.args(["auth", "login", provider]); + let mut args: Vec = vec!["auth".into(), "login".into(), provider.into()]; if api_key { - command.arg("--api-key"); + args.push("--api-key".into()); } - command - .env("TERM", "xterm-256color") - .env("NO_COLOR", "1") - .stdin(Stdio::from(slave.try_clone()?)) - .stdout(Stdio::from(slave.try_clone()?)) - .stderr(Stdio::from(slave)); - // SAFETY: only async-signal-safe calls between fork and exec. - unsafe { - command.pre_exec(|| { - if libc::setsid() < 0 { - return Err(std::io::Error::last_os_error()); - } - if libc::ioctl(0, libc::TIOCSCTTY as _, 0) < 0 { - return Err(std::io::Error::last_os_error()); - } - Ok(()) - }); - } - let child = Arc::new(Mutex::new(command.spawn()?)); - // The parent's copies of the slave are closed now (dropped with - // `command`), so reading the master ends when pi exits. - drop(command); - let master = File::from(master); - let input = master.try_clone()?; + let path = pi::path_with_executable_dir(&installation.executable); + let env = [ + ("PATH", path), + ("TERM", OsString::from("xterm-256color")), + ("NO_COLOR", OsString::from("1")), + ]; + let crate::pty::Pty { + input, + reader, + child, + keep_alive, + } = crate::pty::spawn(&installation.executable, &args, &env)?; + let child = Arc::new(Mutex::new(child)); let (sender, receiver) = mpsc::unbounded(); let waiter = child.clone(); std::thread::spawn(move || { - let mut master = master; + let mut reader = reader; let mut buffer = [0u8; 4096]; loop { - match master.read(&mut buffer) { + match reader.read(&mut buffer) { Ok(0) | Err(_) => break, Ok(read) => { if sender @@ -225,15 +213,21 @@ impl LoginProcess { } let code = loop { match waiter.lock().unwrap().try_wait() { - Ok(Some(status)) => break status.code(), - Ok(None) => {} - Err(_) => break None, + crate::pty::Status::Exited(code) => break code, + crate::pty::Status::Running => {} } std::thread::sleep(Duration::from_millis(50)); }; sender.unbounded_send(LoginEvent::Exited(code)).ok(); }); - Ok((Self { input, child }, receiver)) + Ok(( + Self { + input, + child, + _pty: keep_alive, + }, + receiver, + )) } /// Answers pi's question: the text and Enter. @@ -254,8 +248,8 @@ impl LoginProcess { std::thread::spawn(move || { std::thread::sleep(Duration::from_secs(2)); let mut child = child.lock().unwrap(); - if matches!(child.try_wait(), Ok(None)) { - child.kill().ok(); + if matches!(child.try_wait(), crate::pty::Status::Running) { + child.kill(); } }); } @@ -264,43 +258,12 @@ impl LoginProcess { impl Drop for LoginProcess { fn drop(&mut self) { let mut child = self.child.lock().unwrap(); - if matches!(child.try_wait(), Ok(None)) { - child.kill().ok(); + if matches!(child.try_wait(), crate::pty::Status::Running) { + child.kill(); } } } -/// A pseudo-terminal wide enough that pi's lines do not wrap. -fn open_pty() -> std::io::Result<(OwnedFd, OwnedFd)> { - let mut master = -1; - let mut slave = -1; - let size = libc::winsize { - ws_row: 40, - ws_col: 200, - ws_xpixel: 0, - ws_ypixel: 0, - }; - // SAFETY: openpty writes two descriptors we then own. - let result = unsafe { - libc::openpty( - &mut master, - &mut slave, - std::ptr::null_mut(), - std::ptr::null_mut(), - &size as *const libc::winsize as *mut libc::winsize, - ) - }; - if result != 0 { - return Err(std::io::Error::last_os_error()); - } - // SAFETY: both descriptors are open and owned by nobody else. - let (master, slave) = unsafe { (OwnedFd::from_raw_fd(master), OwnedFd::from_raw_fd(slave)) }; - // The master must not leak into pi. - // SAFETY: setting FD_CLOEXEC on a descriptor we own. - unsafe { libc::fcntl(master.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) }; - Ok((master, slave)) -} - /// What pi printed, as lines: escape sequences removed, a carriage return /// or "move to column 1" starts the line over, as in a terminal. #[derive(Default)] diff --git a/src/pi_updates.rs b/src/pi_updates.rs index 98ef1a4..a2c6891 100644 --- a/src/pi_updates.rs +++ b/src/pi_updates.rs @@ -75,7 +75,7 @@ pub fn check(installation: &Installation) -> Updates { /// Runs `pi update ` and returns its output. Blocking. pub fn run(installation: &Installation, args: &[&str]) -> Result { - let output = Command::new(&installation.executable) + let output = pi::command(&installation.executable) .arg("update") .args(args) .env( @@ -104,7 +104,7 @@ pub fn run(installation: &Installation, args: &[&str]) -> Result /// `(source, install path)` pairs from `pi list`. fn installed_packages(installation: &Installation) -> Vec<(String, PathBuf)> { - let Ok(output) = Command::new(&installation.executable) + let Ok(output) = pi::command(&installation.executable) .arg("list") .env( "PATH", @@ -157,11 +157,12 @@ fn package_version(path: &Path) -> Option { } fn latest_version(name: &str) -> Option { - let output = Command::new("curl") + let mut command = Command::new("curl"); + command .args(["-fsSL", "--max-time", "15"]) - .arg(format!("https://registry.npmjs.org/{name}/latest")) - .output() - .ok()?; + .arg(format!("https://registry.npmjs.org/{name}/latest")); + crate::platform::hide_console(&mut command); + let output = command.output().ok()?; if !output.status.success() { return None; } diff --git a/src/platform.rs b/src/platform.rs index 01c9712..9c8df5b 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -1,5 +1,5 @@ //! Platform pieces gpui 0.2.2 does not provide: AppKit calls on macOS, the -//! freedesktop equivalents on Linux. +//! freedesktop equivalents on Linux, and Win32 calls on Windows. // `objc` 0.2 macros probe a `cargo-clippy` feature that modern rustc flags. #![allow(unexpected_cfgs)] @@ -44,11 +44,41 @@ pub fn start_window_drag(window: &Window) { } } -#[cfg(not(target_os = "macos"))] +/// Linux: ask the compositor to move the window. +#[cfg(not(any(target_os = "macos", target_os = "windows")))] pub fn start_window_drag(window: &Window) { window.start_window_move(); } +/// Windows: the same as clicking the native title bar. gpui 0.2.2 has no +/// `start_window_move` there, and its hit test would swallow the buttons, so +/// the app starts the move itself. +#[cfg(target_os = "windows")] +pub fn start_window_drag(window: &Window) { + use raw_window_handle::{HasWindowHandle, RawWindowHandle}; + use windows::Win32::Foundation::{HWND, LPARAM, WPARAM}; + use windows::Win32::UI::Input::KeyboardAndMouse::ReleaseCapture; + use windows::Win32::UI::WindowsAndMessaging::{HTCAPTION, SendMessageW, WM_NCLBUTTONDOWN}; + + let Ok(handle) = HasWindowHandle::window_handle(window) else { + return; + }; + let RawWindowHandle::Win32(win32) = handle.as_raw() else { + return; + }; + // SAFETY: gpui's window owns this HWND and we are in one of its event + // handlers on the UI thread; the messages are the standard title-bar drag. + unsafe { + let _ = ReleaseCapture(); + SendMessageW( + HWND(win32.hwnd.get() as *mut std::ffi::c_void), + WM_NCLBUTTONDOWN, + Some(WPARAM(HTCAPTION as usize)), + Some(LPARAM(0)), + ); + } +} + /// Tells macOS whether the app looks dark or light, so system-drawn parts /// (traffic lights, menus, scroll bars, permission sheets) and other apps /// asking for our appearance match the theme instead of the system setting. @@ -121,10 +151,40 @@ pub fn move_to_trash(path: &std::path::Path) -> Result<(), String> { } } +/// Windows: the Recycle Bin, through the .NET API that knows about it. +#[cfg(target_os = "windows")] +pub fn move_to_trash(path: &std::path::Path) -> Result<(), String> { + use std::os::windows::process::CommandExt as _; + use std::process::Command; + + // delete_file wants single quotes; PowerShell escapes them by doubling. + let escaped = path.display().to_string().replace('\'', "''"); + let script = format!( + "Add-Type -AssemblyName Microsoft.VisualBasic; \ + [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile('{escaped}', \ + 'OnlyErrorDialogs', 'SendToRecycleBin')" + ); + let output = Command::new("powershell") + .args(["-NoProfile", "-NonInteractive", "-Command", &script]) + .creation_flags(CREATE_NO_WINDOW) + .output() + .map_err(|error| error.to_string())?; + if output.status.success() { + Ok(()) + } else { + let message = String::from_utf8_lossy(&output.stderr).trim().to_string(); + Err(if message.is_empty() { + "the file could not be moved to the Recycle Bin".to_string() + } else { + message + }) + } +} + /// `gio trash` (GLib, on GNOME and most other desktops), then `kioclient` /// (KDE), then `trash-put` (trash-cli). Never deletes for good: without any of /// them the file stays where it is. -#[cfg(not(target_os = "macos"))] +#[cfg(all(unix, not(target_os = "macos")))] pub fn move_to_trash(path: &std::path::Path) -> Result<(), String> { use std::process::Command; @@ -155,12 +215,19 @@ pub fn move_to_trash(path: &std::path::Path) -> Result<(), String> { Err("no trash tool found (install gio, kioclient or trash-cli)".to_string()) } -/// Shows the file in Finder, or in the file manager on Linux. +/// Shows the file in Finder, Explorer or the Linux file manager. pub fn reveal_in_file_manager(path: &std::path::Path) { use std::process::Command; let result = if cfg!(target_os = "macos") { Command::new("open").arg("-R").arg(path).spawn().map(drop) + } else if cfg!(target_os = "windows") { + // `/select,` opens the folder with the file selected; Explorer + // treats a folder as "open it". + Command::new("explorer") + .arg(format!("/select,{}", path.display())) + .spawn() + .map(drop) } else { // The freedesktop FileManager1 interface selects the file (Nautilus, // Dolphin, Nemo, Thunar…); otherwise just open its folder. @@ -205,11 +272,22 @@ pub fn open_in_editor(path: &std::path::Path) { command.arg("-t"); } command.arg(path).spawn().map(drop) + } else if cfg!(target_os = "windows") { + match crate::pi::find_on_path("zed") { + Some(zed) => Command::new(zed).arg(path).spawn().map(drop), + // `start` (a cmd built-in) opens the file with its associated app. + None => { + let mut command = Command::new("cmd"); + command.args(["/C", "start", ""]).arg(path); + hide_console(&mut command); + command.spawn().map(drop) + } + } } else { // Zed's CLI is `zed`, or `zeditor` in some distributions' packages. match ["zed", "zeditor"] .into_iter() - .find(|program| on_path(program)) + .find(|program| crate::pi::find_on_path(program).is_some()) { Some(zed) => Command::new(zed).arg(path).spawn().map(drop), None => Command::new("xdg-open").arg(path).spawn().map(drop), @@ -220,25 +298,43 @@ pub fn open_in_editor(path: &std::path::Path) { } } -fn on_path(program: &str) -> bool { - std::env::var_os("PATH").is_some_and(|paths| { - std::env::split_paths(&paths).any(|directory| directory.join(program).is_file()) - }) -} - /// `file://` URI with the bytes that need it percent-encoded. +#[cfg(not(target_os = "windows"))] fn file_uri(path: &std::path::Path) -> String { use std::os::unix::ffi::OsStrExt as _; let mut uri = String::from("file://"); - for &byte in path.as_os_str().as_bytes() { - if byte.is_ascii_alphanumeric() || b"/-._~".contains(&byte) { + push_percent_encoded(&mut uri, path.as_os_str().as_bytes(), b"/-._~"); + uri +} + +/// `C:\Users\me\my app` → `file:///C:/Users/me/my%20app`. +#[cfg(target_os = "windows")] +fn file_uri(path: &std::path::Path) -> String { + let text = path.to_string_lossy(); + // `canonicalize` returns `\\?\C:\…`; the prefix is not part of the path. + let text = text.strip_prefix(r"\\?\").unwrap_or(&text); + let text = text.replace('\\', "/"); + if let Some(unc) = text.strip_prefix("//") { + // `\\server\share\file` → `file://server/share/file`. + let mut uri = String::from("file://"); + push_percent_encoded(&mut uri, unc.as_bytes(), b"/-._~"); + uri + } else { + let mut uri = String::from("file:///"); + push_percent_encoded(&mut uri, text.trim_start_matches('/').as_bytes(), b"/-._~:"); + uri + } +} + +fn push_percent_encoded(uri: &mut String, bytes: &[u8], safe: &[u8]) { + for &byte in bytes { + if byte.is_ascii_alphanumeric() || safe.contains(&byte) { uri.push(byte as char); } else { uri.push_str(&format!("%{byte:02X}")); } } - uri } /// Files copied in Finder (file URLs on the general pasteboard). @@ -289,11 +385,153 @@ pub fn clipboard_file_paths() -> Vec { paths } -#[cfg(not(target_os = "macos"))] +/// Files copied in Explorer (a `CF_HDROP` on the clipboard). +#[cfg(target_os = "windows")] +pub fn clipboard_file_paths() -> Vec { + use windows::Win32::System::DataExchange::{ + CloseClipboard, GetClipboardData, IsClipboardFormatAvailable, OpenClipboard, + }; + use windows::Win32::System::Ole::CF_HDROP; + use windows::Win32::UI::Shell::{DragQueryFileW, HDROP}; + + // `DragQueryFileW` asks for the count with this index. + const FILES_COUNT: u32 = 0xFFFF_FFFF; + let mut paths = Vec::new(); + // SAFETY: standard clipboard API. The clipboard is closed on every path, + // and the returned handles are only read while it stays open. + unsafe { + if OpenClipboard(None).is_err() { + return paths; + } + if IsClipboardFormatAvailable(CF_HDROP.0 as u32).is_ok() + && let Ok(data) = GetClipboardData(CF_HDROP.0 as u32) + { + let hdrop = HDROP(data.0); + for index in 0..DragQueryFileW(hdrop, FILES_COUNT, None) { + let length = DragQueryFileW(hdrop, index, None) as usize; + let mut buffer = vec![0u16; length + 1]; + if DragQueryFileW(hdrop, index, Some(&mut buffer)) == 0 { + continue; + } + buffer.truncate(length); + paths.push(std::path::PathBuf::from(String::from_utf16_lossy(&buffer))); + } + } + let _ = CloseClipboard(); + } + paths +} + +#[cfg(all(unix, not(target_os = "macos")))] pub fn clipboard_file_paths() -> Vec { Vec::new() } +/// A timestamp as the local clock shows it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LocalTime { + pub year: i32, + /// 1–12. + pub month: u32, + pub day: u32, + pub hour: u32, + pub minute: u32, + pub second: u32, +} + +#[cfg(unix)] +pub fn local_time(ms: i64) -> LocalTime { + let seconds = (ms / 1000) as libc::time_t; + // SAFETY: localtime_r only writes into the struct we pass. + let tm = unsafe { + let mut tm: libc::tm = std::mem::zeroed(); + libc::localtime_r(&seconds, &mut tm); + tm + }; + LocalTime { + year: 1900 + tm.tm_year, + month: (tm.tm_mon + 1).clamp(1, 12) as u32, + day: tm.tm_mday.clamp(1, 31) as u32, + hour: tm.tm_hour.clamp(0, 23) as u32, + minute: tm.tm_min.clamp(0, 59) as u32, + second: tm.tm_sec.clamp(0, 60) as u32, + } +} + +#[cfg(target_os = "windows")] +pub fn local_time(ms: i64) -> LocalTime { + use windows::Win32::Foundation::{FILETIME, SYSTEMTIME}; + use windows::Win32::System::Time::{FileTimeToSystemTime, SystemTimeToTzSpecificLocalTime}; + + // FILETIME counts 100 ns ticks since 1601; Unix time counts seconds since 1970. + const UNIX_EPOCH_TICKS: i128 = 116_444_736_000_000_000; + let ticks = (ms.max(0) as i128 * 10_000 + UNIX_EPOCH_TICKS).min(u64::MAX as i128) as u64; + let file_time = FILETIME { + dwLowDateTime: ticks as u32, + dwHighDateTime: (ticks >> 32) as u32, + }; + let mut utc: SYSTEMTIME = unsafe { std::mem::zeroed() }; + let mut local: SYSTEMTIME = unsafe { std::mem::zeroed() }; + // SAFETY: both calls only write into SYSTEMTIME values we own; passing no + // time zone means the current one, with its daylight saving rule. + let converted = unsafe { + FileTimeToSystemTime(&file_time, &mut utc).is_ok() + && SystemTimeToTzSpecificLocalTime(None, &utc, &mut local).is_ok() + }; + if !converted { + return LocalTime { + year: 1970, + month: 1, + day: 1, + hour: 0, + minute: 0, + second: 0, + }; + } + LocalTime { + year: local.wYear as i32, + month: local.wMonth as u32, + day: local.wDay as u32, + hour: local.wHour as u32, + minute: local.wMinute as u32, + second: local.wSecond as u32, + } +} + +#[cfg(target_os = "windows")] +const CREATE_NO_WINDOW: u32 = 0x0800_0000; + +/// Keeps a console window from appearing when a GUI app starts a console +/// program. On other systems there is nothing to hide. +pub fn hide_console(command: &mut std::process::Command) { + #[cfg(target_os = "windows")] + { + use std::os::windows::process::CommandExt as _; + command.creation_flags(CREATE_NO_WINDOW); + } + #[cfg(not(target_os = "windows"))] + { + let _ = command; + } +} + +/// Stops a child and, on Windows, the processes it started. `cmd /c pi.cmd` +/// leaves node as a grandchild, which a plain `kill` would keep running. +pub fn kill_process_tree(child: &mut std::process::Child) -> std::io::Result<()> { + #[cfg(target_os = "windows")] + { + use std::process::Command; + + let mut command = Command::new("taskkill"); + command.args(["/PID", &child.id().to_string(), "/T", "/F"]); + hide_console(&mut command); + if command.status().is_ok_and(|status| status.success()) { + return Ok(()); + } + } + child.kill() +} + /// Asks for one or more folders with the system open panel. /// /// gpui builds a new `NSOpenPanel` for every prompt, and building one blocks diff --git a/src/plugins.rs b/src/plugins.rs index e39f6bb..a0ac3e8 100644 --- a/src/plugins.rs +++ b/src/plugins.rs @@ -939,6 +939,7 @@ impl PluginRegistry { .current_dir(&plugin.dir) .env("PATH", pi::path_with_executable_dir(&program)) .env("PI_GPUI_PLUGIN_DIR", &plugin.dir); + crate::platform::hide_console(&mut command); JsonlProcess::spawn(&mut command).map_err(|error| error.to_string()) }); match spawned { diff --git a/src/pty.rs b/src/pty.rs new file mode 100644 index 0000000..2348af2 --- /dev/null +++ b/src/pty.rs @@ -0,0 +1,486 @@ +//! A pseudo-terminal for `pi auth login`, which needs a terminal to ask its +//! questions: a Unix pty here, a Windows ConPTY there. The app shows what the +//! child prints and writes the answers back. +//! +//! The terminal is 40 rows by 200 columns, wide enough that pi's lines do not +//! wrap. + +use std::ffi::OsString; +use std::fs::File; +use std::path::Path; + +const ROWS: u16 = 40; +const COLUMNS: u16 = 200; + +/// What the child has done since the last look. +pub enum Status { + Running, + Exited(Option), +} + +pub struct Pty { + /// What the user types, written to the child. + pub input: File, + /// What the child prints (a second handle to the same terminal). + pub reader: File, + pub child: Child, + /// The ConPTY console on Windows; it must outlive the child. Unit elsewhere. + pub keep_alive: KeepAlive, +} + +#[cfg(unix)] +pub type KeepAlive = (); +#[cfg(target_os = "windows")] +pub type KeepAlive = windows_impl::Console; + +pub fn spawn(program: &Path, args: &[OsString], env: &[(&str, OsString)]) -> std::io::Result { + #[cfg(unix)] + { + unix::spawn(program, args, env) + } + #[cfg(target_os = "windows")] + { + windows_impl::spawn(program, args, env) + } +} + +/// The child process of a pty, on either platform. +pub enum Child { + #[cfg(unix)] + Unix(std::process::Child), + #[cfg(target_os = "windows")] + Windows(windows_impl::Child), +} + +impl Child { + pub fn try_wait(&mut self) -> Status { + match self { + #[cfg(unix)] + Child::Unix(child) => match child.try_wait() { + Ok(Some(status)) => Status::Exited(status.code()), + Ok(None) => Status::Running, + Err(_) => Status::Exited(None), + }, + #[cfg(target_os = "windows")] + Child::Windows(child) => child.try_wait(), + } + } + + pub fn kill(&mut self) { + match self { + #[cfg(unix)] + Child::Unix(child) => { + child.kill().ok(); + } + #[cfg(target_os = "windows")] + Child::Windows(child) => child.kill(), + } + } +} + +#[cfg(unix)] +mod unix { + use std::ffi::{OsStr, OsString}; + use std::fs::File; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::os::unix::process::CommandExt as _; + use std::path::Path; + use std::process::{Command, Stdio}; + + use super::{COLUMNS, Child, Pty, ROWS}; + + pub fn spawn( + program: &Path, + args: &[OsString], + env: &[(&str, OsString)], + ) -> std::io::Result { + let (master, slave) = open_pty()?; + let mut command = Command::new(program); + command.args(args); + for (key, value) in env { + command.env(*key, value); + } + command + .stdin(Stdio::from(slave.try_clone()?)) + .stdout(Stdio::from(slave.try_clone()?)) + .stderr(Stdio::from(slave)); + // SAFETY: only async-signal-safe calls between fork and exec. + unsafe { + command.pre_exec(|| { + if libc::setsid() < 0 { + return Err(std::io::Error::last_os_error()); + } + if libc::ioctl(0, libc::TIOCSCTTY as _, 0) < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let child = command.spawn()?; + // The parent's copies of the slave are closed now (dropped with + // `command`), so reading the master ends when the child exits. + drop(command); + let reader = File::from(master); + let input = reader.try_clone()?; + Ok(Pty { + input, + reader, + child: Child::Unix(child), + keep_alive: (), + }) + } + + /// A pseudo-terminal of `COLUMNS` by `ROWS`. + fn open_pty() -> std::io::Result<(OwnedFd, OwnedFd)> { + let mut master = -1; + let mut slave = -1; + let size = libc::winsize { + ws_row: ROWS, + ws_col: COLUMNS, + ws_xpixel: 0, + ws_ypixel: 0, + }; + // SAFETY: openpty writes two descriptors we then own. + let result = unsafe { + libc::openpty( + &mut master, + &mut slave, + std::ptr::null_mut(), + std::ptr::null_mut(), + &size as *const libc::winsize as *mut libc::winsize, + ) + }; + if result != 0 { + return Err(std::io::Error::last_os_error()); + } + // SAFETY: both descriptors are open and owned by nobody else. + let (master, slave) = + unsafe { (OwnedFd::from_raw_fd(master), OwnedFd::from_raw_fd(slave)) }; + // The master must not leak into the child. + // SAFETY: setting FD_CLOEXEC on a descriptor we own. + unsafe { libc::fcntl(master.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) }; + Ok((master, slave)) + } +} + +#[cfg(target_os = "windows")] +mod windows_impl { + use std::ffi::{OsStr, OsString}; + use std::fs::File; + use std::mem::size_of; + use std::os::windows::ffi::OsStrExt as _; + use std::os::windows::io::{FromRawHandle, RawHandle}; + use std::path::Path; + + use windows::Win32::Foundation::{CloseHandle, HANDLE}; + use windows::Win32::System::Console::{COORD, ClosePseudoConsole, CreatePseudoConsole, HPCON}; + use windows::Win32::System::Pipes::CreatePipe; + use windows::Win32::System::Threading::{ + CREATE_UNICODE_ENVIRONMENT, CreateProcessW, DeleteProcThreadAttributeList, + EXTENDED_STARTUPINFO_PRESENT, InitializeProcThreadAttributeList, + LPPROC_THREAD_ATTRIBUTE_LIST, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, PROCESS_INFORMATION, + STARTUPINFOEXW, UpdateProcThreadAttribute, + }; + use windows::core::{PCWSTR, PWSTR}; + + use super::{COLUMNS, Pty, ROWS, Status}; + + /// The ConPTY side of the terminal. It must stay open while the child runs. + pub struct Console(HPCON); + + // The handle is process-local and only used from the thread that owns it. + unsafe impl Send for Console {} + + impl Drop for Console { + fn drop(&mut self) { + // SAFETY: we own the console and close it once. + unsafe { ClosePseudoConsole(self.0) }; + } + } + + /// The child process, as a Win32 handle instead of a `std::process::Child` + /// (ConPTY needs `CreateProcessW` directly). + pub struct Child { + process: HANDLE, + exited: Option>, + } + + // HANDLE is process-local and this one is only used from one thread at a + // time (behind the mutex in pi_auth). + unsafe impl Send for Child {} + + impl Drop for Child { + fn drop(&mut self) { + // SAFETY: we own the handle and close it once. + unsafe { + let _ = CloseHandle(self.process); + } + } + } + + impl Child { + pub fn try_wait(&mut self) -> Status { + if let Some(code) = self.exited { + return match code { + Some(code) => Status::Exited(Some(code)), + None => Status::Exited(None), + }; + } + const STILL_ACTIVE: u32 = 259; + let mut code = 0u32; + // SAFETY: the handle is valid for the life of this value. + let read = unsafe { + windows::Win32::System::Threading::GetExitCodeProcess(self.process, &mut code) + }; + if read.is_err() || code == STILL_ACTIVE { + return Status::Running; + } + self.exited = Some(Some(code as i32)); + Status::Exited(Some(code as i32)) + } + + pub fn kill(&mut self) { + // SAFETY: the handle is valid; a process that already exited makes + // TerminateProcess fail, which is fine. + unsafe { + let _ = windows::Win32::System::Threading::TerminateProcess(self.process, 1); + } + } + } + + pub fn spawn( + program: &Path, + args: &[OsString], + env: &[(&str, OsString)], + ) -> std::io::Result { + let (input_read, input_write) = pipe()?; + let (output_read, output_write) = pipe()?; + + // SAFETY: the two pipe ends are open; on success the console owns them + // and we close our copies right after. + let console = unsafe { + CreatePseudoConsole( + COORD { + X: COLUMNS as i16, + Y: ROWS as i16, + }, + input_read, + output_write, + 0, + ) + } + .map_err(|error| std::io::Error::other(error.to_string()))?; + // SAFETY: the console took its own references to these ends. + unsafe { + let _ = CloseHandle(input_read); + let _ = CloseHandle(output_write); + } + let console = Console(console); + + let mut command_line = command_line(program, args); + let environment = environment_block(env); + let attributes = AttributeList::new(console.0)?; + let mut process = PROCESS_INFORMATION::default(); + let mut startup: STARTUPINFOEXW = unsafe { std::mem::zeroed() }; + startup.StartupInfo.cb = size_of::() as u32; + startup.lpAttributeList = attributes.list; + + // SAFETY: the command line is null-terminated and mutable, the + // environment block is null-terminated, and every out-pointer is valid + // for the duration of the call. + let created = unsafe { + CreateProcessW( + PCWSTR::null(), + Some(PWSTR(command_line.as_mut_ptr())), + None, + None, + false, + EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT, + Some(environment.as_ptr() as *const std::ffi::c_void), + PCWSTR::null(), + &startup.StartupInfo, + &mut process, + ) + }; + if let Err(error) = created { + return Err(std::io::Error::other(error.to_string())); + } + // The thread handle is not needed; the process handle is. + // SAFETY: both handles were returned by CreateProcessW and are ours. + unsafe { + let _ = CloseHandle(process.hThread); + } + + // SAFETY: the pipes are open and nobody else owns these ends. + let input = unsafe { File::from_raw_handle(input_write.0 as RawHandle) }; + let reader = unsafe { File::from_raw_handle(output_read.0 as RawHandle) }; + Ok(Pty { + input, + reader, + child: super::Child::Windows(Child { + process: process.hProcess, + exited: None, + }), + keep_alive: console, + }) + } + + fn pipe() -> std::io::Result<(HANDLE, HANDLE)> { + let mut read = HANDLE(std::ptr::null_mut()); + let mut write = HANDLE(std::ptr::null_mut()); + // SAFETY: CreatePipe writes the two handles into our variables. + unsafe { CreatePipe(&mut read, &mut write, None, 0) } + .map_err(|error| std::io::Error::other(error.to_string()))?; + Ok((read, write)) + } + + /// The process-wide attribute list that carries the HPCON to the child. + struct AttributeList { + list: LPPROC_THREAD_ATTRIBUTE_LIST, + _buffer: Vec, + } + + impl AttributeList { + fn new(console: HPCON) -> std::io::Result { + let mut size = 0usize; + // SAFETY: a null list with a size out-pointer asks for the size; + // the call is expected to fail with ERROR_INSUFFICIENT_BUFFER. + let _ = unsafe { InitializeProcThreadAttributeList(None, 1, None, &mut size) }.ok(); + if size == 0 { + return Err(std::io::Error::other( + "could not size the process attribute list", + )); + } + let words = size.div_ceil(size_of::()); + let mut buffer = vec![0usize; words]; + let list = LPPROC_THREAD_ATTRIBUTE_LIST(buffer.as_mut_ptr().cast()); + // SAFETY: the buffer is large enough (the API said so) and lives + // until the attribute list is deleted in Drop. + unsafe { + InitializeProcThreadAttributeList(Some(list), 1, None, &mut size) + .and_then(|()| { + UpdateProcThreadAttribute( + list, + 0, + PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE as usize, + Some(&console as *const HPCON as *const std::ffi::c_void), + size_of::(), + None, + None, + ) + }) + .map_err(|error| std::io::Error::other(error.to_string()))?; + } + // The buffer must stay alive as long as the list points into it. + Ok(Self { + list, + _buffer: buffer, + }) + } + } + + impl Drop for AttributeList { + fn drop(&mut self) { + // SAFETY: the list was initialized once and is deleted once; its + // buffer is still owned by this struct. + unsafe { DeleteProcThreadAttributeList(self.list) }; + } + } + + /// `program args…`, quoted the way `CreateProcessW` parses it and null + /// terminated. + fn command_line(program: &Path, args: &[OsString]) -> Vec { + let mut line = Vec::new(); + let batch = program + .extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| { + extension.eq_ignore_ascii_case("cmd") || extension.eq_ignore_ascii_case("bat") + }); + if batch { + // npm installs pi as `pi.cmd`; CreateProcess cannot start that + // directly, so run it through the command interpreter. + let interpreter = + std::env::var_os("ComSpec").unwrap_or_else(|| OsString::from("cmd.exe")); + push_quoted(&mut line, &interpreter); + line.extend(" /d /s /c ".encode_utf16()); + // `/s` means "strip exactly the outer quotes and use the rest". + line.push(b'"' as u16); + push_quoted(&mut line, program.as_os_str()); + for arg in args { + line.push(b' ' as u16); + push_quoted(&mut line, arg); + } + line.push(b'"' as u16); + } else { + push_quoted(&mut line, program.as_os_str()); + for arg in args { + line.push(b' ' as u16); + push_quoted(&mut line, arg); + } + } + line.push(0); + line + } + + /// One argument, quoted as `CommandLineToArgvW` and `cmd` expect it. + fn push_quoted(line: &mut Vec, argument: &OsStr) { + let wide: Vec = argument.encode_wide().collect(); + let plain = !wide.is_empty() + && !wide + .iter() + .any(|character| [b' ', b'\t', b'"'].contains(&(*character as u8))); + if plain { + line.extend(wide); + return; + } + line.push(b'"' as u16); + let mut backslashes = 0; + for character in wide { + match character { + character if character == b'\\' as u16 => backslashes += 1, + character if character == b'"' as u16 => { + line.extend(std::iter::repeat_n(b'\\' as u16, backslashes * 2 + 1)); + line.push(b'"' as u16); + backslashes = 0; + } + character => { + line.extend(std::iter::repeat_n(b'\\' as u16, backslashes)); + backslashes = 0; + line.push(character); + } + } + } + line.extend(std::iter::repeat_n(b'\\' as u16, backslashes * 2)); + line.push(b'"' as u16); + } + + /// The parent's environment with `env` applied, as `CreateProcessW` wants + /// it: sorted, `KEY=VALUE` entries, double null terminated. + fn environment_block(env: &[(&str, OsString)]) -> Vec { + let mut variables: Vec<(OsString, OsString)> = std::env::vars_os() + .filter(|(key, _)| { + !env.iter() + .any(|(name, _)| key.to_string_lossy().eq_ignore_ascii_case(name)) + }) + .collect(); + for (key, value) in env { + variables.push((OsString::from(*key), value.clone())); + } + variables.sort_by(|left, right| { + left.0 + .to_string_lossy() + .to_uppercase() + .cmp(&right.0.to_string_lossy().to_uppercase()) + }); + let mut block = Vec::new(); + for (key, value) in variables { + block.extend(key.encode_wide()); + block.push(b'=' as u16); + block.extend(value.encode_wide()); + block.push(0); + } + block.push(0); + block + } +} diff --git a/src/sessions.rs b/src/sessions.rs index 621358f..b851bc4 100644 --- a/src/sessions.rs +++ b/src/sessions.rs @@ -7,6 +7,7 @@ use std::collections::HashSet; use std::fs::{self, File}; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; +#[cfg(not(target_os = "windows"))] use std::process::{Command, Stdio}; use std::time::{Duration, SystemTime}; @@ -186,6 +187,7 @@ pub fn foreign_lease_holder(session: &Path) -> Option { ) } +#[cfg(not(target_os = "windows"))] fn process_is_alive(pid: u64) -> bool { Command::new("kill") .args(["-0", &pid.to_string()]) @@ -195,6 +197,27 @@ fn process_is_alive(pid: u64) -> bool { .is_ok_and(|status| status.success()) } +#[cfg(target_os = "windows")] +fn process_is_alive(pid: u64) -> bool { + use windows::Win32::Foundation::CloseHandle; + use windows::Win32::System::Threading::{ + GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, + }; + + // What GetExitCodeProcess reports while the process has not ended. + const STILL_ACTIVE: u32 = 259; + // SAFETY: the handle is closed before returning; the out-pointer is valid. + unsafe { + let Ok(process) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid as u32) else { + return false; + }; + let mut code = 0; + let alive = GetExitCodeProcess(process, &mut code).is_ok() && code == STILL_ACTIVE; + let _ = CloseHandle(process); + alive + } +} + pub fn message_text(message: &Value) -> String { if let Some(text) = message["content"].as_str() { return text.to_string(); @@ -243,7 +266,11 @@ pub fn display_path(path: &Path) -> String { } pub fn home_directory() -> Option { - std::env::var_os("HOME").map(PathBuf::from) + #[cfg(target_os = "windows")] + let variable = "USERPROFILE"; + #[cfg(not(target_os = "windows"))] + let variable = "HOME"; + std::env::var_os(variable).map(PathBuf::from) } /// The app's own files (settings, projects, plugins): `~/Library/Application @@ -253,6 +280,13 @@ pub fn app_data_directory() -> Option { if cfg!(target_os = "macos") { return Some(home_directory()?.join("Library/Application Support/pi-gpui")); } + if cfg!(target_os = "windows") { + return std::env::var_os("APPDATA") + .map(PathBuf::from) + .filter(|path| path.is_absolute()) + .map(|path| path.join("pi-gpui")) + .or_else(|| Some(home_directory()?.join("AppData/Roaming/pi-gpui"))); + } Some(xdg_directory("XDG_CONFIG_HOME", ".config")?.join("pi-gpui")) } @@ -262,6 +296,13 @@ pub fn app_cache_directory() -> Option { if cfg!(target_os = "macos") { return Some(home_directory()?.join("Library/Caches/pi-gpui")); } + if cfg!(target_os = "windows") { + return std::env::var_os("LOCALAPPDATA") + .map(PathBuf::from) + .filter(|path| path.is_absolute()) + .map(|path| path.join("pi-gpui/cache")) + .or_else(|| Some(home_directory()?.join("AppData/Local/pi-gpui/cache"))); + } Some(xdg_directory("XDG_CACHE_HOME", ".cache")?.join("pi-gpui")) } @@ -312,12 +353,14 @@ mod tests { let workspace = directory.canonicalize().expect("canonical"); let session = workspace.join("session.jsonl"); let mut file = File::create(&session).expect("session file"); - writeln!( - file, - r#"{{"type":"session","version":3,"id":"x","cwd":"{}"}}"#, - workspace.display() - ) - .expect("write"); + // serde_json escapes the backslashes Windows paths contain. + let header = serde_json::json!({ + "type": "session", + "version": 3, + "id": "x", + "cwd": workspace.to_string_lossy(), + }); + writeln!(file, "{header}").expect("write"); writeln!(file, r#"{{"type":"message","id":"a","message":{{"role":"user","content":" \nFirst question\nsecond line"}}}}"#).expect("write"); drop(file); assert_eq!( diff --git a/src/single_instance.rs b/src/single_instance.rs index de802f7..379c6e6 100644 --- a/src/single_instance.rs +++ b/src/single_instance.rs @@ -1,12 +1,8 @@ -//! One app per user on Linux. macOS routes `pi-gpui://` links and reopening to -//! the running app by itself; on Linux every launch (from the dock, a -//! `.desktop` link handler or a terminal) is a new process. The first one -//! listens on a socket in `$XDG_RUNTIME_DIR`; later ones hand it their link -//! and exit. - -use std::io::{BufRead as _, BufReader, Write as _}; -use std::os::unix::net::{UnixListener, UnixStream}; -use std::path::PathBuf; +//! One app per user. macOS routes `pi-gpui://` links and reopening to the +//! running app by itself; on Linux and Windows every launch (from the dock, a +//! link handler or a terminal) is a new process. The first one listens on a +//! socket (`$XDG_RUNTIME_DIR` on Linux, a named pipe on Windows); later ones +//! hand it their link and exit. /// Sent when the app is launched again without a link: bring it forward. pub const ACTIVATE: &str = "activate"; @@ -14,52 +10,190 @@ pub const ACTIVATE: &str = "activate"; /// Hands `message` to an app that is already running. `true` when it took /// it, so this process should exit. pub fn forward(message: &str) -> bool { - let Some(path) = socket_path() else { - return false; - }; - let Ok(mut stream) = UnixStream::connect(&path) else { - return false; - }; - stream.write_all(format!("{message}\n").as_bytes()).is_ok() + #[cfg(unix)] + { + unix::forward(message) + } + #[cfg(target_os = "windows")] + { + windows_impl::forward(message) + } } /// Listens for later launches; each message goes to `deliver` on a /// background thread. pub fn listen(deliver: impl Fn(String) + Send + 'static) { - let Some(path) = socket_path() else { - return; - }; - // `forward` found nobody listening, so a file left here is stale. - let _ = std::fs::remove_file(&path); - let listener = match UnixListener::bind(&path) { - Ok(listener) => listener, - Err(error) => { - eprintln!("pi-gpui: cannot listen on {}: {error}", path.display()); + #[cfg(unix)] + unix::listen(deliver); + #[cfg(target_os = "windows")] + windows_impl::listen(deliver); +} + +#[cfg(unix)] +mod unix { + use std::io::{BufRead as _, BufReader, Write as _}; + use std::os::unix::net::{UnixListener, UnixStream}; + use std::path::PathBuf; + + /// Hands `message` to an app that is already running. `true` when it took + /// it, so this process should exit. + pub fn forward(message: &str) -> bool { + let Some(path) = socket_path() else { + return false; + }; + let Ok(mut stream) = UnixStream::connect(&path) else { + return false; + }; + stream.write_all(format!("{message}\n").as_bytes()).is_ok() + } + + pub fn listen(deliver: impl Fn(String) + Send + 'static) { + let Some(path) = socket_path() else { return; - } - }; - std::thread::spawn(move || { - for stream in listener.incoming().flatten() { - let mut line = String::new(); - if BufReader::new(stream).read_line(&mut line).is_ok() { - let message = line.trim().to_string(); - if !message.is_empty() { - deliver(message); + }; + // `forward` found nobody listening, so a file left here is stale. + let _ = std::fs::remove_file(&path); + let listener = match UnixListener::bind(&path) { + Ok(listener) => listener, + Err(error) => { + eprintln!("pi-gpui: cannot listen on {}: {error}", path.display()); + return; + } + }; + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let mut line = String::new(); + if BufReader::new(stream).read_line(&mut line).is_ok() { + let message = line.trim().to_string(); + if !message.is_empty() { + deliver(message); + } } } - } - }); + }); + } + + fn socket_path() -> Option { + let runtime = std::env::var_os("XDG_RUNTIME_DIR") + .map(PathBuf::from) + .filter(|path| path.is_absolute() && path.is_dir())?; + // Development builds keep to themselves, so `cargo run` works while the + // installed app is open. + Some(runtime.join(if cfg!(debug_assertions) { + "pi-gpui-dev.sock" + } else { + "pi-gpui.sock" + })) + } } -fn socket_path() -> Option { - let runtime = std::env::var_os("XDG_RUNTIME_DIR") - .map(PathBuf::from) - .filter(|path| path.is_absolute() && path.is_dir())?; - // Development builds keep to themselves, so `cargo run` works while the - // installed app is open. - Some(runtime.join(if cfg!(debug_assertions) { - "pi-gpui-dev.sock" - } else { - "pi-gpui.sock" - })) +#[cfg(target_os = "windows")] +mod windows_impl { + use std::fs::File; + use std::io::{BufRead as _, BufReader, Write as _}; + use std::os::windows::io::{FromRawHandle as _, RawHandle}; + + use windows::Win32::Storage::FileSystem::{ + CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_READ, + FILE_SHARE_WRITE, OPEN_EXISTING, PIPE_ACCESS_DUPLEX, + }; + use windows::Win32::System::Pipes::{ + ConnectNamedPipe, CreateNamedPipeW, NAMED_PIPE_MODE, PIPE_READMODE_BYTE, PIPE_TYPE_BYTE, + PIPE_UNLIMITED_INSTANCES, PIPE_WAIT, + }; + use windows::core::PCWSTR; + + /// Hands `message` to an app that is already running. `true` when it took + /// it, so this process should exit. + pub fn forward(message: &str) -> bool { + let Some(mut path) = pipe_path() else { + return false; + }; + path.push(0); + // SAFETY: the path is null-terminated and outlives the call; the pipe + // handle becomes a File, which closes it. + let opened = unsafe { + CreateFileW( + PCWSTR(path.as_ptr()), + FILE_GENERIC_READ.0 | FILE_GENERIC_WRITE.0, + FILE_SHARE_READ | FILE_SHARE_WRITE, + None, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + None, + ) + }; + let Ok(handle) = opened else { + return false; + }; + // SAFETY: CreateFileW returned this handle and nothing else owns it. + let mut pipe = unsafe { File::from_raw_handle(handle.0 as RawHandle) }; + pipe.write_all(format!("{message}\n").as_bytes()).is_ok() + } + + pub fn listen(deliver: impl Fn(String) + Send + 'static) { + let Some(mut path) = pipe_path() else { + return; + }; + path.push(0); + std::thread::spawn(move || { + loop { + // A new instance for every connection: pipes serve one client. + // SAFETY: the path is null-terminated and outlives the call. + let handle = unsafe { + CreateNamedPipeW( + PCWSTR(path.as_ptr()), + PIPE_ACCESS_DUPLEX, + NAMED_PIPE_MODE(PIPE_TYPE_BYTE.0 | PIPE_READMODE_BYTE.0 | PIPE_WAIT.0), + PIPE_UNLIMITED_INSTANCES, + 4096, + 4096, + 0, + None, + ) + }; + if handle.is_invalid() { + let error = std::io::Error::last_os_error(); + eprintln!("pi-gpui: cannot listen on a named pipe: {error}"); + return; + } + // SAFETY: a client may have connected between creating the pipe + // and this call; that error is expected and harmless. + unsafe { + let _ = ConnectNamedPipe(handle, None); + } + // SAFETY: the pipe handle is open and nothing else owns it. + let pipe = unsafe { File::from_raw_handle(handle.0 as RawHandle) }; + let mut line = String::new(); + if BufReader::new(pipe).read_line(&mut line).is_ok() { + let message = line.trim().to_string(); + if !message.is_empty() { + deliver(message); + } + } + } + }); + } + + /// `\\.\pipe\pi-gpui-[-dev]`, the Windows socket in the user's + /// session. The default security descriptor keeps other users out. + fn pipe_path() -> Option> { + let user = std::env::var("USERNAME").unwrap_or_else(|_| "user".to_string()); + let user: String = user + .chars() + .map(|character| { + if character.is_ascii_alphanumeric() { + character + } else { + '_' + } + }) + .collect(); + let name = if cfg!(debug_assertions) { + format!("pi-gpui-{user}-dev") + } else { + format!("pi-gpui-{user}") + }; + Some(format!(r"\\.\pipe\{name}").encode_utf16().collect()) + } } diff --git a/src/updater.rs b/src/updater.rs index ab856a6..8186792 100644 --- a/src/updater.rs +++ b/src/updater.rs @@ -229,6 +229,9 @@ impl AutoUpdater { let Some(bundle) = self.bundle.clone() else { return; }; + #[cfg(target_os = "windows")] + self.restart_to_update_after_exit(&bundle, cx); + #[cfg(not(target_os = "windows"))] match swap_in_staged(&bundle) { Ok(old) => { let cleanup = format!("rm -rf {}; ", shell_quote(&old)); @@ -252,8 +255,64 @@ impl AutoUpdater { } } + /// Windows keeps the running `.exe` locked, so the swap happens in a + /// detached PowerShell process that waits for this one to exit. + #[cfg(target_os = "windows")] + fn restart_to_update_after_exit(&mut self, bundle: &Path, cx: &mut Context) { + let staged = match staged_path(bundle) { + Ok(staged) if staged.is_dir() => staged, + Ok(_) => { + self.status = UpdateStatus::Idle; + self.manual_result = Some(UpdateStatus::Failed( + "the downloaded update is gone; it will be downloaded again".to_string(), + )); + cx.notify(); + return; + } + Err(error) => { + self.status = UpdateStatus::Idle; + self.manual_result = Some(UpdateStatus::Failed(error)); + cx.notify(); + return; + } + }; + let old = bundle.with_file_name(format!( + ".{}.old", + bundle + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("app") + )); + let launch = bundle.join("bin/pi-gpui.exe"); + let script = format!( + "Wait-Process -Id {pid} -ErrorAction SilentlyContinue; \ + Start-Sleep -Milliseconds 300; \ + Remove-Item -LiteralPath {old} -Recurse -Force -ErrorAction SilentlyContinue; \ + Move-Item -LiteralPath {bundle} -Destination {old} -Force; \ + Move-Item -LiteralPath {staged} -Destination {bundle} -Force; \ + Start-Process -FilePath {launch}; \ + Start-Sleep -Milliseconds 300; \ + Remove-Item -LiteralPath {old} -Recurse -Force -ErrorAction SilentlyContinue", + pid = std::process::id(), + old = powershell_quote(&old), + bundle = powershell_quote(bundle), + staged = powershell_quote(&staged), + launch = powershell_quote(&launch), + ); + if let Err(error) = run_powershell(&script) { + self.status = UpdateStatus::Idle; + self.manual_result = Some(UpdateStatus::Failed(format!( + "could not restart to update: {error}" + ))); + cx.notify(); + return; + } + cx.quit(); + } + /// A shell waits for this process to exit, runs `cleanup`, then launches /// the app; this process quits. + #[cfg(not(target_os = "windows"))] fn relaunch_after_exit(&mut self, cleanup: String, cx: &mut Context) { let launch = match &self.bundle { Some(bundle) if cfg!(target_os = "macos") => format!("open {}", shell_quote(bundle)), @@ -290,6 +349,40 @@ impl AutoUpdater { } cx.quit(); } + + /// Windows: a detached PowerShell waits for this process, then starts the + /// app again (the running `.exe` stays locked until then). + #[cfg(target_os = "windows")] + fn relaunch_after_exit(&mut self, _cleanup: String, cx: &mut Context) { + let launch = match &self.bundle { + Some(bundle) => bundle.join("bin/pi-gpui.exe"), + None => match std::env::current_exe() { + Ok(executable) => executable, + Err(error) => { + self.manual_result = Some(UpdateStatus::Failed(format!( + "could not find the app to relaunch: {error}" + ))); + cx.notify(); + return; + } + }, + }; + let script = format!( + "Wait-Process -Id {pid} -ErrorAction SilentlyContinue; \ + Start-Process -FilePath {launch}", + pid = std::process::id(), + launch = powershell_quote(&launch), + ); + if let Err(error) = run_powershell(&script) { + self.status = UpdateStatus::Idle; + self.manual_result = Some(UpdateStatus::Failed(format!( + "could not relaunch: {error}; open the app again" + ))); + cx.notify(); + return; + } + cx.quit(); + } } struct Release { @@ -332,11 +425,14 @@ fn latest_release(current: Version, pi: Option) -> Result Result, String> { - let output = Command::new("curl") + let mut command = Command::new("curl"); + command .args(["-fsSL", "--max-time", "30"]) .args(["-H", "Accept: application/vnd.github+json"]) .args(["-H", &format!("User-Agent: pi-gpui/{current}")]) - .arg(url) + .arg(url); + crate::platform::hide_console(&mut command); + let output = command .output() .map_err(|error| format!("could not run curl: {error}"))?; if output.status.success() { @@ -354,6 +450,8 @@ fn fetch(url: &str, current: Version) -> Result, String> { fn asset_suffix(arch: &str) -> String { if cfg!(target_os = "macos") { format!("-{arch}.zip") + } else if cfg!(target_os = "windows") { + format!("-windows-{arch}.zip") } else { format!("-linux-{arch}.tar.gz") } @@ -420,6 +518,9 @@ fn stage(release: &Release, bundle: &Path) -> Result<(), String> { .arg(&archive) .arg(&release.url))?; let unpacked = cache.join("unpacked"); + if cfg!(target_os = "windows") { + return stage_windows(release, bundle, &archive, &unpacked, &cache); + } if !cfg!(target_os = "macos") { return stage_linux(release, bundle, &archive, &unpacked, &cache); } @@ -500,8 +601,69 @@ fn stage_linux( Ok(()) } +/// Windows: the zip holds `pi-gpui.app/` (`bin/`, `share/`); `tar` (bsdtar) +/// unpacks zip files too. The new binary must report the expected version +/// before it is staged. +fn stage_windows( + release: &Release, + bundle: &Path, + archive: &Path, + unpacked: &Path, + cache: &Path, +) -> Result<(), String> { + std::fs::create_dir_all(unpacked).map_err(|error| error.to_string())?; + run(Command::new("tar") + .arg("-xf") + .arg(archive) + .arg("-C") + .arg(unpacked))?; + let app = unpacked.join("pi-gpui.app"); + let binary = app.join("bin/pi-gpui.exe"); + let output = Command::new(&binary) + .arg("--version") + .output() + .map_err(|error| format!("the download has no working app: {error}"))?; + let reported = String::from_utf8_lossy(&output.stdout); + if Version::find_in(&reported) != Some(release.version) { + return Err(format!( + "the download is not Pi GPUI {} ({})", + release.version, + reported.trim() + )); + } + let staged = staged_path(bundle)?; + let _ = std::fs::remove_dir_all(&staged); + copy_directory(&app, &staged).map_err(|error| { + format!( + "could not write next to the app in {} ({error})", + bundle + .parent() + .map_or_else(String::new, |parent| parent.display().to_string()) + ) + })?; + let _ = std::fs::remove_dir_all(cache); + Ok(()) +} + +/// A recursive copy; `cp -a` is not on Windows. +fn copy_directory(from: &Path, to: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(to)?; + for entry in std::fs::read_dir(from)? { + let entry = entry?; + let destination = to.join(entry.file_name()); + if entry.file_type()?.is_dir() { + copy_directory(&entry.path(), &destination)?; + } else { + std::fs::copy(entry.path(), destination)?; + } + } + Ok(()) +} + /// Moves the running app aside and the staged one into its place. Returns -/// where the old app went (removed after the relaunch). +/// where the old app went (removed after the relaunch). Windows swaps after +/// the process exits instead. +#[cfg(not(target_os = "windows"))] fn swap_in_staged(bundle: &Path) -> Result { let staged = staged_path(bundle)?; if !staged.is_dir() { @@ -544,6 +706,7 @@ fn plist_value(plist: &Path, key: &str) -> Result { } fn run(command: &mut Command) -> Result<(), String> { + crate::platform::hide_console(command); let output = command.output().map_err(|error| error.to_string())?; if output.status.success() { Ok(()) @@ -552,11 +715,21 @@ fn run(command: &mut Command) -> Result<(), String> { } } -/// `…/Pi GPUI.app` when running from a bundle; on Linux the install folder -/// from the release tarball (`…/pi-gpui.app/bin/pi-gpui`). A binary a distro -/// package put in `/usr/bin` is not one: its package manager updates it. +/// `…/Pi GPUI.app` when running from a bundle; on Linux and Windows the +/// install folder from the release archive (`…/pi-gpui.app/bin/pi-gpui`). A +/// binary a distro package put in `/usr/bin` is not one: its package manager +/// updates it. fn running_bundle() -> Option { let executable = std::env::current_exe().ok()?.canonicalize().ok()?; + // PowerShell and `Move-Item` are happier without the verbatim prefix. + #[cfg(target_os = "windows")] + let executable = { + let text = executable.to_string_lossy(); + match text.strip_prefix(r"\\?\") { + Some(rest) => PathBuf::from(rest), + None => executable, + } + }; if !cfg!(target_os = "macos") { let bin = executable.parent()?; let prefix = bin.parent()?; @@ -591,6 +764,38 @@ fn remember_version() -> Option { .filter(|previous| previous != current) } +/// A PowerShell single-quoted string: paths may contain spaces and quotes. +#[cfg(target_os = "windows")] +fn powershell_quote(path: &Path) -> String { + format!("'{}'", path.display().to_string().replace('\'', "''")) +} + +/// Runs a detached PowerShell command without flashing a console window. +#[cfg(target_os = "windows")] +fn run_powershell(script: &str) -> Result<(), String> { + use std::os::windows::process::CommandExt as _; + + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let output = Command::new("powershell") + .args([ + "-NoProfile", + "-NonInteractive", + "-WindowStyle", + "Hidden", + "-Command", + script, + ]) + .creation_flags(CREATE_NO_WINDOW) + .output() + .map_err(|error| error.to_string())?; + if output.status.success() { + Ok(()) + } else { + Err(String::from_utf8_lossy(&output.stderr).trim().to_string()) + } +} + +#[cfg(not(target_os = "windows"))] fn shell_quote(path: &Path) -> String { format!("'{}'", path.display().to_string().replace('\'', r"'\''")) }