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.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
Convert in the right-click menu: pictures into another format, next to the originals
gelenmedya64df0eac6273
diff --git a/AGENTS.md b/AGENTS.mdindex b3ea22a5..b90dc33a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -30,7 +30,8 @@ Short rules for a tool that writes code here (and for the person driving it). Th- **Layout.** `crates/rf-app` is the interface (GPUI), `rf-win` everything that talks to Windows,`rf-core`, `rf-archive` and `rf-nearby` are shared with the macOS app, `rf-dialog` is the DLL that- runs inside other programs for Open/Save, `rf-shellguard` watches the Explorer replacement. The+ runs inside other programs for Open/Save, `rf-shellguard` watches the Explorer replacement,+ `rf-convert` is the converter's core (pure Rust: what turns into what, and the writing). ThemacOS app (`macos/`, `crates/rf-mac`) is outside the Windows workspace and builds on a Mac only:if you change a public type in a shared crate, search `crates/rf-mac` for its uses.- **Nothing waits on the interface thread.** Disk, shell and network calls run on a backgrounddiff --git a/Cargo.lock b/Cargo.lockindex cfd7d351..f8dea197 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6671,6 +6671,7 @@ dependencies = ["raw-window-handle","resvg 0.46.0","rf-archive",+ "rf-convert","rf-core","rf-dialog","rf-nearby",@@ -6717,6 +6718,16 @@ dependencies = ["zstd",]+[[package]]+name = "rf-convert"+version = "1.1.1"+dependencies = [+ "anyhow",+ "image",+ "jxl-oxide",+ "rf-jxl",+]+[[package]]name = "rf-core"version = "1.1.1"@@ -6821,6 +6832,7 @@ dependencies = ["psd","rayon","resvg 0.46.0",+ "rf-convert","rf-core","rf-shellguard","roxmltree 0.20.0",diff --git a/Cargo.toml b/Cargo.tomlindex 38cff502..343fb6a2 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[workspace]resolver = "3"-members = ["crates/rf-core", "crates/rf-win", "crates/rf-app", "crates/rf-nearby", "crates/rf-archive", "crates/rf-dialog", "crates/rf-shellguard", "crates/rf-player", "crates/rustdecoder", "crates/rf-jxl", "tools/gpustress"]+members = ["crates/rf-core", "crates/rf-win", "crates/rf-app", "crates/rf-nearby", "crates/rf-archive", "crates/rf-dialog", "crates/rf-shellguard", "crates/rf-player", "crates/rustdecoder", "crates/rf-jxl", "crates/rf-convert", "tools/gpustress"]# The macOS app (Swift in macos/, its Rust bridge in crates/rf-mac) is built on the Mac only, as a workspace of its own.exclude = ["crates/rf-mac", "macos", "vendor/velopack"]@@ -47,6 +47,7 @@ sha2 = "0.10"crc32fast = "1"regex = "1"rf-archive = { path = "crates/rf-archive" }+rf-convert = { path = "crates/rf-convert" }tar = { version = "0.4", default-features = false }flate2 = { version = "1.1", default-features = false, features = ["zlib-rs"] }zstd = { version = "0.14", default-features = false, features = ["zstdmt"] }diff --git a/crates/rf-app/Cargo.toml b/crates/rf-app/Cargo.tomlindex 824b38d2..ecc646a0 100644--- a/crates/rf-app/Cargo.toml+++ b/crates/rf-app/Cargo.toml@@ -24,6 +24,7 @@ rf-dialog = { path = "../rf-dialog" }# installer and auto-update (GitHub Releases)velopack = "=1.2.161"rf-archive.workspace = true+rf-convert.workspace = truerf-nearby.workspace = truerf-player.workspace = truerustdecoder.workspace = truediff --git a/crates/rf-app/src/ctx_menu.rs b/crates/rf-app/src/ctx_menu.rsindex e7e41908..a1320fbd 100644--- a/crates/rf-app/src/ctx_menu.rs+++ b/crates/rf-app/src/ctx_menu.rs@@ -612,6 +612,13 @@ impl FolderView {None => Item::sub(t!("Sıkıştır"), compress_icon, sub_items),});}+ // pictures: into another format, next to the originals (the converter; nothing for a selection that is not all pictures)+ if mp.convert && !in_archive {+ let targets = convert_targets(items);+ if !targets.is_empty() {+ v.push(Item::sub(t!("Dönüştür"), icon(L::Replace), convert_menu(items, &targets)));+ }+ }// a .torrent file, with HyperDownload installed: downloaded next to itif items.len() == 1&& items[0].extension().is_some_and(|e| e.eq_ignore_ascii_case("torrent"))@@ -1184,6 +1191,24 @@ fn archive_stem(items: &[PathBuf]) -> Option<(PathBuf, String)> {Some((dir, stem))}+/// The picture formats the selection `items` can be converted to; empty when one of them is no picture the converter takes.+/// Told by the names alone (no disk is asked while the menu is built): a folder named like a picture fails in the work, by name.+fn convert_targets(items: &[PathBuf]) -> Vec<rf_convert::PictureFormat> {+ let exts: Vec<String> = items.iter().map(|p| rf_convert::ext_of(p)).collect();+ rf_convert::picture_targets(exts.iter().map(String::as_str))+}++/// The "Dönüştür" submenu: one row a target format. A click converts every selected picture, next to its original.+fn convert_menu(items: &[PathBuf], targets: &[rf_convert::PictureFormat]) -> Vec<Item> {+ targets+ .iter()+ .map(|&format| {+ let items = items.to_vec();+ Item::action(format.label(), icon(L::FileImage), move |_, cx| crate::status_center::convert_pictures(cx, items.clone(), format))+ })+ .collect()+}+/// The "Sıkıştır" submenu for `items`: the archive dialog, then ZIP, 7z and (with WinRAR) RAR at once. Also the toolbar's Compress/// button's menu (discussion 677).fn compress_menu(items: &[PathBuf]) -> Vec<Item> {diff --git a/crates/rf-app/src/i18n_en.rs b/crates/rf-app/src/i18n_en.rsindex 5828dbc5..504e3d35 100644--- a/crates/rf-app/src/i18n_en.rs+++ b/crates/rf-app/src/i18n_en.rs@@ -419,6 +419,9 @@ pub const EN: &[(&str, &str)] = &[("Sayfa düzeni", "Layout"),("Seçenekler yüklenemedi", "Couldn't load options"),("Sıkıştır", "Compress"),+ ("Dönüştür", "Convert"),+ ("Dönüştürülüyor:", "Converting:"),+ ("{n} dosya dönüştürülemedi. İlki: {name}: {why}", "{n} file(s) could not be converted. The first: {name}: {why}"),("Sırala", "Sort"),("Ada göre sırala, A'dan Z'ye", "Sort by name, A to Z"),("Ada göre sırala, Z'den A'ya", "Sort by name, Z to A"),diff --git a/crates/rf-app/src/settings.rs b/crates/rf-app/src/settings.rsindex 4907ac58..abc7080f 100644--- a/crates/rf-app/src/settings.rs+++ b/crates/rf-app/src/settings.rs@@ -490,6 +490,8 @@ pub struct MenuPrefs {pub create_shortcut: bool,pub pin: bool,pub compress: bool,+ /// "Dönüştür": pictures into another format, next to the originals (the converter).+ pub convert: bool,pub tags: bool,/// "Seç": select all, none, invert (Discord, 2026-11-29: "a new context sub menu that gives you options to quickly select/de-select/// items without having to rely on keyboard shortcuts").@@ -532,6 +534,7 @@ impl Default for MenuPrefs {create_shortcut: true,pin: true,compress: true,+ convert: true,tags: true,select: true,shelf: true,diff --git a/crates/rf-app/src/settings_view.rs b/crates/rf-app/src/settings_view.rsindex 5ac3dca1..a6a6af73 100644--- a/crates/rf-app/src/settings_view.rs+++ b/crates/rf-app/src/settings_view.rs@@ -1303,7 +1303,7 @@ fn general(p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {None,move || {type Set = fn(&mut Settings, bool);- let rows: [(&str, bool, Set); 16] = [+ let rows: [(&str, bool, Set); 17] = [(t!("Yeni sekmede aç"), m.open_in_new_tab, |s, v| s.menu.open_in_new_tab = v),(t!("Yeni sekmede arka planda aç"), m.open_in_background_tab, |s, v| s.menu.open_in_background_tab = v),(t!("Yeni pencerede aç"), m.open_in_new_window, |s, v| s.menu.open_in_new_window = v),@@ -1311,6 +1311,7 @@ fn general(p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {(t!("Kısayol oluştur"), m.create_shortcut, |s, v| s.menu.create_shortcut = v),(t!("Kenar çubuğuna sabitle"), m.pin, |s, v| s.menu.pin = v),(t!("Sıkıştır / Çıkar"), m.compress, |s, v| s.menu.compress = v),+ (t!("Dönüştür"), m.convert, |s, v| s.menu.convert = v),(t!("Etiketler"), m.tags, |s, v| s.menu.tags = v),(t!("Seç"), m.select, |s, v| s.menu.select = v),(t!("Rafa ekle"), m.shelf, |s, v| s.menu.shelf = v),diff --git a/crates/rf-app/src/status_center.rs b/crates/rf-app/src/status_center.rsindex 30417571..0f898a21 100644--- a/crates/rf-app/src/status_center.rs+++ b/crates/rf-app/src/status_center.rs@@ -1467,6 +1467,31 @@ pub fn compress_level(cx: &mut App, sources: Vec<std::path::PathBuf>, dest: std:});}+/// Pictures written in another format next to their originals (the converter). Nothing is replaced: a name that is taken gets a+/// number. The files run a few at a time; one that cannot be read is named when the work ends, and the others are still made.+pub fn convert_pictures(cx: &mut App, sources: Vec<std::path::PathBuf>, format: rf_convert::PictureFormat) {+ let title = format!("{} {} → {}", t!("Dönüştürülüyor:"), named(&sources), format.label());+ start(cx, title, move |t| {+ let progress = |done: u32, total: u32, name: &str| (t.on_progress)(total, done, Some(name.to_string()));+ let outcomes = rf_win::convert::pictures(&sources, format, &rf_convert::PictureOptions::default(), &t.cancel, &progress);+ let failed: Vec<(String, String)> = outcomes+ .iter()+ .filter_map(|o| o.result.as_ref().err().map(|e| (rf_core::history::display_name(&o.source), format!("{e:#}"))))+ .collect();+ for (name, why) in &failed {+ log::warn!("convert to {}: {name}: {why}", format.label());+ }+ match failed.first() {+ Some((name, why)) => anyhow::bail!(+ "{}",+ t!("{n} dosya dönüştürülemedi. İlki: {name}: {why}").replace("{n}", &failed.len().to_string()).replace("{name}", name).replace("{why}", why)+ ),+ // (stopped before every file was begun: cancelled, not done)+ None => Ok(outcomes.len() == sources.len()),+ }+ });+}+/// A place only Windows' own engine reaches: an item of a shell folder (a phone's, `::{...}`) or of an FTP server.fn is_shell_name(p: &std::path::Path) -> bool {p.to_string_lossy().starts_with("::") || rf_win::ftp::is_ftp(p)diff --git a/crates/rf-convert/Cargo.toml b/crates/rf-convert/Cargo.tomlnew file mode 100644index 00000000..96200b82--- /dev/null+++ b/crates/rf-convert/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "rf-convert"+description = "rustyfiles' converter: which files turn into what, and the writing of the result. Pure Rust, no Windows code."+version.workspace = true+edition.workspace = true+license.workspace = true+publish.workspace = true++[dependencies]+anyhow.workspace = true+image = { workspace = true, features = ["png", "jpeg", "gif", "webp", "bmp", "ico", "tiff", "qoi"] }+rf-jxl = { path = "../rf-jxl" }++[dev-dependencies]+# (the reference decoder for our own JPEG XL files, as in rf-jxl's tests)+jxl-oxide = "0.12"diff --git a/crates/rf-convert/src/lib.rs b/crates/rf-convert/src/lib.rsnew file mode 100644index 00000000..3f0aba67--- /dev/null+++ b/crates/rf-convert/src/lib.rs@@ -0,0 +1,467 @@+//! rustyfiles' converter (plan: a ring of target formats while dragging, "Convert" in the right-click menu, a command line; the+//! idea of Filee, with no outside program: every format is code of ours or a pure Rust crate).+//!+//! This crate is the part that is the same on every system: which files the converter takes, which targets a selection has, the+//! encoding of a decoded picture into a target format, and the writing of the result without ever replacing a file. DECODING is+//! the platform's (on Windows `rf_win::look::decode`, which also asks Windows' codecs for HEIC and AVIF): a picture arrives here+//! as 8-bit RGBA.+//!+//! Step 1 is pictures. What it does not do yet, on purpose and said in the interface where it matters:+//! * camera RAW files are not taken (their full picture needs the system's raw codec; the preview inside may be small);+//! * an animated GIF or WebP gives its first frame;+//! * 8 bits a channel: a 16-bit or HDR picture loses depth, and colour profiles and EXIF are not carried over (the platform hands+//! the picture upright, so nothing ends up turned);+//! * WebP is written without loss only: there is no lossy WebP encoder in pure Rust.++use std::io::{Cursor, Write};+use std::path::{Path, PathBuf};++use anyhow::{Context, ensure};+use image::{ExtendedColorType, ImageEncoder};++/// A picture format the converter writes.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum PictureFormat {+ Png,+ Jpeg,+ Webp,+ Jxl,+ Bmp,+ Tiff,+ Gif,+ Ico,+ Qoi,+}++impl PictureFormat {+ /// Every target, in the order the interface shows them: the ones asked for most first.+ pub const ALL: [PictureFormat; 9] = [Self::Jpeg, Self::Png, Self::Webp, Self::Jxl, Self::Tiff, Self::Bmp, Self::Gif, Self::Ico, Self::Qoi];++ /// The extension a file of this format gets, without the dot.+ pub fn ext(self) -> &'static str {+ match self {+ Self::Png => "png",+ Self::Jpeg => "jpg",+ Self::Webp => "webp",+ Self::Jxl => "jxl",+ Self::Bmp => "bmp",+ Self::Tiff => "tif",+ Self::Gif => "gif",+ Self::Ico => "ico",+ Self::Qoi => "qoi",+ }+ }++ /// The name in the interface (a format's name is the same in every language).+ pub fn label(self) -> &'static str {+ match self {+ Self::Png => "PNG",+ Self::Jpeg => "JPEG",+ Self::Webp => "WebP",+ Self::Jxl => "JPEG XL",+ Self::Bmp => "BMP",+ Self::Tiff => "TIFF",+ Self::Gif => "GIF",+ Self::Ico => "ICO",+ Self::Qoi => "QOI",+ }+ }++ /// The format a file with this extension (lower case, no dot) IS, when it is one of the targets.+ pub fn of_ext(ext: &str) -> Option<Self> {+ Some(match ext {+ "png" => Self::Png,+ "jpg" | "jpeg" | "jpe" | "jfif" => Self::Jpeg,+ "webp" => Self::Webp,+ "jxl" => Self::Jxl,+ "bmp" | "dib" => Self::Bmp,+ "tif" | "tiff" => Self::Tiff,+ "gif" => Self::Gif,+ "ico" => Self::Ico,+ "qoi" => Self::Qoi,+ _ => return None,+ })+ }++ /// Whether the format throws detail away to be small ([`PictureOptions::quality`] matters for these only).+ pub fn lossy(self) -> bool {+ matches!(self, Self::Jpeg | Self::Jxl)+ }++ /// Whether a file of this format can be see-through. The others get the picture on [`PictureOptions::background`].+ pub fn keeps_transparency(self) -> bool {+ !matches!(self, Self::Jpeg | Self::Bmp)+ }++ /// The longest side the format (or its use) allows; a bigger picture is fitted into it.+ fn max_side(self) -> Option<u32> {+ match self {+ // an icon file holds pictures of up to 256 pixels+ Self::Ico => Some(256),+ Self::Gif | Self::Jpeg => Some(65_535),+ Self::Webp => Some(16_383),+ _ => None,+ }+ }+}++/// The extensions (lower case, no dot) of pictures the converter takes, beside the targets' own. Camera RAW files are not among+/// them yet (see the top of this file).+const OTHER_PICTURES: &[&str] = &["heic", "heif", "avif", "tga", "dds", "exr", "hdr", "pnm", "pbm", "pgm", "ppm", "svg", "psd"];++/// Whether a file with this extension (lower case, no dot) is a picture the converter takes.+pub fn is_picture(ext: &str) -> bool {+ PictureFormat::of_ext(ext).is_some() || OTHER_PICTURES.contains(&ext)+}++/// The extension of `path` as the functions here want it: lower case, no dot; empty when there is none.+pub fn ext_of(path: &Path) -> String {+ path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase()+}++/// The targets to offer for a selection of files with these extensions (lower case, no dot). Nothing when the selection is empty+/// or one of the files is no picture: the entry is for a selection that converts whole, not for a part of it. A format that every+/// file already is, is left out (PNG to PNG is not a conversion).+pub fn picture_targets<'a>(exts: impl IntoIterator<Item = &'a str>) -> Vec<PictureFormat> {+ let mut all_are: Option<Option<PictureFormat>> = None;+ for ext in exts {+ if !is_picture(ext) {+ return Vec::new();+ }+ let this = PictureFormat::of_ext(ext);+ all_are = Some(match all_are {+ None => this,+ Some(so_far) if so_far == this => so_far,+ Some(_) => None,+ });+ }+ let Some(all_are) = all_are else { return Vec::new() };+ PictureFormat::ALL.into_iter().filter(|f| Some(*f) != all_are).collect()+}++/// How a picture is written.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PictureOptions {+ /// 1 to 100, for the formats that are [`PictureFormat::lossy`]. 90 is the usual "looks the same" setting.+ pub quality: u8,+ /// The longest side of the result; a bigger picture is made smaller, a smaller one is left as it is. `None`: the picture's own.+ pub max_side: Option<u32>,+ /// What shows through where the picture is see-through, for a format that cannot be (JPEG, BMP).+ pub background: [u8; 3],+}++impl Default for PictureOptions {+ fn default() -> Self {+ Self { quality: 90, max_side: None, background: [255, 255, 255] }+ }+}++/// A decoded picture: 8-bit RGBA, rows from the top, not premultiplied.+#[derive(Clone, Copy)]+pub struct Picture<'a> {+ pub width: u32,+ pub height: u32,+ pub rgba: &'a [u8],+}++impl Picture<'_> {+ fn check(&self) -> anyhow::Result<()> {+ ensure!(self.width > 0 && self.height > 0, "the picture is empty");+ let want = (self.width as u64) * (self.height as u64) * 4;+ ensure!(self.rgba.len() as u64 == want, "the picture's data is {} bytes, {}x{} needs {want}", self.rgba.len(), self.width, self.height);+ Ok(())+ }+}++/// Whether no pixel of the picture is see-through.+fn opaque(rgba: &[u8]) -> bool {+ rgba.chunks_exact(4).all(|p| p[3] == 255)+}++/// The picture on a plain background, as RGB.+fn flattened(rgba: &[u8], bg: [u8; 3]) -> Vec<u8> {+ let mut out = Vec::with_capacity(rgba.len() / 4 * 3);+ for p in rgba.chunks_exact(4) {+ let a = p[3] as u32;+ for c in 0..3 {+ // (rounded: a fully covered pixel stays exactly its colour, an empty one exactly the background)+ out.push(((p[c] as u32 * a + bg[c] as u32 * (255 - a) + 127) / 255) as u8);+ }+ }+ out+}++/// The picture without its alpha channel (for one that is [`opaque`]).+fn rgb_of(rgba: &[u8]) -> Vec<u8> {+ let mut out = Vec::with_capacity(rgba.len() / 4 * 3);+ for p in rgba.chunks_exact(4) {+ out.extend_from_slice(&p[..3]);+ }+ out+}++/// The size of a `w` x `h` picture fitted into `max` on its longest side (never bigger than it was, never zero on a side).+fn fitted(w: u32, h: u32, max: u32) -> (u32, u32) {+ let long = w.max(h);+ if long <= max {+ return (w, h);+ }+ let scale = |v: u32| ((v as u64 * max as u64 + long as u64 / 2) / long as u64).max(1) as u32;+ (scale(w), scale(h))+}++/// Encodes `picture` as a file of `format`. The bytes are the whole file.+pub fn encode_picture(picture: Picture<'_>, format: PictureFormat, options: &PictureOptions) -> anyhow::Result<Vec<u8>> {+ picture.check()?;+ // the size: what was asked for, inside what the format allows+ let limit = match (options.max_side, format.max_side()) {+ (Some(a), Some(b)) => Some(a.min(b)),+ (a, b) => a.or(b),+ };+ let (w, h) = limit.map_or((picture.width, picture.height), |m| fitted(picture.width, picture.height, m.max(1)));+ let resized;+ let rgba: &[u8] = if (w, h) == (picture.width, picture.height) {+ picture.rgba+ } else {+ let src = image::RgbaImage::from_raw(picture.width, picture.height, picture.rgba.to_vec()).context("the picture's data does not fit its size")?;+ resized = image::imageops::resize(&src, w, h, image::imageops::FilterType::CatmullRom).into_raw();+ &resized+ };+ let solid = opaque(rgba);+ // three channels where the format has no transparency or the picture has none; four otherwise+ let (pixels, color): (std::borrow::Cow<'_, [u8]>, ExtendedColorType) = if !format.keeps_transparency() {+ (flattened(rgba, options.background).into(), ExtendedColorType::Rgb8)+ } else if solid && !matches!(format, PictureFormat::Ico | PictureFormat::Gif) {+ (rgb_of(rgba).into(), ExtendedColorType::Rgb8)+ } else {+ (rgba.into(), ExtendedColorType::Rgba8)+ };+ let mut out = Vec::new();+ match format {+ PictureFormat::Png => {+ use image::codecs::png::{CompressionType, FilterType, PngEncoder};+ PngEncoder::new_with_quality(&mut out, CompressionType::Default, FilterType::Adaptive).write_image(&pixels, w, h, color)?+ }+ PictureFormat::Jpeg => image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, options.quality.clamp(1, 100)).write_image(&pixels, w, h, color)?,+ PictureFormat::Webp => image::codecs::webp::WebPEncoder::new_lossless(&mut out).write_image(&pixels, w, h, color)?,+ PictureFormat::Jxl => {+ // (our own encoder takes RGBA and is told whether the alpha means anything)+ out = rf_jxl::encode(w, h, rgba, !solid, options.quality.clamp(1, 100) as f32).map_err(|e| anyhow::anyhow!("JPEG XL: {e:?}"))?+ }+ PictureFormat::Bmp => image::codecs::bmp::BmpEncoder::new(&mut out).write_image(&pixels, w, h, color)?,+ PictureFormat::Tiff => {+ // (the TIFF writer goes back to patch offsets: it needs a seekable sink)+ let mut sink = Cursor::new(Vec::new());+ image::codecs::tiff::TiffEncoder::new(&mut sink).write_image(&pixels, w, h, color)?;+ out = sink.into_inner();+ }+ PictureFormat::Gif => image::codecs::gif::GifEncoder::new(&mut out).encode(&pixels, w, h, color)?,+ PictureFormat::Ico => image::codecs::ico::IcoEncoder::new(&mut out).write_image(&pixels, w, h, color)?,+ PictureFormat::Qoi => image::codecs::qoi::QoiEncoder::new(&mut out).write_image(&pixels, w, h, color)?,+ }+ ensure!(!out.is_empty(), "the {} encoder wrote nothing", format.label());+ Ok(out)+}++/// The name a converted file is first tried under: the source's name with the target's extension.+pub fn target_name(source: &Path, ext: &str) -> String {+ let stem = source.file_stem().map(|s| s.to_string_lossy().into_owned()).filter(|s| !s.is_empty()).unwrap_or_else(|| "file".into());+ format!("{stem}.{ext}")+}++/// Writes `bytes` as a NEW file in `dir`, named `name`, or `name (2)`, `name (3)`... when that is taken (the number goes before the+/// extension). Never replaces a file: the name is taken with create-new, so two conversions running at once cannot pick the same+/// one, and a file that appears between the look and the write is not written over. A write that fails leaves no half file.+pub fn write_new(dir: &Path, name: &str, bytes: &[u8]) -> std::io::Result<PathBuf> {+ let (stem, ext) = match name.rfind('.') {+ Some(i) if i > 0 => (&name[..i], &name[i..]),+ _ => (name, ""),+ };+ for n in 1u32.. {+ let path = if n == 1 { dir.join(name) } else { dir.join(format!("{stem} ({n}){ext}")) };+ match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) {+ Ok(mut file) => {+ if let Err(e) = file.write_all(bytes).and_then(|_| file.flush()) {+ drop(file);+ let _ = std::fs::remove_file(&path);+ return Err(e);+ }+ return Ok(path);+ }+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,+ Err(e) => return Err(e),+ }+ }+ unreachable!("the loop over names only ends by returning")+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A picture with a gradient, and a see-through quarter when `alpha`.+ fn sample(w: u32, h: u32, alpha: bool) -> Vec<u8> {+ let mut v = Vec::with_capacity((w * h * 4) as usize);+ for y in 0..h {+ for x in 0..w {+ let a = if alpha && x < w / 2 && y < h / 2 { 0 } else { 255 };+ v.extend_from_slice(&[(x * 255 / w.max(1)) as u8, (y * 255 / h.max(1)) as u8, 128, a]);+ }+ }+ v+ }++ fn tmp(name: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("rf-convert-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+ }++ #[test]+ fn a_selection_gets_targets_only_when_every_file_is_a_picture() {+ assert!(picture_targets([]).is_empty());+ assert!(picture_targets(["png", "txt"]).is_empty(), "one file that is no picture: no entry");+ assert!(picture_targets(["arw"]).is_empty(), "camera RAW is not taken yet");+ let mixed = picture_targets(["png", "jpg", "heic"]);+ assert_eq!(mixed, PictureFormat::ALL);+ }++ #[test]+ fn the_format_every_file_already_is_is_not_offered() {+ let t = picture_targets(["jpg", "jpeg", "jfif"]);+ assert!(!t.contains(&PictureFormat::Jpeg));+ assert_eq!(t.len(), PictureFormat::ALL.len() - 1);+ // a format that is no target (HEIC) takes nothing away+ assert_eq!(picture_targets(["heic", "heic"]), PictureFormat::ALL);+ // two different ones: both stay+ assert!(picture_targets(["png", "jpg"]).contains(&PictureFormat::Png));+ }++ #[test]+ fn every_target_is_written_and_read_back_at_its_size() {+ let (w, h) = (40, 24);+ let rgba = sample(w, h, true);+ for f in PictureFormat::ALL {+ let bytes = encode_picture(Picture { width: w, height: h, rgba: &rgba }, f, &PictureOptions::default()).unwrap_or_else(|e| panic!("{}: {e:#}", f.label()));+ if f == PictureFormat::Jxl {+ let img = jxl_oxide::JxlImage::builder().read(Cursor::new(&bytes)).expect("our JPEG XL file opens in the reference decoder");+ assert_eq!((img.width(), img.height()), (w, h));+ continue;+ }+ let back = image::load_from_memory(&bytes).unwrap_or_else(|e| panic!("{} does not read back: {e}", f.label()));+ assert_eq!((back.width(), back.height()), (w, h), "{}", f.label());+ let px = back.to_rgba8();+ // the see-through corner stays see-through where the format can; on white where it cannot+ let corner = px.get_pixel(2, 2).0;+ if f.keeps_transparency() {+ assert_eq!(corner[3], 0, "{}", f.label());+ } else {+ assert_eq!(corner[3], 255, "{}", f.label());+ assert!(corner[..3].iter().all(|c| *c > 240), "{}: {corner:?} is not the white background", f.label());+ }+ }+ }++ #[test]+ fn the_formats_without_loss_give_the_same_pixels_back() {+ let (w, h) = (33, 17);+ let rgba = sample(w, h, false);+ for f in [PictureFormat::Png, PictureFormat::Webp, PictureFormat::Bmp, PictureFormat::Tiff, PictureFormat::Qoi] {+ let bytes = encode_picture(Picture { width: w, height: h, rgba: &rgba }, f, &PictureOptions::default()).unwrap();+ assert_eq!(image::load_from_memory(&bytes).unwrap().to_rgba8().into_raw(), rgba, "{}", f.label());+ }+ }++ #[test]+ fn a_picture_is_fitted_into_what_was_asked_for_and_what_the_format_allows() {+ assert_eq!(fitted(4000, 3000, 2000), (2000, 1500));+ assert_eq!(fitted(100, 50, 2000), (100, 50), "never made bigger");+ assert_eq!(fitted(10_000, 1, 100), (100, 1), "never zero on a side");+ let (w, h) = (600, 300);+ let rgba = sample(w, h, false);+ let ico = encode_picture(Picture { width: w, height: h, rgba: &rgba }, PictureFormat::Ico, &PictureOptions::default()).unwrap();+ let back = image::load_from_memory(&ico).unwrap();+ assert_eq!((back.width(), back.height()), (256, 128), "an icon file holds 256 pixels at most");+ let small = encode_picture(Picture { width: w, height: h, rgba: &rgba }, PictureFormat::Png, &PictureOptions { max_side: Some(60), ..Default::default() }).unwrap();+ let back = image::load_from_memory(&small).unwrap();+ assert_eq!((back.width(), back.height()), (60, 30));+ }++ #[test]+ fn a_bigger_photo_goes_through_our_jpeg_xl_encoder() {+ // (rf-jxl was made for thumbnails: a picture of several groups each way is the case to hold it to)+ let (w, h) = (1500, 1100);+ let rgba = sample(w, h, false);+ let bytes = encode_picture(Picture { width: w, height: h, rgba: &rgba }, PictureFormat::Jxl, &PictureOptions::default()).unwrap();+ let img = jxl_oxide::JxlImage::builder().read(Cursor::new(&bytes)).unwrap();+ assert_eq!((img.width(), img.height()), (w, h));+ let frame = img.render_frame(0).expect("the reference decoder renders it");+ let fb = frame.image_all_channels();+ let buf = fb.buf();+ let ch = fb.channels();+ // the gradient comes back close: red rises along x, green along y+ let at = |x: usize, y: usize, c: usize| buf[(y * w as usize + x) * ch + c];+ assert!((at(1400, 10, 0) - at(100, 10, 0)) > 0.5, "red rises along the row");+ assert!((at(10, 1000, 1) - at(10, 100, 1)) > 0.5, "green rises down the column");+ }++ /// How long each target takes for a photo of a camera's size, and how big the file is:+ /// `cargo test -p rf-convert --release -- --ignored --nocapture a_24_megapixel`+ #[test]+ #[ignore = "a measurement: a few seconds in a release build, minutes in a debug one"]+ fn a_24_megapixel_photo_in_every_target() {+ let (w, h) = (6000u32, 4000u32);+ // a gradient with fine noise on it, so that the encoders have a photo's kind of work+ let mut rgba = Vec::with_capacity((w * h * 4) as usize);+ let mut seed = 0x2545_F491u32;+ for y in 0..h {+ for x in 0..w {+ seed ^= seed << 13;+ seed ^= seed >> 17;+ seed ^= seed << 5;+ let n = (seed & 15) as u32;+ rgba.extend_from_slice(&[((x * 240 / w) + n) as u8, ((y * 240 / h) + n) as u8, (((x + y) * 120 / (w + h)) + n) as u8, 255]);+ }+ }+ for f in PictureFormat::ALL {+ let t = std::time::Instant::now();+ let bytes = encode_picture(Picture { width: w, height: h, rgba: &rgba }, f, &PictureOptions::default()).unwrap();+ println!("{:<8} {:>7.0} ms {:>8.1} MB", f.label(), t.elapsed().as_secs_f64() * 1000.0, bytes.len() as f64 / 1_048_576.0);+ }+ }++ #[test]+ fn wrong_data_is_refused_not_written() {+ let bad = Picture { width: 10, height: 10, rgba: &[0u8; 12] };+ assert!(encode_picture(bad, PictureFormat::Png, &PictureOptions::default()).is_err());+ let empty = Picture { width: 0, height: 10, rgba: &[] };+ assert!(encode_picture(empty, PictureFormat::Png, &PictureOptions::default()).is_err());+ }++ #[test]+ fn a_file_is_never_replaced_the_name_counts_up() {+ let d = tmp("names");+ std::fs::write(d.join("photo.png"), b"the user's own file").unwrap();+ let a = write_new(&d, "photo.png", b"one").unwrap();+ let b = write_new(&d, "photo.png", b"two").unwrap();+ assert_eq!(a.file_name().unwrap(), "photo (2).png");+ assert_eq!(b.file_name().unwrap(), "photo (3).png");+ assert_eq!(std::fs::read(d.join("photo.png")).unwrap(), b"the user's own file");+ assert_eq!(std::fs::read(&b).unwrap(), b"two");+ // a name with no extension, and one that begins with a dot+ std::fs::write(d.join("LICENSE"), b"x").unwrap();+ assert_eq!(write_new(&d, "LICENSE", b"y").unwrap().file_name().unwrap(), "LICENSE (2)");+ std::fs::write(d.join(".env"), b"x").unwrap();+ assert_eq!(write_new(&d, ".env", b"y").unwrap().file_name().unwrap(), ".env (2)");+ let _ = std::fs::remove_dir_all(&d);+ }++ #[test]+ fn the_target_name_is_the_sources_name_with_the_new_extension() {+ assert_eq!(target_name(Path::new(r"C:\p\IMG_0001.HEIC"), "jpg"), "IMG_0001.jpg");+ assert_eq!(target_name(Path::new("a.b.png"), "webp"), "a.b.webp");+ assert_eq!(ext_of(Path::new(r"C:\p\IMG_0001.HEIC")), "heic");+ assert_eq!(ext_of(Path::new("noext")), "");+ }+}diff --git a/crates/rf-win/Cargo.toml b/crates/rf-win/Cargo.tomlindex 62ac88f1..6ec43fc7 100644--- a/crates/rf-win/Cargo.toml+++ b/crates/rf-win/Cargo.toml@@ -16,6 +16,7 @@ zip.workspace = trueroxmltree = "0.20"encoding_rs = "0.8"rf-core.workspace = true+rf-convert.workspace = true# the pure rules and the real taskbar-window code of hiding Explorer's taskbar (taskbar_hide.rs); the watchdog crate is tiny (std + windows)rf-shellguard = { path = "../rf-shellguard" }anyhow.workspace = truediff --git a/crates/rf-win/src/convert.rs b/crates/rf-win/src/convert.rsnew file mode 100644index 00000000..0f1821f5--- /dev/null+++ b/crates/rf-win/src/convert.rs@@ -0,0 +1,156 @@+//! The converter's work on this system: a picture file is decoded here (the image crate, then Windows' own codecs for HEIC, AVIF+//! and the like: `look::decode`) and written by `rf_convert` next to the original. Nothing is ever replaced, and the shell's+//! thumbnail is never taken for the picture (`decode_whole`).+//!+//! Many files run side by side on a few threads of their own: a decoded 24-megapixel photo is about 100 MB, and one thread a core+//! would ask for gigabytes at once.++use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};++use rayon::prelude::*;+use rf_convert::{Picture, PictureFormat, PictureOptions};++/// One picture: `source` decoded, written as `format` into the folder it is in. Gives the new file.+pub fn picture(source: &Path, format: PictureFormat, options: &PictureOptions) -> anyhow::Result<PathBuf> {+ crate::shell::ensure_com();+ let decoded = crate::look::decode::decode_whole(source)?;+ let (frame, _) = decoded.frames.into_iter().next().ok_or_else(|| anyhow::anyhow!("the picture has no frame"))?;+ let mut rgba = frame.data;+ // (the decoders here give BGRA)+ for px in rgba.chunks_exact_mut(4) {+ px.swap(0, 2);+ }+ let bytes = rf_convert::encode_picture(Picture { width: frame.width, height: frame.height, rgba: &rgba }, format, options)?;+ drop(rgba);+ let dir = source.parent().ok_or_else(|| anyhow::anyhow!("{} has no folder", source.display()))?;+ Ok(rf_convert::write_new(dir, &rf_convert::target_name(source, format.ext()), &bytes)?)+}++/// What became of one file of a batch.+pub struct Outcome {+ pub source: PathBuf,+ /// The new file, or why there is none.+ pub result: anyhow::Result<PathBuf>,+}++/// How many pictures are worked on at once (see the top of this file).+fn workers() -> usize {+ (std::thread::available_parallelism().map_or(2, |n| n.get()) / 2).clamp(1, 6)+}++/// Converts `sources` to `format`, a few at a time. `progress(done, total, name)` is called from the workers as each file ends.+/// `cancel` stops the files not yet begun (one in work is finished: a half-written file is never left). The outcomes come in the+/// order of `sources`; a file that was not begun is not among them.+pub fn pictures(sources: &[PathBuf], format: PictureFormat, options: &PictureOptions, cancel: &AtomicBool, progress: &(dyn Fn(u32, u32, &str) + Sync)) -> Vec<Outcome> {+ let total = sources.len() as u32;+ let done = AtomicU32::new(0);+ let run = || {+ sources+ .par_iter()+ .filter_map(|source| {+ if cancel.load(Ordering::Relaxed) {+ return None;+ }+ // (a decoder that panics on a broken file ends this file, not the batch. Only where panics unwind: the released+ // build aborts on a panic, here as for every picture decoder in the app; the lasting answer is a helper process)+ let result = std::panic::catch_unwind(|| picture(source, format, options)).unwrap_or_else(|_| Err(anyhow::anyhow!("the file could not be read as a picture")));+ let name = source.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ progress(done.fetch_add(1, Ordering::Relaxed) + 1, total, &name);+ Some(Outcome { source: source.clone(), result })+ })+ .collect()+ };+ match rayon::ThreadPoolBuilder::new().num_threads(workers().min(sources.len().max(1))).thread_name(|i| format!("convert-{i}")).build() {+ Ok(pool) => pool.install(run),+ // (no threads to be had: one after the other on this one)+ Err(_) => run(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn data(name: &str) -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data").join(name)+ }++ /// A folder of this test's own with copies of the sample pictures.+ fn folder(name: &str, files: &[&str]) -> (PathBuf, Vec<PathBuf>) {+ let dir = std::env::temp_dir().join(format!("rf-convert-win-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let copies = files+ .iter()+ .map(|f| {+ let to = dir.join(Path::new(f).file_name().unwrap());+ std::fs::copy(data(f), &to).unwrap();+ to+ })+ .collect();+ (dir, copies)+ }++ #[test]+ fn a_picture_is_written_next_to_its_original_and_the_original_stays() {+ let (dir, files) = folder("one", &["look/a.jpg"]);+ let before = std::fs::read(&files[0]).unwrap();+ let out = picture(&files[0], PictureFormat::Png, &PictureOptions::default()).unwrap();+ assert_eq!(out, dir.join("a.png"));+ assert_eq!(std::fs::read(&files[0]).unwrap(), before, "the original is not touched");+ let (a, b) = (image::open(&files[0]).unwrap(), image::open(&out).unwrap());+ assert_eq!((a.width(), a.height()), (b.width(), b.height()), "the whole picture, not a thumbnail of it");+ // a second run keeps the first result+ let again = picture(&files[0], PictureFormat::Png, &PictureOptions::default()).unwrap();+ assert_eq!(again, dir.join("a (2).png"));+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_batch_reports_every_file_and_a_broken_one_does_not_stop_the_rest() {+ let (dir, mut files) = folder("batch", &["look/a.png", "look/a.jpg", "look/a.webp", "look/a.gif"]);+ let broken = dir.join("broken.png");+ std::fs::write(&broken, b"this is no picture").unwrap();+ files.push(broken.clone());+ let calls = AtomicU32::new(0);+ let out = pictures(&files, PictureFormat::Jpeg, &PictureOptions::default(), &AtomicBool::new(false), &|done, total, _| {+ assert!(done >= 1 && done <= total && total == 5);+ calls.fetch_add(1, Ordering::Relaxed);+ });+ assert_eq!(calls.load(Ordering::Relaxed), 5);+ assert_eq!(out.len(), 5);+ for o in &out {+ if o.source == broken {+ assert!(o.result.is_err(), "a file that is no picture is an error, not a small thumbnail");+ } else {+ let made = o.result.as_ref().unwrap_or_else(|e| panic!("{}: {e:#}", o.source.display()));+ assert!(image::open(made).is_ok(), "{}", made.display());+ }+ }+ // a.jpg was a JPEG already: its copy got a number, the original stayed+ assert!(dir.join("a (2).jpg").is_file() || dir.join("a (3).jpg").is_file());+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// The result carries no EXIF, so a photo taken with the camera turned has to be written the way it is seen.+ #[test]+ fn a_photo_the_camera_marked_as_turned_is_written_upright() {+ let (dir, files) = folder("turned", &["look/rot6.jpg"]);+ let stored = image::open(&files[0]).unwrap();+ let out = picture(&files[0], PictureFormat::Png, &PictureOptions::default()).unwrap();+ let made = image::open(&out).unwrap();+ assert_ne!(stored.width(), stored.height(), "the sample has to be oblong for this to say anything");+ assert_eq!((made.width(), made.height()), (stored.height(), stored.width()), "orientation 6 is a quarter turn");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_cancelled_batch_begins_nothing() {+ let (dir, files) = folder("cancel", &["look/a.png", "look/a.jpg"]);+ let out = pictures(&files, PictureFormat::Bmp, &PictureOptions::default(), &AtomicBool::new(true), &|_, _, _| panic!("nothing was to run"));+ assert!(out.is_empty());+ assert!(!dir.join("a.bmp").exists());+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/crates/rf-win/src/lib.rs b/crates/rf-win/src/lib.rsindex 3d4ac018..5229285a 100644--- a/crates/rf-win/src/lib.rs+++ b/crates/rf-win/src/lib.rs@@ -106,6 +106,7 @@ pub mod sysstatus;pub mod shortcut;pub mod internet_shortcut;pub mod app_icon;+pub mod convert;pub mod scrollbars;pub mod sendto;pub mod startup;diff --git a/crates/rf-win/src/look/decode.rs b/crates/rf-win/src/look/decode.rsindex 3726e8c8..fa81a366 100644--- a/crates/rf-win/src/look/decode.rs+++ b/crates/rf-win/src/look/decode.rs@@ -466,6 +466,13 @@ pub fn decode_full(path: &Path, max_side: u32) -> anyhow::Result<Decoded> {decode_full_with_orientation(path, max_side, None, Some(crate::thumbs::Kind::Thumbnail))}+/// The picture of `path` at its own size, for the converter: the same decoders as [`decode_full`], but never the shell's thumbnail+/// or icon in its place. A file nothing here can decode is an error: written out as a small thumbnail it would look like a+/// conversion that worked.+pub fn decode_whole(path: &Path) -> anyhow::Result<Decoded> {+ decode_full_with_orientation(path, u32::MAX, None, None)+}+pub fn decode_picture(path: &Path, max_side: u32) -> anyhow::Result<Decoded> {decode_full_with_orientation(path, max_side, None, Some(crate::thumbs::Kind::ThumbnailOnly))}