Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Draw on the GPU that drives the screen on Linux, so laptops with two GPUs open fast and don't lag (#659)

BFlatf05f0196911a
diff --git a/apps/craft-anything/src/linux_gpu.rs b/apps/craft-anything/src/linux_gpu.rs
new file mode 100644
index 00000000..4dbf29bd
--- /dev/null
+++ b/apps/craft-anything/src/linux_gpu.rs
@@ -0,0 +1,254 @@
+//! Linux: draw on the GPU that drives the screen (#571).
+//!
+//! egui-wgpu picks the discrete GPU by default. On a laptop whose integrated GPU drives the panel,
+//! every frame drawn on the discrete one is copied across to it: the window took 20 s to open and
+//! the whole desktop lagged while it was open. Forcing the integrated GPU instead breaks desktops
+//! whose screen is on the discrete card, and a desktop with a monitor on each card needs the
+//! discrete one. So the choice follows the connected displays:
+//!
+//! 1. `WGPU_ADAPTER_NAME` (part of the adapter's name) or `WGPU_POWER_PREF` (`high`, `low`,
+//! `none`), when set, decide;
+//! 2. a connected built-in panel: the GPU behind it;
+//! 3. displays on only one GPU: that GPU;
+//! 4. otherwise (displays on several GPUs, or nothing readable): the discrete GPU, as before.
+
+use craft_anything_platform::display::DisplayCard;
+use eframe::wgpu::{DeviceType, PowerPreference};
+
+/// What we know of one adapter wgpu offers.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct Candidate {
+ pub name: String,
+ pub vendor: u32,
+ pub device: u32,
+ /// `0000:05:00.0`, lowercase; empty when the driver doesn't say (always, under GL).
+ pub pci_slot: String,
+ pub device_type: DeviceType,
+ pub gl: bool,
+}
+
+/// What the person asked for through wgpu's environment variables.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub(crate) struct Asked {
+ pub adapter_name: Option<String>,
+ pub power: Option<PowerPreference>,
+}
+
+/// Why an adapter was chosen, for the log.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Why {
+ AskedByName,
+ AskedPower,
+ BuiltInPanel,
+ OnlyGpuWithDisplays,
+ Fallback,
+}
+
+/// The index of the adapter to draw with, and why; `None` when there is none.
+pub(crate) fn choose(candidates: &[Candidate], cards: &[DisplayCard], asked: &Asked) -> Option<(usize, Why)> {
+ if let Some(want) = asked.adapter_name.as_deref().map(str::to_lowercase).filter(|w| !w.is_empty()) {
+ // As wgpu's own `WGPU_ADAPTER_NAME`: part of the name, any case. No match: the usual choice.
+ if let Some(i) = candidates.iter().position(|c| c.name.to_lowercase().contains(&want)) {
+ return Some((i, Why::AskedByName));
+ }
+ log::warn!("WGPU_ADAPTER_NAME={want}: no graphics adapter has that in its name");
+ }
+ if let Some(power) = asked.power {
+ return by_kind(candidates, power).map(|i| (i, Why::AskedPower));
+ }
+ let panels: Vec<&DisplayCard> = cards.iter().filter(|c| c.built_in_panel).collect();
+ let with_displays: Vec<&DisplayCard> = cards.iter().filter(|c| c.displays > 0).collect();
+ let target = if !panels.is_empty() {
+ Some((panels, Why::BuiltInPanel))
+ } else if with_displays.len() == 1 {
+ Some((with_displays, Why::OnlyGpuWithDisplays))
+ } else {
+ None
+ };
+ if let Some((wanted, why)) = target {
+ // Vulkan before GL for the same card; otherwise wgpu's order.
+ let found = candidates.iter().enumerate().filter(|(_, c)| wanted.iter().any(|card| drives(card, c, cards))).min_by_key(|(_, c)| c.gl);
+ if let Some((i, _)) = found {
+ return Some((i, why));
+ }
+ }
+ by_kind(candidates, PowerPreference::HighPerformance).map(|i| (i, Why::Fallback))
+}
+
+/// Whether `card` is the GPU behind `adapter`: by PCI address when the driver gives one, else by
+/// PCI ids; GL gives only a vendor, which counts only when no other card has that vendor.
+fn drives(card: &DisplayCard, adapter: &Candidate, all: &[DisplayCard]) -> bool {
+ if !adapter.pci_slot.is_empty() && !card.pci_slot.is_empty() {
+ return adapter.pci_slot == card.pci_slot;
+ }
+ if adapter.device != 0 {
+ return adapter.vendor == card.vendor && adapter.device == card.device;
+ }
+ adapter.vendor != 0 && adapter.vendor == card.vendor && all.iter().filter(|c| c.vendor == card.vendor).count() == 1
+}
+
+/// The first adapter in wgpu's own order for that power preference.
+fn by_kind(candidates: &[Candidate], power: PowerPreference) -> Option<usize> {
+ let rank = |t: DeviceType| match (power, t) {
+ (PowerPreference::None, _) => 0,
+ (PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 1,
+ (_, DeviceType::IntegratedGpu | DeviceType::DiscreteGpu) => 2,
+ (_, DeviceType::Other) => 3,
+ (_, DeviceType::VirtualGpu) => 4,
+ (_, DeviceType::Cpu) => 5,
+ };
+ candidates.iter().enumerate().min_by_key(|(_, c)| rank(c.device_type)).map(|(i, _)| i)
+}
+
+#[cfg(target_os = "linux")]
+impl Candidate {
+ fn of(info: &eframe::wgpu::AdapterInfo) -> Self {
+ Candidate {
+ name: info.name.clone(),
+ vendor: info.vendor,
+ device: info.device,
+ pci_slot: info.device_pci_bus_id.to_ascii_lowercase(),
+ device_type: info.device_type,
+ gl: info.backend == eframe::wgpu::Backend::Gl,
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+impl Asked {
+ fn from_env() -> Self {
+ Asked { adapter_name: std::env::var("WGPU_ADAPTER_NAME").ok(), power: PowerPreference::from_env() }
+ }
+}
+
+/// The adapter that draws the window, among those that can draw to it.
+#[cfg(target_os = "linux")]
+pub(crate) fn pick_adapter(adapters: &[eframe::wgpu::Adapter], surface: Option<&eframe::wgpu::Surface<'_>>) -> Result<eframe::wgpu::Adapter, String> {
+ let usable: Vec<&eframe::wgpu::Adapter> = adapters.iter().filter(|a| surface.is_none_or(|s| a.is_surface_supported(s))).collect();
+ let candidates: Vec<Candidate> = usable.iter().map(|a| Candidate::of(&a.get_info())).collect();
+ let cards = craft_anything_platform::display::display_cards();
+ let picked = choose(&candidates, &cards, &Asked::from_env()).and_then(|(i, why)| Some((*usable.get(i)?, why)));
+ match picked {
+ Some((a, why)) => {
+ log::info!("drawing with {:?} ({why:?}); displays: {cards:?}", a.get_info());
+ Ok(a.clone())
+ }
+ None => Err(format!("None of the {} graphics adapters found can draw this window.", adapters.len())),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const AMD: (u32, u32, &str) = (0x1002, 0x1638, "0000:05:00.0");
+ const NVIDIA: (u32, u32, &str) = (0x10de, 0x25a2, "0000:01:00.0");
+ const INTEL: (u32, u32, &str) = (0x8086, 0xa780, "0000:00:02.0");
+
+ fn vulkan(name: &str, (vendor, device, slot): (u32, u32, &str), device_type: DeviceType) -> Candidate {
+ Candidate { name: name.into(), vendor, device, pci_slot: slot.into(), device_type, gl: false }
+ }
+
+ fn gl(name: &str, vendor: u32, device_type: DeviceType) -> Candidate {
+ Candidate { name: name.into(), vendor, device: 0, pci_slot: String::new(), device_type, gl: true }
+ }
+
+ fn card((vendor, device, slot): (u32, u32, &str), displays: u32, built_in_panel: bool) -> DisplayCard {
+ DisplayCard { vendor, device, pci_slot: slot.into(), displays, built_in_panel }
+ }
+
+ /// What wgpu offered on #571's laptop, in its order (Vulkan, then GL).
+ fn laptop_adapters() -> Vec<Candidate> {
+ vec![
+ vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu),
+ vulkan("NVIDIA GeForce RTX 3050 Laptop GPU", NVIDIA, DeviceType::DiscreteGpu),
+ gl("AMD Radeon Graphics (radeonsi, renoir)", 0x1002, DeviceType::IntegratedGpu),
+ ]
+ }
+
+ /// #571: the AMD iGPU drives the panel; the default drew on NVIDIA (20 s to open, lag).
+ #[test]
+ fn a_laptop_draws_on_the_gpu_behind_its_panel() {
+ let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
+ assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel)));
+ // The same with the discrete GPU listed first.
+ let mut swapped = laptop_adapters();
+ swapped.swap(0, 1);
+ assert_eq!(choose(&swapped, &cards, &Asked::default()), Some((1, Why::BuiltInPanel)));
+ }
+
+ /// The panel's GPU stays the choice with an external monitor on the discrete card as well.
+ #[test]
+ fn the_panel_wins_over_a_monitor_on_the_other_card() {
+ let cards = [card(NVIDIA, 1, false), card(AMD, 1, true)];
+ assert_eq!(choose(&laptop_adapters(), &cards, &Asked::default()), Some((0, Why::BuiltInPanel)));
+ }
+
+ /// A desktop with its monitor on the discrete card and the iGPU left on (a low-power default
+ /// draws on the iGPU there, and the window can't start: the case the panel rule must not break).
+ #[test]
+ fn a_desktop_draws_on_the_only_card_with_a_monitor() {
+ let adapters = [vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)];
+ let cards = [card(INTEL, 0, false), card(NVIDIA, 1, false)];
+ assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::OnlyGpuWithDisplays)));
+ // And on the iGPU when that's where the only monitor is.
+ let cards = [card(INTEL, 2, false), card(NVIDIA, 0, false)];
+ assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((0, Why::OnlyGpuWithDisplays)));
+ }
+
+ /// A desktop with a monitor on each card: the discrete GPU, as before (an iGPU choice there
+ /// lost its surface as soon as it was set up).
+ #[test]
+ fn monitors_on_two_cards_keep_the_discrete_gpu() {
+ let adapters = [vulkan("Intel(R) Graphics (RPL-S)", INTEL, DeviceType::IntegratedGpu), vulkan("NVIDIA GeForce RTX", NVIDIA, DeviceType::DiscreteGpu)];
+ let cards = [card(INTEL, 1, false), card(NVIDIA, 1, false)];
+ assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::Fallback)));
+ }
+
+ /// Nothing readable (no `/sys`, or a card the drivers don't name): the discrete GPU, as before.
+ #[test]
+ fn without_display_facts_the_old_choice_stands() {
+ assert_eq!(choose(&laptop_adapters(), &[], &Asked::default()), Some((1, Why::Fallback)));
+ let unknown = [card((0x1234, 0x1, "0000:09:00.0"), 1, true)];
+ assert_eq!(choose(&laptop_adapters(), &unknown, &Asked::default()), Some((1, Why::Fallback)));
+ assert_eq!(choose(&[], &[card(AMD, 1, true)], &Asked::default()), None);
+ }
+
+ /// The environment variables still decide: prime-run style requests reach the NVIDIA card.
+ #[test]
+ fn wgpu_environment_variables_decide_when_set() {
+ let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
+ let asked = |name: Option<&str>, power: Option<PowerPreference>| Asked { adapter_name: name.map(Into::into), power };
+ assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::HighPerformance))), Some((1, Why::AskedPower)));
+ assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::LowPower))), Some((0, Why::AskedPower)));
+ assert_eq!(choose(&laptop_adapters(), &cards, &asked(None, Some(PowerPreference::None))), Some((0, Why::AskedPower)));
+ assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("nvidia"), None)), Some((1, Why::AskedByName)));
+ assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("RadeonSI"), Some(PowerPreference::HighPerformance))), Some((2, Why::AskedByName)));
+ // A name nothing has: the usual choice, not a failure.
+ assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some("matrox"), None)), Some((0, Why::BuiltInPanel)));
+ assert_eq!(choose(&laptop_adapters(), &cards, &asked(Some(""), None)), Some((0, Why::BuiltInPanel)));
+ }
+
+ /// Under `WGPU_BACKEND=gl` there's no PCI address or device id: the vendor alone finds the
+ /// card, but only when no other card shares it.
+ #[test]
+ fn gl_adapters_are_matched_by_vendor_only_when_unambiguous() {
+ let adapters = [gl("NVIDIA GeForce RTX 3050", 0x10de, DeviceType::Other), gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu)];
+ let cards = [card(NVIDIA, 0, false), card(AMD, 1, true)];
+ assert_eq!(choose(&adapters, &cards, &Asked::default()), Some((1, Why::BuiltInPanel)));
+ // Two AMD cards: the vendor can't tell them apart, so the old choice stands.
+ let two_amd = [card((0x1002, 0x73df, "0000:03:00.0"), 0, false), card(AMD, 1, true)];
+ let adapters = [gl("AMD Radeon RX 6700", 0x1002, DeviceType::Other), gl("AMD Radeon Graphics", 0x1002, DeviceType::IntegratedGpu)];
+ assert_eq!(choose(&adapters, &two_amd, &Asked::default()), Some((1, Why::Fallback)));
+ }
+
+ /// Two adapters for the panel's card (Vulkan and GL): Vulkan, whatever the order.
+ #[test]
+ fn vulkan_comes_before_gl_for_the_same_card() {
+ let adapters = [
+ gl("AMD Radeon Graphics (radeonsi)", 0x1002, DeviceType::IntegratedGpu),
+ vulkan("AMD Radeon Graphics (RADV RENOIR)", AMD, DeviceType::IntegratedGpu),
+ ];
+ assert_eq!(choose(&adapters, &[card(AMD, 1, true)], &Asked::default()), Some((1, Why::BuiltInPanel)));
+ }
+}
diff --git a/apps/craft-anything/src/main.rs b/apps/craft-anything/src/main.rs
index 8c10131e..62be2cdf 100644
--- a/apps/craft-anything/src/main.rs
+++ b/apps/craft-anything/src/main.rs
@@ -15,6 +15,9 @@ mod start_guard;
#[cfg(windows)]
static RETRY_IN_SOFTWARE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+#[cfg(any(target_os = "linux", test))]
+mod linux_gpu;
+
fn main() -> eframe::Result {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.iter().any(|a| a == "--version" || a == "-V") {
@@ -60,8 +63,15 @@ fn main() -> eframe::Result {
// the bundle's; no icon at all would bring eframe's own.
let icon = if cfg!(target_os = "macos") { None } else { eframe::icon_data::from_png_bytes(craft_anything_ui_egui::APP_ICON_PNG).ok() };
let viewport = viewport.with_icon(Arc::new(icon.unwrap_or_default()));
- #[cfg_attr(not(windows), expect(unused_mut, reason = "only Windows picks its own graphics adapter"))]
+ #[cfg_attr(not(any(windows, target_os = "linux")), expect(unused_mut, reason = "only Windows and Linux pick their own graphics adapter"))]
let mut options = eframe::NativeOptions { viewport, ..Default::default() };
+ #[cfg(target_os = "linux")]
+ if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
+ // egui-wgpu's default is the discrete GPU; on a laptop whose integrated GPU drives the
+ // panel, the window took 20 s to open and the whole desktop lagged (#571). Draw on the
+ // GPU that drives the screen; `WGPU_ADAPTER_NAME` and `WGPU_POWER_PREF` still decide.
+ setup.native_adapter_selector = Some(Arc::new(linux_gpu::pick_adapter));
+ }
#[cfg(windows)]
if let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &mut options.wgpu_options.wgpu_setup {
// Starting GL loads the system's OpenGL driver before any adapter is picked, and some
diff --git a/crates/platform/src/display.rs b/crates/platform/src/display.rs
new file mode 100644
index 00000000..8ae73368
--- /dev/null
+++ b/crates/platform/src/display.rs
@@ -0,0 +1,199 @@
+//! Which graphics cards drive displays, as the system reports them (Linux: `/sys/class/drm`).
+//!
+//! A window drawn on one card and shown on a screen attached to another is copied across on every
+//! frame. On a laptop whose integrated GPU drives the panel, drawing on the discrete GPU made the
+//! window take 20 s to open and the whole desktop lag (#571), so the app draws on the card that
+//! drives the screen.
+
+use std::io::Read as _;
+use std::path::Path;
+
+/// A graphics card and the displays connected to it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DisplayCard {
+ /// PCI vendor id: 0x1002 AMD, 0x10de NVIDIA, 0x8086 Intel.
+ pub vendor: u32,
+ /// PCI device id.
+ pub device: u32,
+ /// PCI address in the form `0000:05:00.0`, lowercase; empty when the system doesn't give one.
+ pub pci_slot: String,
+ /// Connected displays of any kind, built-in panel included.
+ pub displays: u32,
+ /// A connected built-in panel (eDP, LVDS or DSI): this card drives a laptop's own screen.
+ pub built_in_panel: bool,
+}
+
+/// Connector kinds that are a computer's own screen rather than a monitor plugged into it.
+const BUILT_IN_PANELS: &[&str] = &["eDP", "LVDS", "DSI"];
+
+/// At most this many entries are read from the DRM folder.
+const MAX_ENTRIES: usize = 512;
+
+/// At most this many bytes are read from one sysfs file.
+const MAX_FILE: u64 = 4096;
+
+/// The graphics cards on this computer and what's connected to them. Empty where the system
+/// doesn't say (anything but Linux, or a sandbox without `/sys`).
+pub fn display_cards() -> Vec<DisplayCard> {
+ #[cfg(target_os = "linux")]
+ {
+ display_cards_in(Path::new("/sys/class/drm"))
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ Vec::new()
+ }
+}
+
+/// [`display_cards`] read from a DRM folder laid out like `/sys/class/drm`: a `cardN` entry per
+/// card, with the card's PCI ids in `cardN/device/uevent`, and a `cardN-<kind>-<n>` entry per
+/// connector, with `connected` or `disconnected` in its `status`. Cards without PCI ids (a
+/// firmware framebuffer) are left out.
+pub fn display_cards_in(drm: &Path) -> Vec<DisplayCard> {
+ let Ok(entries) = std::fs::read_dir(drm) else {
+ return Vec::new();
+ };
+ let mut names: Vec<String> = entries.take(MAX_ENTRIES).filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
+ names.sort();
+ let cards = names.iter().filter(|n| is_card(n));
+ cards
+ .filter_map(|card| {
+ let uevent = read_small(&drm.join(card).join("device").join("uevent"))?;
+ let (vendor, device) = pci_ids(&uevent)?;
+ let pci_slot = uevent_value(&uevent, "PCI_SLOT_NAME").unwrap_or_default().to_ascii_lowercase();
+ let prefix = format!("{card}-");
+ let mut out = DisplayCard { vendor, device, pci_slot, displays: 0, built_in_panel: false };
+ for connector in names.iter().filter_map(|n| n.strip_prefix(&prefix)) {
+ let status = read_small(&drm.join(format!("{prefix}{connector}")).join("status")).unwrap_or_default();
+ if status.trim() != "connected" {
+ continue;
+ }
+ out.displays = out.displays.saturating_add(1);
+ if BUILT_IN_PANELS.contains(&connector_kind(connector)) {
+ out.built_in_panel = true;
+ }
+ }
+ Some(out)
+ })
+ .collect()
+}
+
+/// `card0`, `card12`: a card, not a connector (`card0-eDP-1`) or a render node.
+fn is_card(name: &str) -> bool {
+ name.strip_prefix("card").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
+}
+
+/// `eDP-1` → `eDP`, `HDMI-A-1` → `HDMI-A`: the connector's name without its number.
+fn connector_kind(connector: &str) -> &str {
+ match connector.rsplit_once('-') {
+ Some((kind, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => kind,
+ _ => connector,
+ }
+}
+
+/// `PCI_ID=1002:1638` → (0x1002, 0x1638).
+fn pci_ids(uevent: &str) -> Option<(u32, u32)> {
+ let (vendor, device) = uevent_value(uevent, "PCI_ID")?.split_once(':')?;
+ Some((u32::from_str_radix(vendor.trim(), 16).ok()?, u32::from_str_radix(device.trim(), 16).ok()?))
+}
+
+fn uevent_value<'a>(uevent: &'a str, key: &str) -> Option<&'a str> {
+ uevent.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).map(str::trim)
+}
+
+fn read_small(path: &Path) -> Option<String> {
+ let mut text = String::new();
+ std::fs::File::open(path).ok()?.take(MAX_FILE).read_to_string(&mut text).ok()?;
+ Some(text)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::fs;
+
+ /// A fake `/sys/class/drm`: cards as (name, PCI_ID, PCI_SLOT_NAME), connectors as
+ /// (name, status).
+ fn drm(cards: &[(&str, &str, &str)], connectors: &[(&str, &str)]) -> tempfile::TempDir {
+ let dir = tempfile::tempdir().expect("temp dir");
+ for (card, id, slot) in cards {
+ let device = dir.path().join(card).join("device");
+ fs::create_dir_all(&device).expect("card folder");
+ fs::write(device.join("uevent"), format!("DRIVER=x\nPCI_CLASS=30000\nPCI_ID={id}\nPCI_SLOT_NAME={slot}\n")).expect("uevent");
+ }
+ for (connector, status) in connectors {
+ let c = dir.path().join(connector);
+ fs::create_dir_all(&c).expect("connector folder");
+ fs::write(c.join("status"), format!("{status}\n")).expect("status");
+ }
+ fs::create_dir_all(dir.path().join("renderD128")).expect("render node");
+ fs::write(dir.path().join("version"), "drm 1.1.0\n").expect("version");
+ dir
+ }
+
+ /// #571's laptop: the AMD iGPU drives the panel, the NVIDIA card has no outputs.
+ #[test]
+ fn a_laptop_panel_is_found_on_the_integrated_gpu() {
+ let d = drm(
+ &[("card0", "10DE:25A2", "0000:01:00.0"), ("card1", "1002:1638", "0000:05:00.0")],
+ &[("card1-DP-1", "disconnected"), ("card1-eDP-1", "connected"), ("card1-HDMI-A-1", "disconnected")],
+ );
+ let cards = display_cards_in(d.path());
+ assert_eq!(
+ cards,
+ vec![
+ DisplayCard { vendor: 0x10de, device: 0x25a2, pci_slot: "0000:01:00.0".into(), displays: 0, built_in_panel: false },
+ DisplayCard { vendor: 0x1002, device: 0x1638, pci_slot: "0000:05:00.0".into(), displays: 1, built_in_panel: true },
+ ]
+ );
+ }
+
+ /// A desktop with a monitor on each card: displays on both, no built-in panel.
+ #[test]
+ fn monitors_on_two_cards_are_counted_on_each() {
+ let d = drm(
+ &[("card0", "8086:A780", "0000:00:02.0"), ("card1", "10de:2206", "0000:01:00.0")],
+ &[("card0-HDMI-A-1", "connected"), ("card1-DP-1", "connected"), ("card1-DP-2", "connected"), ("card1-DP-3", "disconnected")],
+ );
+ let cards = display_cards_in(d.path());
+ assert_eq!(cards.iter().map(|c| (c.displays, c.built_in_panel)).collect::<Vec<_>>(), vec![(1, false), (2, false)]);
+ }
+
+ /// `card10` is a different card from `card1`, and its connectors aren't `card1`'s.
+ #[test]
+ fn card_numbers_are_not_prefixes_of_each_other() {
+ let d = drm(&[("card1", "1002:1638", "0000:05:00.0"), ("card10", "10de:25a2", "0000:01:00.0")], &[("card10-DP-1", "connected")]);
+ let cards = display_cards_in(d.path());
+ assert_eq!(cards.iter().map(|c| (c.vendor, c.displays)).collect::<Vec<_>>(), vec![(0x1002, 0), (0x10de, 1)]);
+ }
+
+ /// LVDS and DSI panels are built in too; HDMI-A is a monitor, whatever its number.
+ #[test]
+ fn built_in_panels_are_told_from_monitors_by_connector_kind() {
+ assert_eq!(connector_kind("eDP-1"), "eDP");
+ assert_eq!(connector_kind("HDMI-A-1"), "HDMI-A");
+ assert_eq!(connector_kind("DSI-12"), "DSI");
+ assert_eq!(connector_kind("Virtual"), "Virtual");
+ let d = drm(&[("card0", "8086:9a49", "0000:00:02.0")], &[("card0-LVDS-1", "connected")]);
+ assert!(display_cards_in(d.path()).iter().all(|c| c.built_in_panel));
+ }
+
+ /// A firmware framebuffer has no PCI ids; unreadable or odd entries are skipped, never a panic.
+ #[test]
+ fn what_cant_be_read_is_left_out() {
+ let d = drm(&[("card0", "nonsense", ""), ("card1", "1002:", "")], &[("card0-Virtual-1", "connected")]);
+ fs::create_dir_all(d.path().join("card2")).expect("card without device");
+ fs::create_dir_all(d.path().join("card")).expect("bare name");
+ assert!(display_cards_in(d.path()).is_empty());
+ assert!(display_cards_in(&d.path().join("missing")).is_empty());
+ assert_eq!(pci_ids("PCI_ID=10de:25a2"), Some((0x10de, 0x25a2)));
+ assert_eq!(pci_ids("PCI_IDX=10de:25a2"), None);
+ }
+
+ /// A status of `unknown` (some virtual outputs) isn't a connected display.
+ #[test]
+ fn only_connected_counts() {
+ let d = drm(&[("card0", "1af4:1050", "0000:00:01.0")], &[("card0-Virtual-1", "unknown")]);
+ assert_eq!(display_cards_in(d.path()).first().map(|c| c.displays), Some(0));
+ }
+}
diff --git a/crates/platform/src/lib.rs b/crates/platform/src/lib.rs
index 9dcda91b..59e9e6ec 100644
--- a/crates/platform/src/lib.rs
+++ b/crates/platform/src/lib.rs
@@ -7,6 +7,7 @@
pub mod cancel;
pub mod capture;
+pub mod display;
pub mod fs;
pub mod process;
pub mod serve;
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 145e9933..6e98abbc 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -546,6 +546,14 @@ Gaps found while using the app for real projects.
request may take to arrive (#597, #598, #600, #601, by Afloat16)
- [x] The command palette stays where the wheel scrolls it; it follows the selection only when the
arrow keys or typing move it (#584)
+- [x] Linux: draw on the GPU that drives the screen. egui-wgpu's default picks the discrete GPU, so
+ on a laptop whose integrated GPU drives the panel the window took 20 s to open and the whole
+ desktop lagged (#571). Pick by the connected displays in `/sys/class/drm`: the built-in
+ panel's GPU, else the only GPU with displays, else the discrete one; `WGPU_POWER_PREF` and
+ `WGPU_ADAPTER_NAME` still decide when set. Checked live on an AMD + NVIDIA laptop only (#578)
+ — claimed: Nghiathan13, branch bugfix/r2.9-linux-gpu-choice
+- [ ] Linux GPU choice on a desktop with monitors on two GPUs, and on an Intel + NVIDIA laptop:
+ covered by unit tests on fake `/sys/class/drm` folders, not run on such a machine yet (#571)
### R2.10 Pinned builds
Owner: maintainers · Status: in progress
diff --git a/docs/STATUS.md b/docs/STATUS.md
index db1b776c..2112f785 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -189,6 +189,20 @@ Checked with parser fixtures, HTTP/SSE stand-ins exercising real engine tool exe
protocols, and non-action, stop-reason and duplicate-call controls. No live local-model build
was run; other text-call formats remain unsupported.
+### Linux graphics card choice
+
+On Linux the desktop app draws on the GPU that drives the screen (#571), read from the connected
+displays in `/sys/class/drm`: the built-in panel's GPU on a laptop, the only GPU with monitors on a
+desktop, and the discrete GPU when monitors are on more than one GPU or nothing can be read.
+`WGPU_ADAPTER_NAME` and `WGPU_POWER_PREF` still decide when set. `desktop.log` says which adapter
+was chosen and why.
+
+Checked live on one laptop (AMD Renoir iGPU driving the panel, NVIDIA RTX 3050, CachyOS, KDE
+Plasma on Wayland): the window opens in 3 s on the AMD GPU instead of 18–25 s on NVIDIA, and the
+desktop no longer lags; `WGPU_POWER_PREF=high`, `WGPU_ADAPTER_NAME=nvidia` and `DRI_PRIME=1` with
+`WGPU_POWER_PREF=none` still draw on NVIDIA. Desktops with monitors on one or two GPUs and Intel
+laptops are covered by unit tests on fake `/sys/class/drm` folders only.
+
## Known limits
- Locks: every mutex but the browser viewer's goes through `platform::sync`. A deadlock on one thread or across
diff --git a/docs/pitfalls.md b/docs/pitfalls.md
index 68cfba9e..8ef50835 100644
--- a/docs/pitfalls.md
+++ b/docs/pitfalls.md
@@ -233,6 +233,13 @@ observed (#251). A run that never started the thing it observes is a failure, no
check the exit status before building evidence, and compile generated code (here, with Python)
before trusting it. lldb itself was not run here.
+**A graphics default that drew on the other card.** egui-wgpu picks the discrete GPU unless told
+otherwise; on a Linux laptop whose integrated GPU drives the panel, every frame was copied across
+to it, the window took 20 s to open and the whole desktop lagged (#571). Forcing the low-power GPU
+instead breaks desktops whose monitors are on the discrete card. Draw on the GPU that drives the
+screen, read from the connected displays, and keep wgpu's environment variables as the override;
+when a window is slow to open, check which adapter `desktop.log` says it drew with.
+
**A Mac app that couldn't find Claude Code, and offered a GitHub key instead.** An app opened from
the Dock gets the system's short `PATH`, not the shell's, so `claude` in `~/.local/bin` wasn't
found; "Built by" then fell back to "Claude Code on github.com-work", an `~/.ssh/config` alias