Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix Windows GPUI export and decoder shutdown
Richie McIlroy98abbcfab999
diff --git a/apps/desktop-gpui/build.rs b/apps/desktop-gpui/build.rsindex 4faa84b72..ab7033cbe 100644--- a/apps/desktop-gpui/build.rs+++ b/apps/desktop-gpui/build.rs@@ -7,6 +7,11 @@ fn main() {return;}+ if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") {+ // Export dispatch constructs media futures on the UI thread before Tokio can poll them.+ println!("cargo:rustc-link-arg-bin=cap-gpui=/STACK:16777216");+ }+let icon = "../desktop/src-tauri/icons/icon.ico";println!("cargo:rerun-if-changed={icon}");tauri_winres::WindowsResource::new()diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rsindex 021641a05..5b3b44f97 100644--- a/apps/desktop-gpui/src/editor_export.rs+++ b/apps/desktop-gpui/src/editor_export.rs@@ -1366,6 +1366,8 @@ impl EditorWindow {div().flex_1().flex().flex_row().items_center().child(div().id("export-back")+ .when(cfg!(target_os = "windows"), |button| button.occlude())+ .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation()).flex().flex_row().items_center()diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rsindex 0ca6d76de..aa22b4191 100644--- a/apps/desktop-gpui/src/main.rs+++ b/apps/desktop-gpui/src/main.rs@@ -219,6 +219,16 @@ fn create_log_appender(}}+#[cfg(target_os = "windows")]+fn windows_runtime() -> tokio::runtime::Runtime {+ tokio::runtime::Builder::new_multi_thread()+ .worker_threads(2)+ .thread_stack_size(16 * 1024 * 1024)+ .enable_all()+ .build()+ .expect("Failed to initialize Tokio")+}+fn main() {#[cfg(target_os = "linux")]if let Some(threads) = cap_utils::linux_runtime::llvmpipe_thread_count() {@@ -259,7 +269,15 @@ fn main() {crate::deeplink::submit_deep_link(&url);}});- app.run(|cx: &mut App| {+ #[cfg(target_os = "windows")]+ let runtime = windows_runtime();+ #[cfg(target_os = "windows")]+ let runtime_handle = runtime.handle().clone();++ app.run(move |cx: &mut App| {+ #[cfg(target_os = "windows")]+ gpui_tokio::init_from_handle(cx, runtime_handle);+ #[cfg(not(target_os = "windows"))]gpui_tokio::init(cx);gpui_tokio::Tokio::spawn(cx, cap_utils::operation_diagnostics::run_checkpoints()).detach();// The dock icon: an unbundled dev binary shows the generic terminal@@ -335,7 +353,7 @@ fn main() {gpui::WindowBackgroundAppearance::Transparent},is_resizable: false,- is_minimizable: false,+ is_minimizable: cfg!(target_os = "windows"),..Default::default()},{@@ -682,6 +700,39 @@ fn main() {cx.activate(true);}});+ #[cfg(target_os = "windows")]+ runtime.shutdown_background();+}++#[cfg(all(test, target_os = "windows"))]+mod runtime_tests {+ fn current_stack_size() -> usize {+ let (mut low, mut high) = (0, 0);+ unsafe {+ windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits(&mut low, &mut high);+ }+ high.saturating_sub(low)+ }++ #[test]+ fn media_workers_and_blocking_tasks_have_large_windows_stacks() {+ let runtime = super::windows_runtime();+ runtime.block_on(async {+ let worker_size = tokio::spawn(async { current_stack_size() }).await.unwrap();+ let blocking_size = tokio::task::spawn_blocking(current_stack_size)+ .await+ .unwrap();+ assert!(+ worker_size >= 16 * 1024 * 1024,+ "worker stack: {worker_size}"+ );+ assert!(+ blocking_size >= 16 * 1024 * 1024,+ "blocking stack: {blocking_size}"+ );+ });+ runtime.shutdown_background();+ }}#[cfg(test)]diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rsindex b816b7f2e..c86f8bac2 100644--- a/apps/desktop-gpui/src/main_window.rs+++ b/apps/desktop-gpui/src/main_window.rs@@ -782,6 +782,10 @@ impl MainWindow {) -> Self {crate::theme::bind_window(window, cx);window.on_window_should_close(cx, |_, cx| {+ // The custom Windows X minimizes; native close requests must still quit.+ #[cfg(target_os = "windows")]+ cx.defer(crate::menus::quit);+ #[cfg(not(target_os = "windows"))]cx.defer(app_windows::request_close_main);false});@@ -2885,11 +2889,8 @@ impl MainWindow {.on_click(|_, window, _| window.minimize_window()),).child(- button("caption-close", "icons/caption-close-windows.svg", 10.).on_click(- cx.listener(|_, _, _, cx| {- cx.defer(app_windows::request_close_main);- }),- ),+ button("caption-close", "icons/caption-close-windows.svg", 10.)+ .on_click(|_, window, _| window.minimize_window()),)}diff --git a/crates/video-decode/src/media_foundation.rs b/crates/video-decode/src/media_foundation.rsindex 9e41c2d2a..45b6cf5a3 100644--- a/crates/video-decode/src/media_foundation.rs+++ b/crates/video-decode/src/media_foundation.rs@@ -551,14 +551,20 @@ pub struct MediaFoundationDecoder {frame_pool: FramePool,plane_converter: Nv12PlaneConverter,capabilities: MFDecoderCapabilities,+ // COM can unload the decoder DLL, so release every COM field before its apartment shuts down.+ _init_guard: MFInitGuard,}-struct MFInitGuard;+struct MFInitGuard {+ media_foundation_started: bool,+}impl Drop for MFInitGuard {fn drop(&mut self) {unsafe {- let _ = MFShutdown();+ if self.media_foundation_started {+ let _ = MFShutdown();+ }CoUninitialize();}}@@ -574,12 +580,15 @@ impl MediaFoundationDecoder {CoInitializeEx(None, COINIT_MULTITHREADED).ok().map_err(|e| format!("Failed to initialize COM: {e:?}"))?;-+ }+ let mut guard = MFInitGuard {+ media_foundation_started: false,+ };+ unsafe {MFStartup(MF_API_VERSION, MFSTARTUP_NOSOCKET).map_err(|e| format!("Failed to start Media Foundation: {e:?}"))?;}-- let guard = MFInitGuard;+ guard.media_foundation_started = true;let (d3d11_device, d3d11_context) = unsafe { create_d3d11_device()? };let device_manager = unsafe { create_dxgi_device_manager(&d3d11_device)? };@@ -615,8 +624,6 @@ impl MediaFoundationDecoder {"MediaFoundation decoder initialized");- std::mem::forget(guard);-Ok(Self {source_reader,d3d11_device,@@ -632,6 +639,7 @@ impl MediaFoundationDecoder {frame_pool: FramePool::new(),plane_converter,capabilities,+ _init_guard: guard,})}@@ -868,15 +876,6 @@ impl MediaFoundationDecoder {}}-impl Drop for MediaFoundationDecoder {- fn drop(&mut self) {- unsafe {- let _ = MFShutdown();- CoUninitialize();- }- }-}-unsafe fn create_d3d11_device() -> Result<(ID3D11Device, ID3D11DeviceContext), String> {use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_UNKNOWN;@@ -1119,6 +1118,20 @@ unsafe impl Send for MediaFoundationDecoder {}mod tests {use super::*;+ #[test]+ #[ignore = "requires a Windows D3D11 device"]+ fn repeatedly_releases_decoder_objects_before_com_shutdown() {+ let path =+ Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/h264-decoder-lifecycle.mp4");+ for _ in 0..20 {+ let mut decoder = MediaFoundationDecoder::new(&path).unwrap();+ for _ in 0..5 {+ assert!(decoder.read_sample().unwrap().is_some());+ }+ drop(decoder);+ }+ }+fn normalized(path: &str) -> String {let encoded = media_foundation_path(Path::new(path));assert_eq!(encoded.last(), Some(&0));diff --git a/crates/video-decode/tests/fixtures/h264-decoder-lifecycle.mp4 b/crates/video-decode/tests/fixtures/h264-decoder-lifecycle.mp4new file mode 100644index 000000000..021294112Binary files /dev/null and b/crates/video-decode/tests/fixtures/h264-decoder-lifecycle.mp4 differdiff --git a/scripts/build-gpui-binary.sh b/scripts/build-gpui-binary.shindex 2db415334..8c696a764 100755--- a/scripts/build-gpui-binary.sh+++ b/scripts/build-gpui-binary.sh@@ -67,6 +67,10 @@ if [[ ! -f "$source_binary" ]]; thenexit 1fi+if [[ "$target" == *windows-msvc ]]; then+ node "$repo_root/scripts/verify-windows-stack.mjs" "$source_binary"+fi+if [[ "$target" == *linux* ]]; thenpatchelf --set-rpath '$ORIGIN:$ORIGIN/../lib/cap' "$source_binary"fidiff --git a/scripts/verify-windows-stack.mjs b/scripts/verify-windows-stack.mjsnew file mode 100644index 000000000..0b1d654cb--- /dev/null+++ b/scripts/verify-windows-stack.mjs@@ -0,0 +1,30 @@+import { readFileSync } from "node:fs";++const filePath = process.argv[2];+if (!filePath) {+ throw new Error("Usage: node scripts/verify-windows-stack.mjs <executable>");+}++const binary = readFileSync(filePath);+if (binary.toString("ascii", 0, 2) !== "MZ") {+ throw new Error(`${filePath} is not a Windows executable`);+}+const peOffset = binary.readUInt32LE(0x3c);+if (binary.readUInt32LE(peOffset) !== 0x4550) {+ throw new Error(`${filePath} has an invalid PE signature`);+}+const optionalHeader = peOffset + 24;+const magic = binary.readUInt16LE(optionalHeader);+if (magic !== 0x20b && magic !== 0x10b) {+ throw new Error(`${filePath} has an unsupported PE optional header`);+}+const stackReserve =+ magic === 0x20b+ ? binary.readBigUInt64LE(optionalHeader + 72)+ : BigInt(binary.readUInt32LE(optionalHeader + 72));+if (stackReserve < 16n * 1024n * 1024n) {+ throw new Error(+ `${filePath} reserves only ${stackReserve} bytes for its Windows UI stack; media dispatch requires at least 16 MiB`,+ );+}+console.log(`Verified Windows UI stack reserve: ${stackReserve} bytes`);