Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

11.6 KB
Raw Blame
//! The wallpaper under the icons: the user's own picture, placed for the rectangle the canvas is shown in (the model's placement maths
//! and decoder, `rf_win::desktop::render`), as ONE bitmap of exactly that size. Nothing is drawn per frame: the view uploads the
//! bitmap once and asks for a new one when the shown size changes (after the window has stopped resizing) or when the wallpaper
//! setting changes.
//!
//! Placement is computed for the SHOWN rectangle, as the shell plan asks ("placed for the window's rectangle"). Fill, fit, stretch and
//! span therefore look as they will on the monitor, only smaller; center and tile show the picture at its real pixel size inside the
//! smaller rectangle, so they look different from the monitor when the canvas is scaled down. The preview says so in its status line
//! (the scale is there).

use std::path::PathBuf;
use std::sync::Arc;

use rf_core::desktop::geom::{Rect, Rgb, Size};
use rf_core::desktop::placement::TileAnchor;
use rf_core::desktop::wallpaper::{MonitorWallpaper, Source, Wallpaper};
use rf_win::desktop::render::{ImageDecoder, RenderOptions, render_all};
use rf_win::desktop::wallcache::DiskCache;
use rf_win::desktop::wallpaper::DiskStamper;
use rf_win::thumbs::Bgra;

/// How many bitmaps the preview keeps on disk (one per size it has been shown at).
pub const CACHE_ENTRIES: usize = 6;

/// The wallpaper as it applies to ONE monitor shown in a rectangle of `size` pixels: that monitor's picture alone, in a rectangle that
/// starts at (0, 0).
pub fn for_canvas(wp: &Wallpaper, canvas: usize, size: Size) -> Wallpaper {
    let picture = wp.pictures().get(canvas).cloned().flatten();
    let device = wp.monitors.get(canvas).map(|m| m.device.clone()).unwrap_or_default();
    Wallpaper {
        // the picture is already resolved above (a virtual desktop's own value included), so the per-desktop logic must not run again
        source: Source::DesktopWallpaperCom,
        monitors: vec![MonitorWallpaper { device, rect: Rect::from_size(0, 0, size.w, size.h), picture }],
        per_desktop: Vec::new(),
        ..wp.clone()
    }
}

/// The wallpaper as it applies to all monitors in cover mode: pictures are resolved once across the virtual screen, and each
/// monitor keeps its real virtual-screen rectangle so `Span` and `Tile` (`TileAnchor::VirtualScreen`) align across displays.
/// Returns the resolved wallpaper and the matching index in `monitors` for the target monitor.
pub fn for_cover(wp: &Wallpaper, target_rect: Rect, target_device: &str, fallback_canvas: usize) -> Option<(Wallpaper, usize)> {
    if wp.monitors.is_empty() {
        return None;
    }
    let pics = wp.pictures();
    let monitors: Vec<MonitorWallpaper> = wp
        .monitors
        .iter()
        .enumerate()
        .map(|(i, m)| MonitorWallpaper { picture: pics.get(i).cloned().flatten(), ..m.clone() })
        .collect();
    let idx = monitors
        .iter()
        .position(|m| m.rect == target_rect)
        .or_else(|| (!target_device.is_empty()).then(|| monitors.iter().position(|m| m.device.eq_ignore_ascii_case(target_device))).flatten())
        .or_else(|| (fallback_canvas < monitors.len()).then_some(fallback_canvas))?;
    let resolved = Wallpaper {
        source: Source::DesktopWallpaperCom,
        monitors,
        per_desktop: Vec::new(),
        ..wp.clone()
    };
    Some((resolved, idx))
}

pub struct Rendered {
    pub bitmap: Arc<Bgra>,
    pub background: Rgb,
    /// Why there is no picture in it, when there is none (missing file, undecodable).
    pub note: Option<String>,
}

/// Blocking: decodes (or reads the disk cache). Run it off the UI thread.
pub fn render(wp: &Wallpaper, canvas: usize, size: Size, cache_dir: Option<PathBuf>) -> Rendered {
    let one = for_canvas(wp, canvas, size);
    let cache = cache_dir.map(|d| DiskCache::new(d, CACHE_ENTRIES));
    let mut out = render_all(&one, &RenderOptions { anchor: TileAnchor::Monitor, cache: cache.as_ref() }, &ImageDecoder, &DiskStamper);
    let m = out.pop().expect("one monitor, one bitmap");
    Rendered { bitmap: m.bitmap, background: one.background, note: m.note }
}

