A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
fix(gui): fall back from OpenGL to WebGpu as well
RoversXf09a70e8eb44
diff --git a/config/src/frontend.rs b/config/src/frontend.rsindex 73ab8ed3..7bd68d19 100644--- a/config/src/frontend.rs+++ b/config/src/frontend.rs@@ -6,8 +6,10 @@ pub enum FrontEndSelection {OpenGL,/// The default since the main window learned to fall back: wgpu asks for/// every backend it has (Metal, then DX12/Vulkan/GL depending on the- /// platform), and if none of them can be brought up the window quietly- /// opens on OpenGL instead of failing to open at all.+ /// platform; on Windows GL is left out where OpenGL would be Mesa), and+ /// if none of them can be brought up the window quietly opens on OpenGL+ /// instead of failing to open at all. OpenGL falls back to WebGpu the same+ /// way; Software never falls back.#[default]WebGpu,Software,diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex cc213f75..24edebc2 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -57,6 +57,7 @@ mod overlay;mod perf;mod plugins;mod quad;+mod renderer_choice;mod renderstate;mod resize_increment_calculator;mod scripting;diff --git a/wezterm-gui/src/renderer_choice.rs b/wezterm-gui/src/renderer_choice.rsnew file mode 100644index 00000000..fa5fbb5b--- /dev/null+++ b/wezterm-gui/src/renderer_choice.rs@@ -0,0 +1,208 @@+//! Which renderer a window comes up on. The selected backend goes first and,+//! unless the configuration asks for software rendering, the other one is+//! tried when it cannot start, so no selection can keep a window shut on a+//! machine where that backend fails. Each attempt covers the whole bring-up,+//! context and shaders both: an OpenGL old enough to create a context but not+//! to compile our shaders is as unusable as one that cannot create a context.+//!+//! A backend that failed once goes last for every later window of the+//! process, so a broken one is not paid for again on each window -- a failed+//! WGL attempt also leaves its probe window behind.++use crate::native_settings::NativeRendererBackend;+use std::cell::Cell;+use std::future::Future;+use std::pin::Pin;++thread_local! {+ // Windows are created on the GUI thread; one record per thread also keeps+ // the unit tests below from seeing each other's failures.+ static FAILED_WEBGPU: Cell<bool> = const { Cell::new(false) };+ static FAILED_OPENGL: Cell<bool> = const { Cell::new(false) };+}++fn failure_record(backend: NativeRendererBackend) -> &'static std::thread::LocalKey<Cell<bool>> {+ match backend {+ NativeRendererBackend::WebGpu => &FAILED_WEBGPU,+ NativeRendererBackend::OpenGL => &FAILED_OPENGL,+ }+}++fn label(backend: NativeRendererBackend) -> &'static str {+ match backend {+ NativeRendererBackend::WebGpu => "WebGPU",+ NativeRendererBackend::OpenGL => "OpenGL",+ }+}++type Attempt<'a, T> = Pin<Box<dyn Future<Output = anyhow::Result<T>> + 'a>>;++/// Neither future is polled unless its backend is tried.+pub(crate) async fn bring_up<'a, T>(+ selected: NativeRendererBackend,+ allow_fallback: bool,+ webgpu: impl Future<Output = anyhow::Result<T>> + 'a,+ opengl: impl Future<Output = anyhow::Result<T>> + 'a,+) -> anyhow::Result<T> {+ let webgpu: Attempt<'a, T> = Box::pin(webgpu);+ let opengl: Attempt<'a, T> = Box::pin(opengl);+ let mut attempts = match selected {+ NativeRendererBackend::WebGpu => vec![+ (NativeRendererBackend::WebGpu, webgpu),+ (NativeRendererBackend::OpenGL, opengl),+ ],+ NativeRendererBackend::OpenGL => vec![+ (NativeRendererBackend::OpenGL, opengl),+ (NativeRendererBackend::WebGpu, webgpu),+ ],+ };+ if !allow_fallback {+ attempts.truncate(1);+ }+ // A stable sort: one that has failed before moves behind one that has not.+ attempts.sort_by_key(|(backend, _)| failure_record(*backend).with(Cell::get));++ let mut causes = Vec::new();+ for (backend, attempt) in attempts {+ match attempt.await {+ Ok(renderer) => return Ok(renderer),+ Err(err) => {+ failure_record(backend).with(|failed| failed.set(true));+ log::error!("{} initialization failed: {err:#}", label(backend));+ causes.push(format!("{} initialization failed: {err:#}", label(backend)));+ }+ }+ }+ Err(anyhow::anyhow!(causes.join("; ")))+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::cell::RefCell;++ #[test]+ fn opengl_success_does_not_initialize_webgpu() {+ let result = smol::block_on(bring_up(+ NativeRendererBackend::OpenGL,+ true,+ async { panic!("WebGPU must not be polled") },+ async { Ok("OpenGL") },+ ));+ assert_eq!(result.unwrap(), "OpenGL");+ }++ #[test]+ fn webgpu_success_does_not_initialize_opengl() {+ let result = smol::block_on(bring_up(+ NativeRendererBackend::WebGpu,+ true,+ async { Ok("WebGPU") },+ async { panic!("OpenGL must not be polled") },+ ));+ assert_eq!(result.unwrap(), "WebGPU");+ }++ #[test]+ fn webgpu_failure_falls_back_to_opengl() {+ let attempts = RefCell::new(Vec::new());+ let result = smol::block_on(bring_up(+ NativeRendererBackend::WebGpu,+ true,+ async {+ attempts.borrow_mut().push("WebGPU");+ anyhow::bail!("adapter unavailable")+ },+ async {+ attempts.borrow_mut().push("OpenGL");+ Ok("OpenGL")+ },+ ));+ assert_eq!(result.unwrap(), "OpenGL");+ assert_eq!(*attempts.borrow(), vec!["WebGPU", "OpenGL"]);+ }++ #[test]+ fn opengl_failure_falls_back_to_webgpu() {+ let attempts = RefCell::new(Vec::new());+ let result = smol::block_on(bring_up(+ NativeRendererBackend::OpenGL,+ true,+ async {+ attempts.borrow_mut().push("WebGPU");+ Ok("WebGPU")+ },+ async {+ attempts.borrow_mut().push("OpenGL");+ anyhow::bail!("the OpenGL implementation is too old")+ },+ ));+ assert_eq!(result.unwrap(), "WebGPU");+ assert_eq!(*attempts.borrow(), vec!["OpenGL", "WebGPU"]);+ }++ #[test]+ fn both_renderer_failures_keep_both_causes() {+ let error = smol::block_on(bring_up::<()>(+ NativeRendererBackend::WebGpu,+ true,+ async { Err(anyhow::anyhow!("adapter unavailable").context("device creation")) },+ async { Err(anyhow::anyhow!("shader compilation failed")) },+ ))+ .unwrap_err();+ let message = format!("{error:#}");+ assert!(message+ .contains("WebGPU initialization failed: device creation: adapter unavailable"));+ assert!(message.contains("OpenGL initialization failed: shader compilation failed"));+ }++ #[test]+ fn explicit_opengl_failure_keeps_both_causes() {+ let error = smol::block_on(bring_up::<()>(+ NativeRendererBackend::OpenGL,+ true,+ async { anyhow::bail!("adapter unavailable") },+ async { anyhow::bail!("context creation failed") },+ ))+ .unwrap_err();+ assert_eq!(+ format!("{error:#}"),+ "OpenGL initialization failed: context creation failed; \+ WebGPU initialization failed: adapter unavailable"+ );+ }++ #[test]+ fn software_rendering_never_falls_back_to_webgpu() {+ let error = smol::block_on(bring_up::<()>(+ NativeRendererBackend::OpenGL,+ false,+ async { panic!("WebGPU must not be polled") },+ async { anyhow::bail!("context creation failed") },+ ))+ .unwrap_err();+ assert_eq!(+ format!("{error:#}"),+ "OpenGL initialization failed: context creation failed"+ );+ }++ #[test]+ fn a_backend_that_failed_goes_last_for_later_windows() {+ let first = smol::block_on(bring_up(+ NativeRendererBackend::OpenGL,+ true,+ async { Ok("WebGPU") },+ async { anyhow::bail!("the OpenGL implementation is too old") },+ ));+ assert_eq!(first.unwrap(), "WebGPU");++ let second = smol::block_on(bring_up(+ NativeRendererBackend::OpenGL,+ true,+ async { Ok("WebGPU") },+ async { panic!("OpenGL failed before and must not go first") },+ ));+ assert_eq!(second.unwrap(), "WebGPU");+ }+}diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex c68b0745..a33d9140 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -2772,99 +2772,6 @@ pub fn show() {}}-async fn create_settings_renderer<T>(- requested: NativeRendererBackend,- webgpu: impl std::future::Future<Output = anyhow::Result<T>>,- opengl: impl std::future::Future<Output = anyhow::Result<T>>,-) -> anyhow::Result<T> {- if requested == NativeRendererBackend::OpenGL {- return opengl.await.context("OpenGL initialization failed");- }- match webgpu.await {- Ok(renderer) => Ok(renderer),- Err(webgpu_error) => {- log::warn!("settings WebGPU initialization failed: {webgpu_error:#}; trying OpenGL");- opengl.await.map_err(|opengl_error| {- anyhow::anyhow!(- "WebGPU initialization failed: {webgpu_error:#}; \- OpenGL initialization failed: {opengl_error:#}"- )- })- }- }-}--#[cfg(test)]-mod renderer_tests {- use super::*;-- #[test]- fn opengl_selection_never_initializes_webgpu() {- let result = smol::block_on(create_settings_renderer(- NativeRendererBackend::OpenGL,- async { panic!("WebGPU must not be polled") },- async { Ok("OpenGL") },- ));- assert_eq!(result.unwrap(), "OpenGL");- }-- #[test]- fn webgpu_success_does_not_initialize_opengl() {- let result = smol::block_on(create_settings_renderer(- NativeRendererBackend::WebGpu,- async { Ok("WebGPU") },- async { panic!("OpenGL must not be polled") },- ));- assert_eq!(result.unwrap(), "WebGPU");- }-- #[test]- fn webgpu_failure_falls_back_to_opengl() {- let attempts = RefCell::new(Vec::new());- let result = smol::block_on(create_settings_renderer(- NativeRendererBackend::WebGpu,- async {- attempts.borrow_mut().push("WebGPU");- anyhow::bail!("adapter unavailable")- },- async {- attempts.borrow_mut().push("OpenGL");- Ok("OpenGL")- },- ));- assert_eq!(result.unwrap(), "OpenGL");- assert_eq!(*attempts.borrow(), vec!["WebGPU", "OpenGL"]);- }-- #[test]- fn both_renderer_failures_keep_both_causes() {- let error = smol::block_on(create_settings_renderer::<()>(- NativeRendererBackend::WebGpu,- async { Err(anyhow::anyhow!("adapter unavailable").context("device creation")) },- async { Err(anyhow::anyhow!("shader compilation failed")) },- ))- .unwrap_err();- let message = format!("{error:#}");- assert!(message- .contains("WebGPU initialization failed: device creation: adapter unavailable"));- assert!(message.contains("OpenGL initialization failed: shader compilation failed"));- }-- #[test]- fn explicit_opengl_failure_reports_the_backend() {- let error = smol::block_on(create_settings_renderer::<()>(- NativeRendererBackend::OpenGL,- async { panic!("WebGPU must not be polled") },- async { anyhow::bail!("context creation failed") },- ))- .unwrap_err();- assert_eq!(- format!("{error:#}"),- "OpenGL initialization failed: context creation failed"- );- }-}-/// One string, shaped and glyph-resolved once for one font.////// `width` is the same sum the painter walks, so a measurement and the paint@@ -3123,8 +3030,9 @@ impl SettingsWindow {.await?;window.set_title(&title);- let render_state = create_settings_renderer(+ let render_state = crate::renderer_choice::bring_up(active_main_renderer,+ config.front_end != config::FrontEndSelection::Software,async {let webgpu = Rc::new(WebGpuState::new(&window, dimensions, &config).await?);let settings = settings.borrow();diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 3d1993f5..25437407 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -3989,31 +3989,15 @@ impl TermWindow {}}- fn created(&mut self, ctx: RenderContext) -> anyhow::Result<()> {- self.render_state = None;-- let render_info = ctx.renderer_info();- self.opengl_info.replace(render_info.clone());-- match RenderState::new(ctx, &self.fonts, &self.render_metrics, ATLAS_SIZE) {- Ok(render_state) => {- log::debug!(- "OpenGL initialized! {} wezterm version: {}",- render_info,- config::wezterm_version(),- );- self.render_state.replace(render_state);- }- Err(err) => {- log::error!("failed to create RenderState: {}", err);- }- }-- if self.render_state.is_none() {- panic!("No OpenGL");- }-- Ok(())+ fn created(&mut self, render_state: RenderState) {+ let render_info = render_state.context.renderer_info();+ log::debug!(+ "OpenGL initialized! {} wezterm version: {}",+ render_info,+ config::wezterm_version(),+ );+ self.opengl_info.replace(render_info);+ self.render_state.replace(render_state);}}@@ -4684,43 +4668,45 @@ impl TermWindow {}});- // Try WebGpu first when it is the selection, but never let its failure- // be fatal: a machine with no usable Vulkan/DX12/Metal adapter would- // otherwise get a window that never opens *and* no way back, because- // the settings window is built the same way and would fail with it.- // Falling back costs a log line; not falling back costs the app.- let mut effective_renderer = main_renderer;- let mut webgpu = None;- if matches!(+ // The selected renderer goes first and, unless the configuration asks+ // for software rendering, the other one is the fallback: a machine with+ // no usable Vulkan/DX12/Metal adapter, or with an OpenGL too old for+ // our shaders, would otherwise get a window that never opens *and* no+ // way back, because the settings window is built the same way. Each+ // attempt runs through RenderState, where the shaders are compiled.+ let render_state = crate::renderer_choice::bring_up(main_renderer,- crate::native_settings::NativeRendererBackend::WebGpu- ) {- gpu_debug(format!(- "create WebGpu main_window size={}x{} dpi={}",- dimensions.pixel_width, dimensions.pixel_height, dimensions.dpi- ));- match WebGpuState::new(&window, dimensions, &config).await {- Ok(state) => webgpu = Some(Rc::new(state)),- Err(err) => {- log::error!("WebGpu is unavailable ({err:#}); falling back to OpenGL");- gpu_debug(format!(- "WebGpu unavailable: {err:#}; falling back to OpenGL"- ));- effective_renderer = crate::native_settings::NativeRendererBackend::OpenGL;- }- }- }-- let gl = match effective_renderer {- crate::native_settings::NativeRendererBackend::WebGpu => None,- crate::native_settings::NativeRendererBackend::OpenGL => {+ config.front_end != config::FrontEndSelection::Software,+ async {+ gpu_debug(format!(+ "create WebGpu main_window size={}x{} dpi={}",+ dimensions.pixel_width, dimensions.pixel_height, dimensions.dpi+ ));+ let webgpu = Rc::new(WebGpuState::new(&window, dimensions, &config).await?);+ let myself = tw.borrow();+ RenderState::new(+ RenderContext::WebGpu(webgpu),+ &myself.fonts,+ &myself.render_metrics,+ ATLAS_SIZE,+ )+ },+ async {gpu_debug(format!("enable OpenGL main_window size={}x{} dpi={}",dimensions.pixel_width, dimensions.pixel_height, dimensions.dpi));- Some(window.enable_opengl().await?)- }- };+ let gl = window.enable_opengl().await?;+ let myself = tw.borrow();+ RenderState::new(+ RenderContext::Glium(gl),+ &myself.fonts,+ &myself.render_metrics,+ ATLAS_SIZE,+ )+ },+ )+ .await?;{let mut myself = tw.borrow_mut();@@ -4741,19 +4727,25 @@ impl TermWindow {);}- if let Some(gl) = gl {- myself.gl.replace(Rc::clone(&gl));- myself.created(RenderContext::Glium(Rc::clone(&gl)))?;- }- if let Some(webgpu) = webgpu {- myself.webgpu.replace(Rc::clone(&webgpu));- // Seed the swapchain latency from the current focus: a- // window spawned in the background starts at the reduced- // latency and only pays for the third drawable once it is- // actually focused.- webgpu.set_desired_frame_latency(if myself.focused.is_some() { 2 } else { 1 });- myself.created(RenderContext::WebGpu(Rc::clone(&webgpu)))?;+ match &render_state.context {+ RenderContext::Glium(gl) => {+ myself.gl.replace(Rc::clone(gl));+ }+ RenderContext::WebGpu(webgpu) => {+ myself.webgpu.replace(Rc::clone(webgpu));+ // A resize or DPI change can arrive while the renderer is+ // coming up -- for longer when a failed OpenGL attempt went+ // first -- and the surface was configured from dimensions+ // taken before the window existed.+ webgpu.resize(myself.dimensions);+ // Seed the swapchain latency from the current focus: a+ // window spawned in the background starts at the reduced+ // latency and only pays for the third drawable once it is+ // actually focused.+ webgpu.set_desired_frame_latency(if myself.focused.is_some() { 2 } else { 1 });+ }}+ myself.created(render_state);myself.apply_native_terminal_settings();myself.apply_workspace_thread_font_scales();myself.load_os_parameters();