diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 0b60668b2b..fcd7b2c28e 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -1134,7 +1134,7 @@ "clap_lex_1.0.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1.0.14\"}],\"features\":{}}", "clap_lex_1.1.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1.0.16\"}],\"features\":{}}", "clatter_2.2.0": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"aes\"],\"name\":\"aes-gcm\",\"optional\":true,\"req\":\"^0.10.3\"},{\"default_features\":false,\"features\":[\"zeroize\"],\"name\":\"arrayvec\",\"req\":\"^0.7.6\"},{\"default_features\":false,\"name\":\"blake2\",\"optional\":true,\"req\":\"^0.10.6\"},{\"default_features\":false,\"features\":[\"rand_core\"],\"name\":\"chacha20poly1305\",\"optional\":true,\"req\":\"^0.10.1\"},{\"default_features\":false,\"name\":\"displaydoc\",\"req\":\"^0.2.5\"},{\"name\":\"getrandom\",\"optional\":true,\"req\":\"^0.3.3\"},{\"default_features\":false,\"features\":[\"zeroize\"],\"name\":\"ml-kem\",\"optional\":true,\"req\":\"^0.2.1\"},{\"default_features\":false,\"name\":\"pqcrypto-mlkem\",\"optional\":true,\"req\":\"^0.1.1\"},{\"default_features\":false,\"name\":\"pqcrypto-traits\",\"optional\":true,\"req\":\"^0.3.5\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.8.5\"},{\"name\":\"rand_core\",\"req\":\"^0.6\"},{\"default_features\":false,\"name\":\"sha2\",\"optional\":true,\"req\":\"^0.10.9\"},{\"default_features\":false,\"name\":\"thiserror-no-std\",\"req\":\"^2.0.2\"},{\"default_features\":false,\"features\":[\"static_secrets\",\"zeroize\"],\"name\":\"x25519-dalek\",\"optional\":true,\"req\":\"^2.0.1\"},{\"default_features\":false,\"features\":[\"zeroize_derive\"],\"name\":\"zeroize\",\"req\":\"^1.8.1\"}],\"features\":{\"alloc\":[],\"core\":[\"use-aes-gcm\",\"use-chacha20poly1305\",\"use-sha\",\"use-blake2\",\"use-25519\",\"use-rust-crypto-ml-kem\"],\"default\":[\"std\",\"use-aes-gcm\",\"use-chacha20poly1305\",\"use-sha\",\"use-blake2\",\"use-25519\",\"use-pqclean-ml-kem\",\"use-rust-crypto-ml-kem\"],\"getrandom\":[\"dep:getrandom\"],\"std\":[\"alloc\",\"sha2/std\",\"blake2/std\",\"aes-gcm/std\",\"chacha20poly1305/std\",\"ml-kem/std\",\"zeroize/std\",\"getrandom\"],\"use-25519\":[\"x25519-dalek\"],\"use-aes-gcm\":[\"aes-gcm\"],\"use-blake2\":[\"blake2\"],\"use-chacha20poly1305\":[\"chacha20poly1305\"],\"use-pqclean-ml-kem\":[\"pqcrypto-mlkem\",\"pqcrypto-traits\",\"getrandom\"],\"use-rust-crypto-ml-kem\":[\"ml-kem\"],\"use-sha\":[\"sha2\"]}}", - "clipboard-win_5.4.1": "{\"dependencies\":[{\"name\":\"error-code\",\"req\":\"^3\",\"target\":\"cfg(windows)\"},{\"name\":\"windows-win\",\"optional\":true,\"req\":\"^3\",\"target\":\"cfg(windows)\"}],\"features\":{\"monitor\":[\"windows-win\"],\"std\":[\"error-code/std\"]}}", + "clipboard-win_5.4.3": "{\"dependencies\":[{\"name\":\"error-code\",\"req\":\"^3\",\"target\":\"cfg(windows)\"},{\"name\":\"windows-win\",\"optional\":true,\"req\":\"^3\",\"target\":\"cfg(windows)\"}],\"features\":{\"monitor\":[\"windows-win\"],\"std\":[\"error-code/std\"]}}", "clru_0.6.3": "{\"dependencies\":[{\"name\":\"hashbrown\",\"req\":\"^0.16\"}],\"features\":{}}", "cmake_0.1.57": "{\"dependencies\":[{\"name\":\"cc\",\"req\":\"^1.2.46\"}],\"features\":{}}", "cmov_0.5.3": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1.9\",\"target\":\"cfg(any(unix, windows))\"}],\"features\":{}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 1c7ee1dbb2..8769637d16 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1853,9 +1853,9 @@ dependencies = [ [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] @@ -5377,6 +5377,7 @@ dependencies = [ "base64 0.22.1", "chrono", "clap", + "clipboard-win", "codex-ansi-escape", "codex-api", "codex-app-server-client", diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index a5269e7d60..6a86e3b9c9 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -158,6 +158,8 @@ objc2-foundation = { version = "0.3.2", default-features = false, features = ["s zbus = "4.4.0" [target.'cfg(windows)'.dependencies] +clipboard-win = "5.4.3" +image = { workspace = true, features = ["bmp"] } which = { workspace = true } windows-sys = { workspace = true, features = [ "Win32_Foundation", diff --git a/codex-rs/tui/src/clipboard_paste.rs b/codex-rs/tui/src/clipboard_paste.rs index f9e0134daa..426c5a8a62 100644 --- a/codex-rs/tui/src/clipboard_paste.rs +++ b/codex-rs/tui/src/clipboard_paste.rs @@ -3,6 +3,8 @@ #[cfg(target_os = "macos")] mod macos; pub(crate) mod text; +#[cfg(windows)] +mod windows; use std::path::Path; use std::path::PathBuf; @@ -125,6 +127,11 @@ fn read_clipboard_image( return Ok(image); } + #[cfg(windows)] + if let Some(result) = windows::clipboard_image() { + return result; + } + let _span = tracing::debug_span!("get_image").entered(); let bitmap = clipboard.get_image().map_err(|e| { // X11 owners such as xclip can answer a PNG request with a text type, diff --git a/codex-rs/tui/src/clipboard_paste/windows.rs b/codex-rs/tui/src/clipboard_paste/windows.rs new file mode 100644 index 0000000000..8284741e9b --- /dev/null +++ b/codex-rs/tui/src/clipboard_paste/windows.rs @@ -0,0 +1,93 @@ +//! Supply the pixel offset missing from packed Windows clipboard bitmaps. + +use super::PasteImageError; +use clipboard_win::formats::CF_DIBV5; +use image::DynamicImage; +use image::ImageFormat; +use image::ImageReader; +use std::io::Cursor; + +const BMP_HEADER: usize = 14; +const V5_HEADER: usize = 124; + +pub(super) fn clipboard_image() -> Option> { + let mut bmp = vec![0; BMP_HEADER]; + { + let _clipboard = clipboard_win::Clipboard::new_attempts(/*num*/ 5).ok()?; + // Keep arboard's preference for the registered PNG format. + if clipboard_win::register_format("PNG") + .is_some_and(|id| clipboard_win::is_format_avail(id.get())) + || !clipboard_win::is_format_avail(CF_DIBV5) + { + return None; + } + clipboard_win::raw::get_vec(CF_DIBV5, &mut bmp).ok()?; + } + decode_bitmap(bmp, image::Limits::default()) +} + +fn decode_bitmap( + mut bmp: Vec, + limits: image::Limits, +) -> Option> { + let dib = bmp.get(BMP_HEADER..)?; + let field = |offset: usize| { + Some(u32::from_le_bytes( + dib.get(offset..offset + 4)?.try_into().ok()?, + )) + }; + // Only handle 32-bit BI_BITFIELDS without a color table or embedded profile. + if field(0)? != V5_HEADER as u32 + || dib.get(14..16)? != 32u16.to_le_bytes() + || field(16)? != 3 // bV5Compression + || field(32)? != 0 // bV5ClrUsed + // bV5ProfileData and bV5ProfileSize + || field(112)? != 0 + || field(116)? != 0 + { + return None; + } + let width = field(4)? as usize; + let height = (field(8)? as i32).unsigned_abs() as usize; + let pixels = width.checked_mul(height)?.checked_mul(4)?; + let data = dib.get(V5_HEADER..)?; + let Some(spare) = data.len().checked_sub(pixels) else { + // arboard can allocate the declared pixel buffer before noticing a short read. + return Some(Err(PasteImageError::ImageReadFailed( + "incomplete bitmap pixel data".into(), + ))); + }; + + // image's headerless decoder skips three extra masks even when the pixels + // immediately follow the V5 header (arboard#234). Trailing allocation + // padding can hide the short read. If the first three pixels match the + // masks and there's enough padding, the layouts are indistinguishable. + // Prefer repeated masks to preserve compatibility with those producers. + let masks = &dib[40..52]; + let mut offset = BMP_HEADER + V5_HEADER; + if spare >= masks.len() && data.starts_with(masks) { + offset += masks.len(); + } + let Ok(size) = u32::try_from(bmp.len()) else { + return Some(Err(PasteImageError::ImageReadFailed( + "bitmap exceeds the BMP file size limit".into(), + ))); + }; + bmp[..2].copy_from_slice(b"BM"); + bmp[2..6].copy_from_slice(&size.to_le_bytes()); + bmp[10..14].copy_from_slice(&(offset as u32).to_le_bytes()); + let mut reader = ImageReader::with_format(Cursor::new(bmp), ImageFormat::Bmp); + reader.limits(limits); + match reader.decode() { + Ok(image) => Some(Ok(image)), + // Retrying through arboard would bypass the decoded allocation limit. + Err(err @ image::ImageError::Limits(_)) => { + Some(Err(PasteImageError::ImageReadFailed(err.to_string()))) + } + Err(_) => None, + } +} + +#[cfg(test)] +#[path = "windows_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/clipboard_paste/windows_tests.rs b/codex-rs/tui/src/clipboard_paste/windows_tests.rs new file mode 100644 index 0000000000..ff96db70eb --- /dev/null +++ b/codex-rs/tui/src/clipboard_paste/windows_tests.rs @@ -0,0 +1,47 @@ +#![cfg(test)] + +use super::*; +use pretty_assertions::assert_eq; + +#[test] +fn dibv5_preserves_pixels_and_respects_allocation_limits() { + let mut header = [0; BMP_HEADER + V5_HEADER]; + let dib = &mut header[BMP_HEADER..]; + for (offset, value) in [ + (0, 124u32), + (4, 1), // width + (8, 2), // bottom-up rows + (12, 1 | (32 << 16)), // planes and bit depth + (16, 3), // BI_BITFIELDS + (20, 8), // image size + (40, 0x00ff0000), + (44, 0x0000ff00), + (48, 0x000000ff), + (52, 0xff000000), + ] { + dib[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + } + let masks = dib[40..52].to_vec(); + assert!(matches!( + decode_bitmap(header.to_vec(), image::Limits::default()), + Some(Err(PasteImageError::ImageReadFailed(_))) + )); + let pixels = [3, 2, 1, 255, 6, 5, 4, 128]; + for data in [ + pixels.to_vec(), + [&pixels[..], &[0; 12]].concat(), + [&masks[..], &pixels].concat(), + ] { + let bmp = [&header[..], &data].concat(); + let mut limits = image::Limits::default(); + limits.max_alloc = Some(7); + assert!(matches!( + decode_bitmap(bmp.clone(), limits), + Some(Err(PasteImageError::ImageReadFailed(_))) + )); + let image = decode_bitmap(bmp, image::Limits::default()) + .unwrap() + .unwrap(); + assert_eq!(image.into_rgba8().into_raw(), [4, 5, 6, 128, 1, 2, 3, 255]); + } +}