/// Cover mode rendering: uses the full multi-monitor virtual screen (`TileAnchor::VirtualScreen`) and selects the bitmap matching
/// `target_rect` / `target_device`. Falls back to [`render`] if the monitor is missing or its rendered size does not match `size`.
pub fn render_cover(wp: &Wallpaper, target_rect: Rect, target_device: &str, fallback_canvas: usize, size: Size, cache_dir: Option<PathBuf>) -> Rendered {
    let Some((resolved, idx)) = for_cover(wp, target_rect, target_device, fallback_canvas) else {
        return render(wp, fallback_canvas, size, cache_dir);
    };
    let cache = cache_dir.map(|d| DiskCache::new(d, CACHE_ENTRIES));
    let mut out = render_all(&resolved, &RenderOptions { anchor: TileAnchor::VirtualScreen, cache: cache.as_ref() }, &ImageDecoder, &DiskStamper);
    if idx < out.len() && (out[idx].bitmap.width, out[idx].bitmap.height) == (size.w, size.h) {
        let m = out.swap_remove(idx);
        return Rendered { bitmap: m.bitmap, background: resolved.background, note: m.note };
    }
    render(wp, fallback_canvas, size, None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use rf_core::desktop::placement::Position;
    use rf_core::desktop::wallpaper::BackgroundKind;

    fn wp(pictures: [Option<&str>; 2]) -> Wallpaper {
        Wallpaper {
            source: Source::Registry,
            monitors: vec![
                MonitorWallpaper { device: "A".into(), rect: Rect::new(0, 0, 2560, 1440), picture: pictures[0].map(PathBuf::from) },
                MonitorWallpaper { device: "B".into(), rect: Rect::new(2560, -618, 4000, 1942), picture: pictures[1].map(PathBuf::from) },
            ],
            position: Position::Fit,
            position_assumed: false,
            background: Rgb(195, 0, 82),
            kind: BackgroundKind::Picture,
            slideshow: None,
            per_desktop: Vec::new(),
        }
    }

    #[test]
    fn the_canvas_gets_its_own_monitors_picture_in_a_rectangle_of_the_shown_size() {
        let w = wp([Some(r"C:\a.png"), Some(r"C:\b.png")]);
        let one = for_canvas(&w, 1, Size::new(720, 1280));
        assert_eq!(one.monitors.len(), 1);
        assert_eq!(one.monitors[0].picture, Some(PathBuf::from(r"C:\b.png")));
        assert_eq!(one.monitors[0].rect, Rect::new(0, 0, 720, 1280), "no negative origin: the canvas is its own world");
        assert_eq!(one.monitors[0].device, "B");
        assert_eq!((one.position, one.background), (Position::Fit, Rgb(195, 0, 82)), "mode and colour are the system's");
        assert_eq!(for_canvas(&w, 0, Size::new(10, 10)).monitors[0].picture, Some(PathBuf::from(r"C:\a.png")));
    }

    #[test]
    fn no_picture_and_solid_colour_stay_solid() {
        assert_eq!(for_canvas(&wp([None, None]), 0, Size::new(10, 10)).monitors[0].picture, None);
        let mut w = wp([Some(r"C:\a.png"), None]);
        w.kind = BackgroundKind::SolidColor;
        let one = for_canvas(&w, 0, Size::new(10, 10));
        assert_eq!(one.pictures(), vec![None], "a solid colour shows no picture");
        // a canvas index past the monitors gives an empty picture, not a panic
        assert_eq!(for_canvas(&w, 9, Size::new(10, 10)).monitors[0].picture, None);
    }

    #[test]
    fn a_virtual_desktops_own_picture_is_resolved_once_and_not_again() {
        use rf_core::desktop::wallpaper::DesktopWallpaperValue;
        let mut w = wp([Some(r"C:\transcoded"), Some(r"C:\transcoded")]);
        w.per_desktop = vec![DesktopWallpaperValue { desktop: "{x}".into(), current: true, picture: Some(PathBuf::from(r"C:\original.jpg")) }];
        let one = for_canvas(&w, 0, Size::new(10, 10));
        assert_eq!(one.monitors[0].picture, Some(PathBuf::from(r"C:\original.jpg")), "the original, not the transcoded copy");
        assert!(one.per_desktop.is_empty());
        assert_eq!(one.pictures(), vec![Some(PathBuf::from(r"C:\original.jpg"))]);
    }

    #[test]
    fn rendering_a_missing_picture_gives_the_colour_and_says_why() {
        let w = wp([Some(r"C:\definitely\not\there.png"), None]);
        let r = render(&w, 0, Size::new(8, 6), None);
        assert_eq!((r.bitmap.width, r.bitmap.height), (8, 6));
        assert_eq!(&r.bitmap.data[..4], &[82, 0, 195, 255], "BGRA of the background colour");
        assert!(r.note.is_some());
        assert_eq!(r.background, Rgb(195, 0, 82));
    }

    #[test]
    fn rendering_a_real_picture_fills_the_shown_rectangle() {
        let dir = std::env::temp_dir().join(format!("rf-deskwall-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let pic = dir.join("red.png");
        image::RgbaImage::from_pixel(40, 20, image::Rgba([255, 0, 0, 255])).save_with_format(&pic, image::ImageFormat::Png).unwrap();
        let mut w = wp([None, None]);
        w.monitors[0].picture = Some(pic.clone());
        w.position = Position::Stretch;
        let cache = dir.join("cache");
        let r = render(&w, 0, Size::new(16, 12), Some(cache.clone()));
        assert_eq!((r.bitmap.width, r.bitmap.height), (16, 12));
        assert_eq!(&r.bitmap.data[..4], &[0, 0, 255, 255], "red, as BGRA");
        assert!(r.note.is_none());
        // the second time it comes from the disk cache
        let again = render(&w, 0, Size::new(16, 12), Some(cache));
        assert_eq!(again.bitmap.data, r.bitmap.data);
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn cover_mode_preserves_virtual_screen_and_matches_monitor_by_rect_or_device() {
        let mut w = wp([Some(r"C:\a.png"), Some(r"C:\b.png")]);
        w.position = Position::Span;
        let (resolved, idx) = for_cover(&w, Rect::new(2560, -618, 4000, 1942), "B", 0).unwrap();
        assert_eq!(idx, 1, "matched by rect even when fallback_canvas is 0");
        assert_eq!(resolved.monitors.len(), 2);
        assert_eq!(resolved.monitors[0].rect, Rect::new(0, 0, 2560, 1440));
        assert_eq!(resolved.monitors[1].rect, Rect::new(2560, -618, 4000, 1942));

        let (_, idx_dev) = for_cover(&w, Rect::new(1, 2, 3, 4), "b", 0).unwrap();
        assert_eq!(idx_dev, 1, "falls back to case-insensitive device match");
    }

    #[test]
    fn cover_mode_span_renders_distinct_slices_across_monitors() {
        let dir = std::env::temp_dir().join(format!("rf-deskwall-span-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let pic = dir.join("split.png");
        let mut img = image::RgbaImage::new(20, 10);
        for y in 0..10 {
            for x in 0..20 {
                let px = if x < 10 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) };
                img.put_pixel(x, y, px);
            }
        }
        img.save_with_format(&pic, image::ImageFormat::Png).unwrap();
        let w = Wallpaper {
            source: Source::DesktopWallpaperCom,
            monitors: vec![
                MonitorWallpaper { device: "A".into(), rect: Rect::new(0, 0, 10, 10), picture: Some(pic.clone()) },
                MonitorWallpaper { device: "B".into(), rect: Rect::new(10, 0, 20, 10), picture: Some(pic) },
            ],
            position: Position::Span,
            position_assumed: false,
            background: Rgb(0, 0, 0),
            kind: BackgroundKind::Picture,
            slideshow: None,
            per_desktop: Vec::new(),
        };
        let left = render_cover(&w, Rect::new(0, 0, 10, 10), "A", 0, Size::new(10, 10), None);
        let right = render_cover(&w, Rect::new(10, 0, 20, 10), "B", 1, Size::new(10, 10), None);
        assert_eq!(&left.bitmap.data[..4], &[0, 0, 255, 255], "left half is red in BGRA");
        assert_eq!(&right.bitmap.data[..4], &[255, 0, 0, 255], "right half is blue in BGRA");
        let _ = std::fs::remove_dir_all(dir);
    }
}