From 309963c7b37da65457d5646f05d11fcc9ee5c29f Mon Sep 17 00:00:00 2001 From: qiqi Date: Mon, 30 Nov 2026 17:06:01 +0800 Subject: [PATCH] =?UTF-8?q?feat(perf):=20v3.26.123=20=E7=BC=A9=E7=95=A5?= =?UTF-8?q?=E5=9B=BE=E6=94=B9=E7=94=B1=E5=8E=9F=E7=94=9F=E7=94=9F=E6=88=90?= =?UTF-8?q?=EF=BC=88webview=20=E4=B8=8D=E5=86=8D=E8=A7=A3=E7=A0=81=204K=20?= =?UTF-8?q?=E5=8E=9F=E5=9B=BE=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 16 ++++++ app.js | 14 +++++ package.json | 2 +- src-tauri/Cargo.lock | 33 +++++++++++- src-tauri/Cargo.toml | 4 +- src-tauri/src/lib.rs | 108 ++++++++++++++++++++++++++++++++++++- src-tauri/tauri.conf.json | 2 +- src/image-display-thumb.js | 16 +++++- src/storage-file.js | 39 +++++++++++--- 9 files changed, 220 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a9a6c0..1cbce8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,22 @@ > 3. 核验正式地址版本 → 之后才移动 `stable` / `stable-verified-<日期>` 标签、更新本 CHANGELOG、写 GitHub Release(`gh release create`)。 > 测试发现问题 → 改 → 再 `deploy:test`,正式环境不受影响。回滚点 `git reset --hard stable`。 +## v3.26.123(2026-11-30)根治:缩略图改由原生生成,webview 不再解码 4K 原图 + +mac 实测 WebContent 进程 1GB+(整棵进程树 1.5~1.9GB),而画布只有 100 多张图、我们自己的结构只占 9~37MB。根因链: + +1. WebKit **忽略 createImageBitmap 的 resize 选项**(Chromium 支持)⇒ JS 生成一张缩略图要把 2016×2688 的原图整幅解码(≈21MB); +2. WebKit 的解码图片缓存不像 Chromium 那样随 img 移除就释放 ⇒ 100 多张 = GB 级且长时间不回落; +3. WKWebView 没有 performance.memory ⇒ 护栏在 mac 上整块失效(v3.26.122 已修)。 + +本轮把「生成缩略图」整个搬到原生侧(纯 Rust image crate,mac/win 同一份代码): + +- 新增 Tauri 命令 img_thumbs(src, jobs[{base,max}]):按目标尺寸解码(Lanczos3)/编码(不透明→JPEG q82,有透明→PNG)后写盘, + 返回 {path,w,h,bytes}。整条链里 webview 只接触几十 KB 的小图,**原图永远不会被 WebKit 解码**。 +- storage-file 新增 makeDisplayThumb(hash, blobKey, max):有现成 tier 直接读;没有就调原生生成。 +- 缩略图队列优先走原生(runNative),失败才退回原来的 JS 解码路径(网页版行为不变)。 +- 附带:Cargo 的 image 依赖补 jpeg/gif/webp/bmp/tiff 特性;新增自测(2000×1500→512×384 jpg、带 alpha→256 png 通过)。 + ## v3.26.122(2026-11-30)修 mac 上内存护栏整块失效(mac/win 策略差异) 用户对比两端诊断数据发现「mac 与 win 的内存策略不同」。查实三条: diff --git a/app.js b/app.js index 78453b2..9151001 100644 --- a/app.js +++ b/app.js @@ -4986,6 +4986,18 @@ const tbCenterSeed = (type, refs) => { } // 缩略图队列(v3.25.67):并发上限 + 空闲启动,逻辑在 src/image-display-thumb.js + // v3.26.123:原生缩略图入口(桌面端)。key 形如 ref:b: ⇒ 让 Rust 按目标尺寸 + // 解码/缩放/编码,返回 objectURL;失败返回 ''(调用方退回 JS 解码路径)。 + function wNativeThumb (key, max) { + const F = wStoreMod() + if (!F || typeof F.makeDisplayThumb !== 'function') return Promise.resolve('') + const m = /^ref:b:(.+)$/.exec(String(key || '')) + if (!m) return Promise.resolve('') + return Promise.resolve(wSha256(String(key))) + .then((hex) => F.makeDisplayThumb(String(hex).slice(0, 16), m[1], max)) + .then((r) => (r && r.url) || '') + .catch(() => '') + } const ThumbGen = (function () { const M = (typeof window !== 'undefined') ? window.IWBImageDisplayThumb : null if (!M || typeof M.create !== 'function') return null @@ -4993,6 +5005,7 @@ const tbCenterSeed = (type, refs) => { return M.create({ max: DISPLAY_THUMB_MAX, cacheMax: DISPLAY_THUMB_CACHE_MAX, + nativeThumb: wNativeThumb, cache: displayThumbs, pending: displayThumbPending, concurrency: 2, // v3.26.118:4 → 2。每次「图库进一张图」的解码尖峰减半(用户实测:一进图就冒一下) @@ -5010,6 +5023,7 @@ const tbCenterSeed = (type, refs) => { return M.create({ max: DISPLAY_THUMB_SMALL, cacheMax: DISPLAY_THUMB_SMALL_CACHE_MAX, + nativeThumb: wNativeThumb, cache: displayThumbsSm, pending: displayThumbSmPending, concurrency: 2, diff --git a/package.json b/package.json index 72aec36..60e9342 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "image-workbench-web", "private": true, - "version": "3.26.122", + "version": "3.26.123", "description": "Browser-based node canvas image workbench", "scripts": { "build": "node scripts/build.js && node scripts/copy-plugins.js", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 285e417..ac75bd4 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -556,6 +556,12 @@ dependencies = [ "error-code", ] +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + [[package]] name = "combine" version = "4.6.9" @@ -1486,6 +1492,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + [[package]] name = "gio" version = "0.18.4" @@ -1975,15 +1991,30 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" dependencies = [ "bytemuck", "byteorder-lite", + "color_quant", + "gif", + "image-webp", "moxcms", "num-traits", "png", "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", ] [[package]] name = "image-workbench" -version = "3.26.121" +version = "3.26.122" dependencies = [ "arboard", "base64 0.22.1", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 167f41f..85f9346 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "image-workbench" -version = "3.26.122" +version = "3.26.123" description = "无限画布 · 生图工作台桌面版" authors = ["malongan"] license = "" @@ -36,7 +36,7 @@ tauri-plugin-updater = "2" tauri-plugin-single-instance = "2" tauri-plugin-notification = "2" arboard = "3" -image = { version = "0.25", default-features = false, features = ["png"] } +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "tiff"] } base64 = "0.22" # 画布内嵌网页的圆角(2026-11-19):WKWebView 是矩形,要给它 backing layer 设 diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 56d4eab..7638c92 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -224,6 +224,73 @@ fn build_tray(app: &AppHandle) -> tauri::Result<()> { // 把「资料目录」加进本次运行的 fs scope。 // 为什么需要它:tauri-plugin-fs 的路径白名单是**运行时**的,重启就没了;而资料目录是用户 // 在设置里选的、存在应用配置里 ⇒ 启动时由这里重新授权一次,之后 fs 插件的读写才允许。 +// ── 原生缩略图(v3.26.123)─────────────────────────────────────────────── +// 为什么搬到 Rust:WebKit 忽略 createImageBitmap 的 resize 选项,JS 生成缩略图时必须先把 +// 4K 原图整幅解码(2016×2688 ≈ 21MB/张),100 张就是 GB 级且 WebKit 迟迟不回收 —— 这是 +// mac 端 1.8GB 的主因。这里用纯 Rust 的 image crate 在原生侧按目标尺寸解码/缩放/编码, +// webview 只拿到几十 KB 的小图,原图永不进入 WebKit 的图片缓存。同一份代码 mac/win 共用。 +#[derive(serde::Deserialize)] +struct ThumbJob { + /// 目标路径不含扩展名;由这里按是否有透明通道决定写 .png 还是 .jpg + base: String, + max: u32, +} + +fn do_thumbs(src: &str, jobs: &[ThumbJob]) -> Result { + use image::imageops::FilterType; + use image::ImageEncoder; + let img = image::open(src).map_err(|e| format!("open: {e}"))?; + let (w0, h0) = (img.width().max(1), img.height().max(1)); + let mut out: Vec = Vec::new(); + for j in jobs { + let max = j.max.max(16); + let scale = (max as f32 / w0 as f32).min(max as f32 / h0 as f32); + let (nw, nh) = if scale < 1.0 { + ( + ((w0 as f32) * scale).round() as u32, + ((h0 as f32) * scale).round() as u32, + ) + } else { + (w0, h0) + }; + let nw = nw.max(1); + let nh = nh.max(1); + let resized = if scale < 1.0 { + img.resize_exact(nw, nh, FilterType::Lanczos3) + } else { + img.clone() + }; + let has_alpha = resized.color().has_alpha(); + let path = format!("{}.{}", j.base, if has_alpha { "png" } else { "jpg" }); + let bytes: usize = if has_alpha { + let rgba = resized.to_rgba8(); + let mut buf: Vec = Vec::new(); + image::codecs::png::PngEncoder::new(&mut buf) + .write_image(rgba.as_raw(), nw, nh, image::ExtendedColorType::Rgba8) + .map_err(|e| format!("png: {e}"))?; + std::fs::write(&path, &buf).map_err(|e| format!("write: {e}"))?; + buf.len() + } else { + let rgb = resized.to_rgb8(); + let f = std::fs::File::create(&path).map_err(|e| format!("create: {e}"))?; + let mut wr = std::io::BufWriter::new(f); + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut wr, 82) + .encode(rgb.as_raw(), nw, nh, image::ExtendedColorType::Rgb8) + .map_err(|e| format!("jpeg: {e}"))?; + std::fs::metadata(&path).map(|m| m.len() as usize).unwrap_or(0) + }; + out.push(serde_json::json!({ "path": path, "w": nw, "h": nh, "bytes": bytes })); + } + Ok(serde_json::json!({ "ok": true, "files": out })) +} + +#[tauri::command] +async fn img_thumbs(src: String, jobs: Vec) -> Result { + tauri::async_runtime::spawn_blocking(move || do_thumbs(&src, &jobs)) + .await + .map_err(|e| e.to_string())? +} + /// 本进程及其全部子进程的常驻内存合计(MB)。 /// 为什么要它:WebView2 的渲染进程/GPU 进程是独立进程,app_memory_mb 只看自己, /// 永远报不出「任务管理器里那一栏」,导致诊断页与真实占用差 2~4 倍、无法定位。前端每 15s 采一次。 @@ -1735,7 +1802,8 @@ pub fn run() { browser_bookmarks_menu, notify_desktop, app_memory_mb, - app_memory_tree_mb + app_memory_tree_mb, + img_thumbs ]) .setup(|app| { if cfg!(debug_assertions) { @@ -1890,3 +1958,41 @@ mod clip_tests { } } } + +#[cfg(test)] +mod thumb_tests { + use super::*; + + #[test] + fn makes_smaller_jpeg_and_png() { + let dir = std::env::temp_dir().join("iwb_thumb_test"); + let _ = std::fs::create_dir_all(&dir); + let src = dir.join("src.png"); + // 2000x1500 不透明图 → 期望 jpg + let mut img = image::RgbImage::new(2000, 1500); + for (x, y, p) in img.enumerate_pixels_mut() { + *p = image::Rgb([(x % 255) as u8, (y % 255) as u8, 128]); + } + img.save(&src).unwrap(); + let base = dir.join("out_512").to_string_lossy().to_string(); + let r = do_thumbs(src.to_str().unwrap(), &[ThumbJob { base, max: 512 }]).unwrap(); + let f = &r["files"][0]; + assert_eq!(f["w"], 512); + assert_eq!(f["h"], 384); + assert!(f["path"].as_str().unwrap().ends_with(".jpg")); + assert!(f["bytes"].as_u64().unwrap() > 0); + + // 带透明的图 → 期望 png + let src2 = dir.join("src_alpha.png"); + let mut img2 = image::RgbaImage::new(800, 400); + for (x, _y, p) in img2.enumerate_pixels_mut() { + *p = image::Rgba([(x % 255) as u8, 0, 0, (x % 200) as u8]); + } + img2.save(&src2).unwrap(); + let base2 = dir.join("out_256").to_string_lossy().to_string(); + let r2 = do_thumbs(src2.to_str().unwrap(), &[ThumbJob { base: base2, max: 256 }]).unwrap(); + let f2 = &r2["files"][0]; + assert_eq!(f2["w"], 256); + assert!(f2["path"].as_str().unwrap().ends_with(".png")); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 3ee7b2a..27d93d5 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "image-workbench", - "version": "3.26.122", + "version": "3.26.123", "identifier": "com.malongan.imageworkbench", "build": { "frontendDist": "../dist", diff --git a/src/image-display-thumb.js b/src/image-display-thumb.js index ad35794..255b684 100644 --- a/src/image-display-thumb.js +++ b/src/image-display-thumb.js @@ -128,9 +128,23 @@ img.src = v }) + // v3.26.123:优先让**原生**生成缩略图(Rust image crate)。桌面端有这条路时, + // webview 永远不解码原图 —— WebKit 忽略 createImageBitmap 的 resize 选项, + // 一解码就是 21MB/张,100 张直接把进程顶到 GB 级(mac 实测 1.8GB)。 + const nativeThumb = (typeof o.nativeThumb === 'function') ? o.nativeThumb : null + const runNative = async (key) => { + if (!nativeThumb) return false + let url = '' + try { url = await nativeThumb(key, max) } catch (e) { return false } + if (!url || typeof url !== 'string') return false + remember(key, url) + return true + } + const run = async (key, v) => { let ok = false - try { ok = await runBitmap(key, v) } catch (e) { ok = false } + try { ok = await runNative(key) } catch (e) { ok = false } + if (!ok) { try { ok = await runBitmap(key, v) } catch (e) { ok = false } } if (!ok) { try { ok = await runImg(key, v) } catch (e2) { ok = false } } if (ok) bump() return ok diff --git a/src/storage-file.js b/src/storage-file.js index cacf38d..3064504 100644 --- a/src/storage-file.js +++ b/src/storage-file.js @@ -1101,8 +1101,8 @@ return '' } - async function thumbFileOf (hash) { - const base = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_768') + async function thumbFileOf (hash, max) { + const base = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_' + (Math.max(64, Number(max) || 768))) for (const ext of ['.webp', '.jpg']) { try { if (await fs().exists(base + ext)) return { path: base + ext, mime: ext === '.webp' ? 'image/webp' : 'image/jpeg' } } catch (e) { /* ignore */ } } @@ -1120,17 +1120,18 @@ } // v3.25.73:缩略图以 Blob + objectURL 交给显示层(避免 dataURL 常驻 JS 堆) const thumbUrlCache = new Map() // hash → objectURL - async function readDisplayThumbUrl(hash) { + async function readDisplayThumbUrl(hash, max) { try { if (!enabled() || !dir || !hash) return '' - const hit = thumbUrlCache.get(String(hash)) + const ck = String(hash) + '_' + (Math.max(64, Number(max) || 768)) + const hit = thumbUrlCache.get(ck) if (hit) return hit - const f = await thumbFileOf(hash) + const f = await thumbFileOf(hash, max) if (!f) return '' const u8 = await fs().readFile(f.path) if (!u8 || !u8.length) return '' const url = URL.createObjectURL(new Blob([u8], { type: sniffMime(u8) || f.mime })) - thumbUrlCache.set(String(hash), url) + thumbUrlCache.set(ck, url) // 不 revoke:这个 URL 可能正在被画布上的 使用,撤销会变成黑块/破图。 if (thumbUrlCache.size > 600) { const k = thumbUrlCache.keys().next().value; try { thumbUrlCache.delete(k) } catch (e) { /* ignore */ } } return url @@ -1205,6 +1206,30 @@ return { thumbs: a, legacy: b } } + // v3.26.123:原生缩略图。有就返回,没有就让 Rust 按目标尺寸解码/缩放/编码后写盘,再读成 objectURL。 + // 关键:整条链里 webview 只接触几十 KB 的小图,4K 原图永远不会被 WebKit 解码(mac 端 GB 级占用的根源)。 + async function makeDisplayThumb (hash, srcKey, max) { + try { + if (!enabled() || !dir || !hash || !srcKey) return null + const m = Math.max(64, Number(max) || 768) + const have = await thumbFileOf(hash, m) + if (have) return { url: await readDisplayThumbUrl(hash, m), path: have.path, cached: true } + const a = assets[String(srcKey)] + if (!a) return null + const src = await join(dir, a.f) + const base = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_' + m) + try { await fs().mkdir(await join(dir, IMG_DIR, 'thumbs'), { recursive: true }) } catch (e) { /* ignore */ } + const T = (typeof window !== 'undefined') ? window.__TAURI__ : null + const inv = T && T.core && T.core.invoke + if (typeof inv !== 'function') return null + const r = await inv('img_thumbs', { src, jobs: [{ base, max: m }] }) + if (!r || !r.ok || !Array.isArray(r.files) || !r.files.length) return null + const url = await readDisplayThumbUrl(hash, m) + if (!url) return null + return { url, path: r.files[0].path, w: r.files[0].w, h: r.files[0].h, bytes: r.files[0].bytes, cached: false } + } catch (e) { return null } + } + async function writeDisplayThumbBlob(hash, blob) { try { if (!enabled() || !dir || !hash || !blob) return false @@ -1423,7 +1448,7 @@ enabled, ready: init, flush, // 供其它模块把诊断写进 _boot.log(v3.26.109) logLine: (m) => blog(m), - runtime, pickDir, switchTo, migrateTo, deleteImageBytes, deleteGalleryBytesFor, galleryAudit, gcImages, rotateTrash, galleryThumb, readDisplayThumb, readDisplayThumbUrl, writeDisplayThumb, writeDisplayThumbBlob, pruneThumbs, cleanupLegacy, maintain, + runtime, pickDir, switchTo, migrateTo, deleteImageBytes, deleteGalleryBytesFor, galleryAudit, gcImages, rotateTrash, galleryThumb, readDisplayThumb, readDisplayThumbUrl, makeDisplayThumb, writeDisplayThumb, writeDisplayThumbBlob, pruneThumbs, cleanupLegacy, maintain, plugins: { manifest: pluginManifest, read: pluginRead, write: pluginWrite, remove: pluginRemove, dir: pluginDir, listLocal: pluginListLocal, listDirs: pluginListDirs, readFile: pluginReadFile, writeFile: pluginWriteFile, writeBinary: pluginWriteBinary, mkdir: pluginMkdir, removeDir: pluginRemoveDir, renameDir: pluginRenameDir, existsDir: pluginExistsDir }, pluginData: { read: pluginDataRead, write: pluginDataWrite, remove: pluginDataRemove, list: pluginDataList }, pluginFiles: { put: pluginFilePut, get: pluginFileGet, list: pluginFileList, remove: pluginFileRemove, stat: pluginFileStat, dir: pluginFilesDir, readBytes: pluginFileReadBytes, listAll: pluginFilesListAll },