Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

bug fixes

sora9eddcbdc35e5
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 36b139c..1947063 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -42,8 +42,11 @@ rusqlite = { version = "0.32", features = ["bundled", "serialize"] }
windows-sys = { version = "0.59", features = [
"Win32_Foundation",
"Win32_Graphics_Gdi",
+ "Win32_Storage_FileSystem",
"Win32_System_LibraryLoader",
"Win32_System_Performance",
+ "Win32_System_Registry",
+ "Win32_System_SystemInformation",
"Win32_System_Threading",
"Win32_UI_HiDpi",
"Win32_UI_Input_Pointer",
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index dc6b3dd..805db7f 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -5,6 +5,7 @@ mod raster_ops;
mod recovery;
mod scratch_disk;
mod server;
+mod system_perf;
mod tablet_input;
mod timelapse;
@@ -324,7 +325,7 @@ async fn save_undo_tile_cache(request: tauri::ipc::Request<'_>) -> Result<(), St
}
let safe_session = sanitize_id(&session_id);
let safe_state = sanitize_id(&state_id);
- let temp_dir = std::env::temp_dir().join("inkstudio_undo").join(&safe_session);
+ let temp_dir = system_perf::get_undo_cache_base_dir().join(&safe_session);
tokio::fs::create_dir_all(&temp_dir)
.await
.map_err(|e| e.to_string())?;
@@ -343,8 +344,7 @@ async fn load_undo_tile_cache(
let state_id = header_str(&request, "x-state-id")?;
let safe_session = sanitize_id(&session_id);
let safe_state = sanitize_id(&state_id);
- let file_path = std::env::temp_dir()
- .join("inkstudio_undo")
+ let file_path = system_perf::get_undo_cache_base_dir()
.join(&safe_session)
.join(format!("{}.bin", safe_state));
let data = tokio::fs::read(&file_path)
@@ -356,7 +356,7 @@ async fn load_undo_tile_cache(
#[tauri::command]
async fn clear_undo_tile_cache(session_id: String) -> Result<(), String> {
let safe_session = sanitize_id(&session_id);
- let temp_dir = std::env::temp_dir().join("inkstudio_undo").join(&safe_session);
+ let temp_dir = system_perf::get_undo_cache_base_dir().join(&safe_session);
if temp_dir.exists() {
let _ = tokio::fs::remove_dir_all(&temp_dir).await;
}
@@ -599,20 +599,22 @@ async fn native_apply_filter(
return Err("Filter payload exceeds raster safety ceiling".to_string());
}
let owned = body.to_vec();
- let out = tokio::task::spawn_blocking(move || match filter_type.as_str() {
- "gaussian-blur" => raster_ops::gaussian_blur_rgba(&owned, width, height, p_a),
- "motion-blur" => raster_ops::motion_blur_rgba(&owned, width, height, p_a, p_b),
- "unsharp-mask" => raster_ops::unsharp_mask_rgba(&owned, width, height, p_a, p_b, p_c),
- "film-grain" => raster_ops::film_grain_rgba(
- &owned,
- width,
- height,
- p_a,
- p_b.round().max(1.0) as u32,
- p_c > 0.5,
- p_d,
- ),
- other => Err(format!("Unsupported filter type: {}", other)),
+ let out = tokio::task::spawn_blocking(move || {
+ system_perf::run_on_worker_pool(|| match filter_type.as_str() {
+ "gaussian-blur" => raster_ops::gaussian_blur_rgba(&owned, width, height, p_a),
+ "motion-blur" => raster_ops::motion_blur_rgba(&owned, width, height, p_a, p_b),
+ "unsharp-mask" => raster_ops::unsharp_mask_rgba(&owned, width, height, p_a, p_b, p_c),
+ "film-grain" => raster_ops::film_grain_rgba(
+ &owned,
+ width,
+ height,
+ p_a,
+ p_b.round().max(1.0) as u32,
+ p_c > 0.5,
+ p_d,
+ ),
+ other => Err(format!("Unsupported filter type: {}", other)),
+ })
})
.await
.map_err(|e| format!("Filter worker failed: {}", e))??;
@@ -746,21 +748,23 @@ async fn native_liquify_step(
};
let out = tokio::task::spawn_blocking(move || {
- let src_roi = &owned[..roi_bytes];
- let mut off = roi_bytes;
- let init_opt = if has_init {
- let s = &owned[off..off + roi_bytes];
- off += roi_bytes;
- Some(s)
- } else {
- None
- };
- let mask_opt = if has_mask {
- Some(&owned[off..off + roi_pixels])
- } else {
- None
- };
- raster_ops::liquify_step_rgba(src_roi, init_opt, mask_opt, &params)
+ system_perf::run_on_worker_pool(|| {
+ let src_roi = &owned[..roi_bytes];
+ let mut off = roi_bytes;
+ let init_opt = if has_init {
+ let s = &owned[off..off + roi_bytes];
+ off += roi_bytes;
+ Some(s)
+ } else {
+ None
+ };
+ let mask_opt = if has_mask {
+ Some(&owned[off..off + roi_pixels])
+ } else {
+ None
+ };
+ raster_ops::liquify_step_rgba(src_roi, init_opt, mask_opt, &params)
+ })
})
.await
.map_err(|e| format!("Liquify worker failed: {}", e))??;
@@ -773,7 +777,9 @@ async fn native_compress_tiles_lz4(
request: tauri::ipc::Request<'_>,
) -> Result<tauri::ipc::Response, String> {
let owned = raw_body(&request)?.to_vec();
- let out = tokio::task::spawn_blocking(move || raster_ops::compress_tiles_lz4_batch(&owned))
+ let out = tokio::task::spawn_blocking(move || {
+ system_perf::run_on_worker_pool(|| raster_ops::compress_tiles_lz4_batch(&owned))
+ })
.await
.map_err(|e| format!("LZ4 compress worker failed: {}", e))??;
Ok(tauri::ipc::Response::new(out))
@@ -784,7 +790,9 @@ async fn native_decompress_tiles_lz4(
request: tauri::ipc::Request<'_>,
) -> Result<tauri::ipc::Response, String> {
let owned = raw_body(&request)?.to_vec();
- let out = tokio::task::spawn_blocking(move || raster_ops::decompress_tiles_lz4_batch(&owned))
+ let out = tokio::task::spawn_blocking(move || {
+ system_perf::run_on_worker_pool(|| raster_ops::decompress_tiles_lz4_batch(&owned))
+ })
.await
.map_err(|e| format!("LZ4 decompress worker failed: {}", e))??;
Ok(tauri::ipc::Response::new(out))
@@ -837,15 +845,107 @@ fn tablet_get_status() -> tablet_input::TabletStatus {
tablet_input::get_tablet_status()
}
+#[tauri::command]
+async fn get_system_hardware_info() -> Result<system_perf::SystemHardwareInfo, String> {
+ tokio::task::spawn_blocking(system_perf::collect_system_hardware_info)
+ .await
+ .map_err(|e| format!("Failed to query system hardware info: {}", e))
+}
+
+#[tauri::command]
+async fn get_scratch_disk_usage() -> Result<system_perf::ScratchDiskUsageReport, String> {
+ tokio::task::spawn_blocking(system_perf::collect_scratch_disk_usage)
+ .await
+ .map_err(|e| format!("Failed to query scratch disk usage: {}", e))
+}
+
+#[tauri::command]
+async fn apply_performance_config(
+ config: system_perf::StartupPerformanceConfig,
+) -> Result<system_perf::SystemHardwareInfo, String> {
+ tokio::task::spawn_blocking(move || -> Result<system_perf::SystemHardwareInfo, String> {
+ let validated_dir = system_perf::validate_custom_scratch_dir(&config.scratch_disk_path)?;
+ let saved = system_perf::save_startup_config(system_perf::StartupPerformanceConfig {
+ scratch_disk_path: validated_dir
+ .as_ref()
+ .map(|p| p.to_string_lossy().to_string())
+ .unwrap_or_default(),
+ ..config
+ })?;
+
+ scratch_disk::set_custom_scratch_dir(validated_dir);
+ scratch_disk::set_scratch_compression_enabled(saved.scratch_disk_compression != "none");
+ let _ = system_perf::set_cpu_worker_threads(saved.cpu_worker_threads)?;
+ Ok(system_perf::collect_system_hardware_info())
+ })
+ .await
+ .map_err(|e| format!("Failed to apply performance config: {}", e))?
+}
+
+#[tauri::command]
+async fn purge_unused_scratch_files(active_session_ids: Vec<String>) -> Result<u64, String> {
+ tokio::task::spawn_blocking(move || -> Result<u64, String> {
+ let active_sanitized: HashSet<String> = active_session_ids
+ .iter()
+ .map(|id| sanitize_id(id))
+ .collect();
+ let mut freed: u64 = 0;
+
+ for base in [
+ scratch_disk::get_scratch_base_dir(),
+ system_perf::get_undo_cache_base_dir(),
+ ] {
+ if !base.exists() {
+ continue;
+ }
+ let Ok(entries) = std::fs::read_dir(&base) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if !path.is_dir() {
+ continue;
+ }
+ let name = entry.file_name().to_string_lossy().to_string();
+ if active_sanitized.contains(&name) {
+ continue;
+ }
+ let bytes = system_perf::compute_dir_bytes(&path);
+ if std::fs::remove_dir_all(&path).is_ok() {
+ freed = freed.saturating_add(bytes);
+ }
+ }
+ }
+ Ok(freed)
+ })
+ .await
+ .map_err(|e| format!("Failed to purge unused scratch files: {}", e))?
+}
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
+ // Load persisted desktop performance settings BEFORE WebView2 initializes
+ let startup_perf = system_perf::load_startup_config();
+ if !startup_perf.scratch_disk_path.is_empty() {
+ if let Ok(Some(valid_dir)) =
+ system_perf::validate_custom_scratch_dir(&startup_perf.scratch_disk_path)
+ {
+ scratch_disk::set_custom_scratch_dir(Some(valid_dir));
+ }
+ }
+ scratch_disk::set_scratch_compression_enabled(startup_perf.scratch_disk_compression != "none");
+ if startup_perf.cpu_worker_threads > 0 {
+ let _ = system_perf::set_cpu_worker_threads(startup_perf.cpu_worker_threads);
+ }
+
// Disable Windows 11 WebView2 Shell Handwriting / DirectInk overlay so stylus input on
- // sidebar text fields (e.g. layer rename) never draws ink strokes over the UI.
+ // sidebar text fields (e.g. layer rename) never draws ink strokes over the UI,
+ // and apply user-configured GPU adapter / ANGLE backend flags.
#[cfg(target_os = "windows")]
{
const HANDWRITING_DISABLE_FLAG: &str =
"--disable-features=StylusHandwritingWin,StylusHandwriting,msAbydos,msAbydosHandwritingAttr,msAbydosGestureSupport";
- let merged = match std::env::var("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS") {
+ let mut merged = match std::env::var("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS") {
Ok(existing) if !existing.trim().is_empty() => {
if existing.contains("StylusHandwritingWin") {
existing
@@ -855,6 +955,12 @@ pub fn run() {
}
_ => HANDWRITING_DISABLE_FLAG.to_string(),
};
+ for flag in system_perf::build_webview_perf_args(&startup_perf) {
+ if !merged.contains(&flag) {
+ merged.push(' ');
+ merged.push_str(&flag);
+ }
+ }
std::env::set_var("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", merged);
}
@@ -925,7 +1031,11 @@ pub fn run() {
native_flate_decompress,
tablet_start_input,
tablet_stop_input,
- tablet_get_status
+ tablet_get_status,
+ get_system_hardware_info,
+ get_scratch_disk_usage,
+ apply_performance_config,
+ purge_unused_scratch_files
])
.build(tauri::generate_context!())
.expect("error while building tauri application");
diff --git a/src-tauri/src/scratch_disk.rs b/src-tauri/src/scratch_disk.rs
index 54493ac..2b65c80 100644
--- a/src-tauri/src/scratch_disk.rs
+++ b/src-tauri/src/scratch_disk.rs
@@ -1,7 +1,8 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
-use std::sync::Mutex;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Mutex, RwLock};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt, SeekFrom};
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -36,6 +37,37 @@ static SCRATCH_IO_LOCK: std::sync::LazyLock<tokio::sync::Mutex<()>> =
static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+static CUSTOM_SCRATCH_BASE: std::sync::LazyLock<RwLock<Option<PathBuf>>> =
+ std::sync::LazyLock::new(|| RwLock::new(None));
+
+static SCRATCH_LZ4_ENABLED: AtomicBool = AtomicBool::new(true);
+
+const RAW_TILE_FLAG: u32 = 0x8000_0000;
+const RAW_TILE_LEN_MASK: u32 = 0x7fff_ffff;
+
+pub fn set_custom_scratch_dir(dir: Option<PathBuf>) {
+ if let Ok(mut guard) = CUSTOM_SCRATCH_BASE.write() {
+ *guard = dir;
+ }
+}
+
+pub fn set_scratch_compression_enabled(enabled: bool) {
+ SCRATCH_LZ4_ENABLED.store(enabled, Ordering::Relaxed);
+}
+
+pub fn is_scratch_compression_enabled() -> bool {
+ SCRATCH_LZ4_ENABLED.load(Ordering::Relaxed)
+}
+
+pub fn get_scratch_base_dir() -> PathBuf {
+ if let Ok(guard) = CUSTOM_SCRATCH_BASE.read() {
+ if let Some(custom) = guard.as_ref() {
+ return custom.join("inkstudio_scratch");
+ }
+ }
+ std::env::temp_dir().join("inkstudio_scratch")
+}
+
const MAX_UNCOMPRESSED_TILE_BYTES: usize = 4 * 1024 * 1024; // 4 MB max per 256x256 tile
const MAX_COMPRESSED_TILE_BYTES: u32 = 8 * 1024 * 1024; // 8 MB max compressed payload
const MAX_TILES_PER_BATCH: usize = 4096;
@@ -149,9 +181,7 @@ pub fn unpack_tile_batch(bytes: &[u8]) -> Result<Vec<TileWritePayload>, String>
pub fn get_scratch_root(session_id: &str) -> PathBuf {
let safe_session = sanitize_layer_id(session_id);
- std::env::temp_dir()
- .join("inkstudio_scratch")
- .join(safe_session)
+ get_scratch_base_dir().join(safe_session)
}
fn sanitize_layer_id(layer_id: &str) -> String {
@@ -197,7 +227,9 @@ pub async fn write_tiles(
return Ok(0);
}
- // Validate & LZ4-compress tiles off Tokio async worker threads and BEFORE acquiring SCRATCH_IO_LOCK
+ let use_lz4 = is_scratch_compression_enabled();
+
+ // Validate & optionally LZ4-compress tiles off Tokio async worker threads and BEFORE acquiring SCRATCH_IO_LOCK
let compressed_by_layer = tokio::task::spawn_blocking(move || -> Result<(usize, HashMap<String, Vec<CompressedTileWrite>>), String> {
let mut grouped: HashMap<String, Vec<CompressedTileWrite>> = HashMap::new();
let count = tiles.len();
@@ -205,8 +237,12 @@ pub async fn write_tiles(
if tile.data.len() > MAX_UNCOMPRESSED_TILE_BYTES {
return Err("Tile uncompressed payload exceeds 4 MB safety ceiling".to_string());
}
- let uncompressed_len = tile.data.len() as u32;
- let compressed = lz4_flex::compress_prepend_size(&tile.data);
+ let raw_len = tile.data.len() as u32;
+ let (uncompressed_len, payload) = if use_lz4 {
+ (raw_len, lz4_flex::compress_prepend_size(&tile.data))
+ } else {
+ (raw_len | RAW_TILE_FLAG, tile.data)
+ };
grouped
.entry(tile.layer_id)
.or_default()
@@ -214,7 +250,7 @@ pub async fn write_tiles(
tile_x: tile.tile_x,
tile_y: tile.tile_y,
uncompressed_len,
- compressed,
+ compressed: payload,
});
}
Ok((count, grouped))
@@ -446,14 +482,17 @@ pub async fn read_tile(
}
};
+ let is_raw_tile = (entry.uncompressed_len & RAW_TILE_FLAG) != 0;
+ let logical_uncompressed_len = (entry.uncompressed_len & RAW_TILE_LEN_MASK) as usize;
+
if entry.compressed_len == 0
|| entry.compressed_len > MAX_COMPRESSED_TILE_BYTES
- || (entry.uncompressed_len as usize) > MAX_UNCOMPRESSED_TILE_BYTES
+ || logical_uncompressed_len > MAX_UNCOMPRESSED_TILE_BYTES
{
return Err("Corrupt or oversized tile index entry".to_string());
}
- // 2. Read compressed payload from bucket file
+ // 2. Read payload from bucket file
let safe_name = sanitize_layer_id(layer_id);
let bucket_path = get_scratch_root(session_id).join(format!("bucket_{}.bin", safe_name));
@@ -476,6 +515,10 @@ pub async fn read_tile(
drop(bucket_file);
drop(_io_guard);
+ if is_raw_tile {
+ return Ok(compressed_buf);
+ }
+
if compressed_buf.len() < 4 {
return Err("Corrupt LZ4 tile header".to_string());
}
@@ -572,6 +615,40 @@ mod tests {
assert!(!get_scratch_root(&session_id).exists());
}
+ #[tokio::test]
+ async fn test_scratch_disk_uncompressed_mode_roundtrip() {
+ let session_id = format!(
+ "test_raw_session_{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ );
+ set_scratch_compression_enabled(false);
+ let _ = init_scratch_disk(&session_id).await.expect("init failed");
+ let payload = vec![0x5Au8; 65536];
+ let count = write_tiles(
+ &session_id,
+ vec![TileWritePayload {
+ layer_id: "raw_layer".to_string(),
+ tile_x: 2,
+ tile_y: 3,
+ data: payload.clone(),
+ }],
+ )
+ .await
+ .expect("raw write failed");
+ assert_eq!(count, 1);
+
+ let read_back = read_tile(&session_id, "raw_layer", 2, 3)
+ .await
+ .expect("raw read failed");
+ assert_eq!(read_back, payload);
+
+ set_scratch_compression_enabled(true);
+ clear_scratch_disk(&session_id).await.expect("clear failed");
+ }
+
#[test]
fn test_tile_batch_pack_unpack_roundtrip() {
let tiles = vec![
diff --git a/src-tauri/src/system_perf.rs b/src-tauri/src/system_perf.rs
new file mode 100644
index 0000000..b81bf4e
--- /dev/null
+++ b/src-tauri/src/system_perf.rs
@@ -0,0 +1,810 @@
+use serde::{Deserialize, Serialize};
+use std::collections::HashSet;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, LazyLock, RwLock};
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct GpuAdapterInfo {
+ pub id: String,
+ pub name: String,
+ pub vendor: String,
+ pub vram_mb: u64,
+ pub kind: String, // "discrete" | "integrated" | "software" | "unknown"
+ pub is_primary: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct StartupPerformanceConfig {
+ pub gpu_power_preference: String, // "high-performance" | "low-power" | "default"
+ pub desktop_graphics_api: String, // "auto" | "d3d11" | "vulkan" | "gl" | "warp"
+ pub scratch_disk_path: String,
+ pub scratch_disk_compression: String, // "lz4" | "none"
+ pub cpu_worker_threads: usize, // 0 = auto
+}
+
+impl Default for StartupPerformanceConfig {
+ fn default() -> Self {
+ Self {
+ gpu_power_preference: "high-performance".to_string(),
+ desktop_graphics_api: "auto".to_string(),
+ scratch_disk_path: String::new(),
+ scratch_disk_compression: "lz4".to_string(),
+ cpu_worker_threads: 0,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SystemHardwareInfo {
+ pub total_ram_mb: u64,
+ pub available_ram_mb: u64,
+ pub cpu_logical_cores: usize,
+ pub os_platform: String,
+ pub gpus: Vec<GpuAdapterInfo>,
+ pub scratch_disk_path: String,
+ pub scratch_disk_free_mb: u64,
+ pub scratch_disk_total_mb: u64,
+ pub scratch_disk_used_bytes: u64,
+ pub undo_cache_used_bytes: u64,
+ pub active_cpu_worker_threads: usize,
+ pub startup_config: StartupPerformanceConfig,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ScratchDiskUsageReport {
+ pub scratch_disk_path: String,
+ pub scratch_disk_free_mb: u64,
+ pub scratch_disk_total_mb: u64,
+ pub scratch_disk_used_bytes: u64,
+ pub undo_cache_used_bytes: u64,
+}
+
+// Configurable Rayon worker pool so users can cap CPU thread usage for filters/compression
+struct WorkerPoolState {
+ max_threads: usize,
+ pool: Option<Arc<rayon::ThreadPool>>,
+}
+
+static WORKER_POOL: LazyLock<RwLock<WorkerPoolState>> = LazyLock::new(|| {
+ RwLock::new(WorkerPoolState {
+ max_threads: 0,
+ pool: None,
+ })
+});
+
+pub fn get_cpu_logical_cores() -> usize {
+ std::thread::available_parallelism()
+ .map(|n| n.get())
+ .unwrap_or(4)
+ .max(1)
+}
+
+pub fn get_active_cpu_worker_threads() -> usize {
+ WORKER_POOL
+ .read()
+ .map(|s| s.max_threads)
+ .unwrap_or(0)
+}
+
+pub fn set_cpu_worker_threads(max_threads: usize) -> Result<usize, String> {
+ let cores = get_cpu_logical_cores();
+ let clamped = if max_threads == 0 {
+ 0
+ } else {
+ max_threads.clamp(1, cores.max(64))
+ };
+
+ let new_pool = if clamped > 0 {
+ let built = rayon::ThreadPoolBuilder::new()
+ .num_threads(clamped)
+ .thread_name(|idx| format!("inkstudio-worker-{}", idx))
+ .build()
+ .map_err(|e| format!("Failed to build CPU worker pool: {}", e))?;
+ Some(Arc::new(built))
+ } else {
+ None
+ };
+
+ if let Ok(mut guard) = WORKER_POOL.write() {
+ guard.max_threads = clamped;
+ guard.pool = new_pool;
+ }
+
+ Ok(clamped)
+}
+
+/// Runs a parallel Rayon closure on the user-configured worker pool (or global pool when Auto / 0).
+pub fn run_on_worker_pool<OP, R>(op: OP) -> R
+where
+ OP: FnOnce() -> R + Send,
+ R: Send,
+{
+ let pool_opt = WORKER_POOL
+ .read()
+ .ok()
+ .and_then(|g| g.pool.clone());
+ if let Some(pool) = pool_opt {
+ pool.install(op)
+ } else {
+ op()
+ }
+}
+
+/// Resolves the persistent `performance.json` config path in the app local data directory
+/// so it can be read BEFORE Tauri initializes WebView2.
+pub fn get_startup_config_path() -> PathBuf {
+ #[cfg(target_os = "windows")]
+ {
+ if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {
+ return PathBuf::from(local_app_data)
+ .join("com.inkstudio.app")
+ .join("performance.json");
+ }
+ }
+ #[cfg(target_os = "macos")]
+ {
+ if let Ok(home) = std::env::var("HOME") {
+ return PathBuf::from(home)
+ .join("Library")
+ .join("Application Support")
+ .join("com.inkstudio.app")
+ .join("performance.json");
+ }
+ }
+ #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
+ {
+ if let Ok(xdg) = std::env::var("XDG_DATA_HOME") {
+ if !xdg.trim().is_empty() {
+ return PathBuf::from(xdg)
+ .join("com.inkstudio.app")
+ .join("performance.json");
+ }
+ }
+ if let Ok(home) = std::env::var("HOME") {
+ return PathBuf::from(home)
+ .join(".local")
+ .join("share")
+ .join("com.inkstudio.app")
+ .join("performance.json");
+ }
+ }
+ std::env::temp_dir()
+ .join("inkstudio_config")
+ .join("performance.json")
+}
+
+fn sanitize_startup_config(mut cfg: StartupPerformanceConfig) -> StartupPerformanceConfig {
+ cfg.gpu_power_preference = match cfg.gpu_power_preference.as_str() {
+ "high-performance" | "low-power" | "default" => cfg.gpu_power_preference,
+ _ => "high-performance".to_string(),
+ };
+ cfg.desktop_graphics_api = match cfg.desktop_graphics_api.as_str() {
+ "auto" | "d3d11" | "vulkan" | "gl" | "warp" => cfg.desktop_graphics_api,
+ _ => "auto".to_string(),
+ };
+ cfg.scratch_disk_compression = match cfg.scratch_disk_compression.as_str() {
+ "lz4" | "none" => cfg.scratch_disk_compression,
+ _ => "lz4".to_string(),
+ };
+ if cfg.scratch_disk_path.contains('\0') {
+ cfg.scratch_disk_path.clear();
+ } else {
+ cfg.scratch_disk_path = cfg.scratch_disk_path.trim().to_string();
+ }
+ cfg.cpu_worker_threads = cfg.cpu_worker_threads.min(64);
+ cfg
+}
+
+pub fn load_startup_config() -> StartupPerformanceConfig {
+ let path = get_startup_config_path();
+ let Ok(raw) = std::fs::read_to_string(&path) else {
+ return StartupPerformanceConfig::default();
+ };
+ let parsed = serde_json::from_str::<StartupPerformanceConfig>(&raw).unwrap_or_default();
+ sanitize_startup_config(parsed)
+}
+
+pub fn save_startup_config(cfg: StartupPerformanceConfig) -> Result<StartupPerformanceConfig, String> {
+ let clean = sanitize_startup_config(cfg);
+ let path = get_startup_config_path();
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)
+ .map_err(|e| format!("Failed to create config directory: {}", e))?;
+ }
+ let json = serde_json::to_string_pretty(&clean)
+ .map_err(|e| format!("Failed to serialize performance config: {}", e))?;
+ std::fs::write(&path, json)
+ .map_err(|e| format!("Failed to save performance config: {}", e))?;
+ Ok(clean)
+}
+
+/// Builds Chromium/WebView2 browser arguments from startup performance preferences.
+pub fn build_webview_perf_args(cfg: &StartupPerformanceConfig) -> Vec<String> {
+ let mut args = Vec::new();
+ match cfg.gpu_power_preference.as_str() {
+ "high-performance" => args.push("--force_high_performance_gpu".to_string()),
+ "low-power" => args.push("--force_low_power_gpu".to_string()),
+ _ => {}
+ }
+ match cfg.desktop_graphics_api.as_str() {
+ "d3d11" => args.push("--use-angle=d3d11".to_string()),
+ "vulkan" => args.push("--use-angle=vulkan".to_string()),
+ "gl" => args.push("--use-angle=gl".to_string()),
+ "warp" => args.push("--use-angle=warp".to_string()),
+ _ => {}
+ }
+ args
+}
+
+/// Classifies a GPU name/vendor into discrete, integrated, software, or unknown.
+pub fn classify_gpu_kind(name: &str, vendor: &str) -> String {
+ let lower = format!("{} {}", name, vendor).to_ascii_lowercase();
+ if lower.contains("microsoft basic")
+ || lower.contains("swiftshader")
+ || lower.contains("llvmpipe")
+ || lower.contains("warp")
+ || lower.contains("software")
+ || lower.contains("virtualbox")
+ || lower.contains("vmware")
+ {
+ return "software".to_string();
+ }
+ if lower.contains("nvidia")
+ || lower.contains("geforce")
+ || lower.contains("rtx")
+ || lower.contains("gtx")
+ || lower.contains("quadro")
+ || lower.contains("radeon rx")
+ || lower.contains("radeon pro")
+ || lower.contains("intel arc")
+ {
+ return "discrete".to_string();
+ }
+ if lower.contains("intel")
+ || lower.contains("uhd")
+ || lower.contains("iris")
+ || lower.contains("hd graphics")
+ || lower.contains("radeon(tm) graphics")
+ || lower.contains("radeon graphics")
+ || lower.contains("vega")
+ || lower.contains("apple m")
+ {
+ return "integrated".to_string();
+ }
+ if lower.contains("amd") || lower.contains("radeon") {
+ return "discrete".to_string();
+ }
+ "unknown".to_string()
+}
+
+fn infer_vendor_from_name(name: &str) -> String {
+ let lower = name.to_ascii_lowercase();
+ if lower.contains("nvidia") || lower.contains("geforce") || lower.contains("rtx") || lower.contains("gtx") {
+ "NVIDIA".to_string()
+ } else if lower.contains("amd") || lower.contains("radeon") {
+ "AMD".to_string()
+ } else if lower.contains("intel") {
+ "Intel".to_string()
+ } else if lower.contains("apple") {
+ "Apple".to_string()
+ } else if lower.contains("microsoft") {
+ "Microsoft".to_string()
+ } else {
+ "Unknown".to_string()
+ }
+}
+
+#[cfg(target_os = "windows")]
+fn query_system_ram_mb() -> (u64, u64) {
+ use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
+ unsafe {
+ let mut status: MEMORYSTATUSEX = std::mem::zeroed();
+ status.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
+ if GlobalMemoryStatusEx(&mut status) != 0 {
+ let total_mb = status.ullTotalPhys / (1024 * 1024);
+ let avail_mb = status.ullAvailPhys / (1024 * 1024);
+ return (total_mb, avail_mb);
+ }
+ }
+ (8192, 4096)
+}
+
+#[cfg(target_os = "linux")]
+fn query_system_ram_mb() -> (u64, u64) {
+ if let Ok(content) = std::fs::read_to_string("/proc/meminfo") {
+ let mut total_kb: u64 = 0;
+ let mut avail_kb: u64 = 0;
+ for line in content.lines() {
+ if let Some(rest) = line.strip_prefix("MemTotal:") {
+ if let Some(val) = rest.split_whitespace().next().and_then(|s| s.parse::<u64>().ok()) {
+ total_kb = val;
+ }
+ } else if let Some(rest) = line.strip_prefix("MemAvailable:") {
+ if let Some(val) = rest.split_whitespace().next().and_then(|s| s.parse::<u64>().ok()) {
+ avail_kb = val;
+ }
+ }
+ }
+ if total_kb > 0 {
+ return (total_kb / 1024, (if avail_kb > 0 { avail_kb } else { total_kb / 2 }) / 1024);
+ }
+ }
+ (8192, 4096)
+}
+
+#[cfg(all(not(target_os = "windows"), not(target_os = "linux")))]
+fn query_system_ram_mb() -> (u64, u64) {
+ // macOS / other Unix fallback via sysctl if available
+ if let Ok(out) = std::process::Command::new("sysctl")
+ .args(["-n", "hw.memsize"])
+ .output()
+ {
+ if out.status.success() {
+ if let Ok(text) = String::from_utf8(out.stdout) {
+ if let Ok(bytes) = text.trim().parse::<u64>() {
+ let mb = bytes / (1024 * 1024);
+ if mb > 0 {
+ return (mb, (mb * 65) / 100);
+ }
+ }
+ }
+ }
+ }
+ (8192, 4096)
+}
+
+#[cfg(target_os = "windows")]
+fn utf16_slice_to_string(buf: &[u16]) -> String {
+ let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
+ String::from_utf16_lossy(&buf[..len]).trim().to_string()
+}
+
+#[cfg(target_os = "windows")]
+fn to_wide_null(s: &str) -> Vec<u16> {
+ s.encode_utf16().chain(std::iter::once(0)).collect()
+}
+
+#[cfg(target_os = "windows")]
+fn read_reg_string(hkey: windows_sys::Win32::System::Registry::HKEY, value_name: &str) -> Option<String> {
+ use windows_sys::Win32::System::Registry::{RegQueryValueExW, REG_SZ};
+ let name_w = to_wide_null(value_name);
+ let mut reg_type: u32 = 0;
+ let mut size: u32 = 0;
+ let status = unsafe {
+ RegQueryValueExW(
+ hkey,
+ name_w.as_ptr(),
+ std::ptr::null_mut(),
+ &mut reg_type,
+ std::ptr::null_mut(),
+ &mut size,
+ )
+ };
+ if status != 0 || reg_type != REG_SZ || size == 0 || size > 4096 {
+ return None;
+ }
+ let mut buf = vec![0u16; (size as usize + 1) / 2];
+ let status2 = unsafe {
+ RegQueryValueExW(
+ hkey,
+ name_w.as_ptr(),
+ std::ptr::null_mut(),
+ &mut reg_type,
+ buf.as_mut_ptr() as *mut u8,
+ &mut size,
+ )
+ };
+ if status2 != 0 {
+ return None;
+ }
+ let s = utf16_slice_to_string(&buf);
+ if s.is_empty() { None } else { Some(s) }
+}
+
+#[cfg(target_os = "windows")]
+fn read_reg_u64(hkey: windows_sys::Win32::System::Registry::HKEY, value_name: &str) -> Option<u64> {
+ use windows_sys::Win32::System::Registry::{
+ RegQueryValueExW, REG_BINARY, REG_DWORD, REG_QWORD,
+ };
+ let name_w = to_wide_null(value_name);
+ let mut reg_type: u32 = 0;
+ let mut buf = [0u8; 8];
+ let mut size: u32 = buf.len() as u32;
+ let status = unsafe {
+ RegQueryValueExW(
+ hkey,
+ name_w.as_ptr(),
+ std::ptr::null_mut(),
+ &mut reg_type,
+ buf.as_mut_ptr(),
+ &mut size,
+ )
+ };
+ if status != 0 {
+ return None;
+ }
+ if reg_type == REG_QWORD && size >= 8 {
+ Some(u64::from_le_bytes(buf))
+ } else if (reg_type == REG_DWORD || reg_type == REG_BINARY) && size >= 4 {
+ if size >= 8 && reg_type == REG_BINARY {
+ Some(u64::from_le_bytes(buf))
+ } else {
+ Some(u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as u64)
+ }
+ } else {
+ None
+ }
+}
+
+#[cfg(target_os = "windows")]
+fn detect_gpus() -> Vec<GpuAdapterInfo> {
+ use windows_sys::Win32::Graphics::Gdi::{EnumDisplayDevicesW, DISPLAY_DEVICEW};
+ use windows_sys::Win32::System::Registry::{
+ RegCloseKey, RegEnumKeyExW, RegOpenKeyExW, HKEY, HKEY_LOCAL_MACHINE, KEY_READ,
+ };
+
+ let mut adapters: Vec<GpuAdapterInfo> = Vec::new();
+ let mut seen_names: HashSet<String> = HashSet::new();
+
+ // 1. Enumerate Display Adapters from Windows Registry Class GUID for accurate VRAM (>4GB QWORD)
+ let class_path = to_wide_null(
+ r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}",
+ );
+ let mut class_key: HKEY = std::ptr::null_mut();
+ let open_ok = unsafe {
+ RegOpenKeyExW(
+ HKEY_LOCAL_MACHINE,
+ class_path.as_ptr(),
+ 0,
+ KEY_READ,
+ &mut class_key,
+ )
+ };
+ if open_ok == 0 && !class_key.is_null() {
+ let mut idx: u32 = 0;
+ loop {
+ let mut sub_name = [0u16; 128];
+ let mut sub_len: u32 = sub_name.len() as u32;
+ let enum_res = unsafe {
+ RegEnumKeyExW(
+ class_key,
+ idx,
+ sub_name.as_mut_ptr(),
+ &mut sub_len,
+ std::ptr::null_mut(),
+ std::ptr::null_mut(),
+ std::ptr::null_mut(),
+ std::ptr::null_mut(),
+ )
+ };
+ if enum_res != 0 {
+ break;
+ }
+ idx += 1;
+ let sub_str = utf16_slice_to_string(&sub_name[..sub_len as usize]);
+ if sub_str.len() != 4 || !sub_str.chars().all(|c| c.is_ascii_digit()) {
+ continue;
+ }
+
+ let mut sub_key: HKEY = std::ptr::null_mut();
+ let sub_w = to_wide_null(&sub_str);
+ if unsafe { RegOpenKeyExW(class_key, sub_w.as_ptr(), 0, KEY_READ, &mut sub_key) } == 0
+ && !sub_key.is_null()
+ {
+ if let Some(desc) = read_reg_string(sub_key, "DriverDesc") {
+ let norm = desc.to_ascii_lowercase();
+ if !seen_names.contains(&norm) {
+ seen_names.insert(norm);
+ let vendor = read_reg_string(sub_key, "ProviderName")
+ .filter(|v| !v.is_empty())
+ .unwrap_or_else(|| infer_vendor_from_name(&desc));
+ let vram_bytes = read_reg_u64(sub_key, "HardwareInformation.qwMemorySize")
+ .or_else(|| read_reg_u64(sub_key, "HardwareInformation.MemorySize"))
+ .unwrap_or(0);
+ let vram_mb = vram_bytes / (1024 * 1024);
+ let kind = classify_gpu_kind(&desc, &vendor);
+ adapters.push(GpuAdapterInfo {
+ id: format!("gpu-{}", sub_str),
+ name: desc,
+ vendor,
+ vram_mb,
+ kind,
+ is_primary: false,
+ });
+ }
+ }
+ unsafe {
+ RegCloseKey(sub_key);
+ }
+ }
+ }
+ unsafe {
+ RegCloseKey(class_key);
+ }
+ }
+
+ // 2. Cross-reference active display devices via EnumDisplayDevicesW to tag primary & catch any unlisted GPUs
+ const DISPLAY_DEVICE_ACTIVE: u32 = 0x0000_0001;
+ const DISPLAY_DEVICE_PRIMARY_DEVICE: u32 = 0x0000_0004;
+ const DISPLAY_DEVICE_MIRRORING_DRIVER: u32 = 0x0000_0008;
+
+ let mut dev_idx: u32 = 0;
+ loop {
+ let mut dev: DISPLAY_DEVICEW = unsafe { std::mem::zeroed() };
+ dev.cb = std::mem::size_of::<DISPLAY_DEVICEW>() as u32;
+ let ok = unsafe { EnumDisplayDevicesW(std::ptr::null(), dev_idx, &mut dev, 0) };
+ if ok == 0 {
+ break;
+ }
+ dev_idx += 1;
+
+ if (dev.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) != 0 {
+ continue;
+ }
+ let name = utf16_slice_to_string(&dev.DeviceString);
+ if name.is_empty() {
+ continue;
+ }
+ let is_primary = (dev.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) != 0;
+ let is_active = (dev.StateFlags & DISPLAY_DEVICE_ACTIVE) != 0;
+ let norm = name.to_ascii_lowercase();
+
+ if let Some(existing) = adapters
+ .iter_mut()
+ .find(|a| a.name.to_ascii_lowercase() == norm)
+ {
+ if is_primary {
+ existing.is_primary = true;
+ }
+ } else if is_active || adapters.is_empty() {
+ seen_names.insert(norm);
+ let vendor = infer_vendor_from_name(&name);
+ let kind = classify_gpu_kind(&name, &vendor);
+ adapters.push(GpuAdapterInfo {
+ id: format!("gdi-{}", dev_idx),
+ name,
+ vendor,
+ vram_mb: 0,
+ kind,
+ is_primary,
+ });
+ }
+ }
+
+ // Sort discrete first, then primary, then integrated, then software
+ adapters.sort_by_key(|a| {
+ let rank = match a.kind.as_str() {
+ "discrete" => 0,
+ "integrated" => 1,
+ "unknown" => 2,
+ _ => 3,
+ };
+ (rank, if a.is_primary { 0 } else { 1 }, std::cmp::Reverse(a.vram_mb))
+ });
+
+ if !adapters.is_empty() && !adapters.iter().any(|a| a.is_primary) {
+ adapters[0].is_primary = true;
+ }
+
+ adapters
+}
+
+#[cfg(not(target_os = "windows"))]
+fn detect_gpus() -> Vec<GpuAdapterInfo> {
+ Vec::new()
+}
+
+#[cfg(target_os = "windows")]
+pub fn query_disk_space_mb(path: &Path) -> (u64, u64) {
+ use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
+ let target = if path.exists() {
+ path.to_path_buf()
+ } else {
+ path.parent()
+ .filter(|p| p.exists())
+ .map(|p| p.to_path_buf())
+ .unwrap_or_else(std::env::temp_dir)
+ };
+ let wide = to_wide_null(&target.to_string_lossy());
+ let mut free_caller: u64 = 0;
+ let mut total_bytes: u64 = 0;
+ let mut total_free: u64 = 0;
+ let ok = unsafe {
+ GetDiskFreeSpaceExW(
+ wide.as_ptr(),
+ &mut free_caller,
+ &mut total_bytes,
+ &mut total_free,
+ )
+ };
+ if ok != 0 {
+ return (free_caller / (1024 * 1024), total_bytes / (1024 * 1024));
+ }
+ (0, 0)
+}
+
+#[cfg(not(target_os = "windows"))]
+pub fn query_disk_space_mb(_path: &Path) -> (u64, u64) {
+ (0, 0)
+}
+
+pub fn compute_dir_bytes(path: &Path) -> u64 {
+ if !path.exists() {
+ return 0;
+ }
+ let mut total: u64 = 0;
+ let mut stack = vec![path.to_path_buf()];
+ while let Some(dir) = stack.pop() {
+ let Ok(entries) = std::fs::read_dir(&dir) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let Ok(meta) = entry.metadata() else {
+ continue;
+ };
+ if meta.is_dir() {
+ stack.push(entry.path());
+ } else if meta.is_file() {
+ total = total.saturating_add(meta.len());
+ }
+ }
+ }
+ total
+}
+
+pub fn validate_custom_scratch_dir(raw_path: &str) -> Result<Option<PathBuf>, String> {
+ let trimmed = raw_path.trim();
+ if trimmed.is_empty() {
+ return Ok(None);
+ }
+ if trimmed.contains('\0') {
+ return Err("Invalid scratch disk path".to_string());
+ }
+ let p = Path::new(trimmed);
+ let meta = std::fs::symlink_metadata(p)
+ .map_err(|_| "Scratch disk directory does not exist or is inaccessible".to_string())?;
+ if meta.file_type().is_symlink() {
+ return Err("Refusing to use a symbolic link as scratch disk directory".to_string());
+ }
+ if !meta.is_dir() {
+ return Err("Scratch disk path must be an existing directory".to_string());
+ }
+ let canonical = std::fs::canonicalize(p)
+ .map_err(|_| "Failed to resolve canonical scratch disk directory".to_string())?;
+
+ // Probe write permission cleanly using a unique probe file
+ let probe = canonical.join(format!(".inkstudio_probe_{}", std::process::id()));
+ std::fs::write(&probe, b"ok")
+ .map_err(|_| "Scratch disk directory is not writable".to_string())?;
+ let _ = std::fs::remove_file(&probe);
+
+ Ok(Some(canonical))
+}
+
+pub fn get_undo_cache_base_dir() -> PathBuf {
+ crate::scratch_disk::get_scratch_base_dir()
+ .parent()
+ .map(|p| p.join("inkstudio_undo"))
+ .unwrap_or_else(|| std::env::temp_dir().join("inkstudio_undo"))
+}
+
+pub fn collect_scratch_disk_usage() -> ScratchDiskUsageReport {
+ let scratch_base = crate::scratch_disk::get_scratch_base_dir();
+ let undo_base = get_undo_cache_base_dir();
+ let (free_mb, total_mb) = query_disk_space_mb(&scratch_base);
+ let scratch_used = compute_dir_bytes(&scratch_base);
+ let undo_used = compute_dir_bytes(&undo_base);
+
+ ScratchDiskUsageReport {
+ scratch_disk_path: scratch_base.to_string_lossy().to_string(),
+ scratch_disk_free_mb: free_mb,
+ scratch_disk_total_mb: total_mb,
+ scratch_disk_used_bytes: scratch_used,
+ undo_cache_used_bytes: undo_used,
+ }
+}
+
+pub fn collect_system_hardware_info() -> SystemHardwareInfo {
+ let (total_ram_mb, available_ram_mb) = query_system_ram_mb();
+ let cpu_logical_cores = get_cpu_logical_cores();
+ let gpus = detect_gpus();
+ let usage = collect_scratch_disk_usage();
+ let startup_config = load_startup_config();
+
+ SystemHardwareInfo {
+ total_ram_mb,
+ available_ram_mb,
+ cpu_logical_cores,
+ os_platform: std::env::consts::OS.to_string(),
+ gpus,
+ scratch_disk_path: usage.scratch_disk_path,
+ scratch_disk_free_mb: usage.scratch_disk_free_mb,
+ scratch_disk_total_mb: usage.scratch_disk_total_mb,
+ scratch_disk_used_bytes: usage.scratch_disk_used_bytes,
+ undo_cache_used_bytes: usage.undo_cache_used_bytes,
+ active_cpu_worker_threads: get_active_cpu_worker_threads(),
+ startup_config,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_classify_gpu_kind_identifies_discrete_integrated_and_software() {
+ assert_eq!(
+ classify_gpu_kind("NVIDIA GeForce RTX 4070", "NVIDIA"),
+ "discrete"
+ );
+ assert_eq!(
+ classify_gpu_kind("AMD Radeon RX 7800 XT", "AMD"),
+ "discrete"
+ );
+ assert_eq!(
+ classify_gpu_kind("Intel(R) Iris(R) Xe Graphics", "Intel"),
+ "integrated"
+ );
+ assert_eq!(
+ classify_gpu_kind("Microsoft Basic Render Driver", "Microsoft"),
+ "software"
+ );
+ }
+
+ #[test]
+ fn test_build_webview_perf_args_maps_gpu_and_angle_flags() {
+ let mut cfg = StartupPerformanceConfig::default();
+ cfg.gpu_power_preference = "high-performance".to_string();
+ cfg.desktop_graphics_api = "vulkan".to_string();
+ let args = build_webview_perf_args(&cfg);
+ assert!(args.contains(&"--force_high_performance_gpu".to_string()));
+ assert!(args.contains(&"--use-angle=vulkan".to_string()));
+
+ cfg.gpu_power_preference = "low-power".to_string();
+ cfg.desktop_graphics_api = "auto".to_string();
+ let args2 = build_webview_perf_args(&cfg);
+ assert_eq!(args2, vec!["--force_low_power_gpu".to_string()]);
+ }
+
+ #[test]
+ fn test_cpu_worker_pool_executes_with_custom_thread_limit() {
+ use rayon::prelude::*;
+ let applied = set_cpu_worker_threads(2).expect("set 2 threads");
+ assert_eq!(applied, 2);
+ let sum: usize = run_on_worker_pool(|| (0..1000).into_par_iter().sum());
+ assert_eq!(sum, (0..1000).sum::<usize>());
+
+ let reset = set_cpu_worker_threads(0).expect("reset to auto");
+ assert_eq!(reset, 0);
+ }
+
+ #[test]
+ fn test_collect_system_hardware_info_returns_valid_values() {
+ let info = collect_system_hardware_info();
+ assert!(info.total_ram_mb >= 512);
+ assert!(info.cpu_logical_cores >= 1);
+ assert!(!info.os_platform.is_empty());
+ assert!(!info.scratch_disk_path.is_empty());
+ }
+
+ #[test]
+ fn test_validate_custom_scratch_dir_accepts_writable_dir_and_rejects_invalid() {
+ let tmp = std::env::temp_dir().join(format!(
+ "inkstudio_scratch_validate_{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&tmp).unwrap();
+ let ok = validate_custom_scratch_dir(tmp.to_str().unwrap()).unwrap();
+ assert!(ok.is_some());
+ assert!(validate_custom_scratch_dir("").unwrap().is_none());
+ assert!(validate_custom_scratch_dir("nonexistent_dir_xyz_99999").is_err());
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+}
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index b862a2b..1a2def0 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -132,7 +132,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {
resizeStartSettingsRef,
});
- const { viewportCanvasRef } = useCompositorViewport({
+ const { viewportCanvasRef, compositorKey } = useCompositorViewport({
viewportRef,
onViewportReady,
artboardRef,
@@ -266,8 +266,9 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {
zoom={zoom}
/>
)}
- {/* Unified GPU Viewport Canvas (WebGL2 with Frustum Culling & Shaders) */}
+ {/* Unified GPU Viewport Canvas (WebGL2 with Frustum Culling & Shaders, or Canvas 2D Software) */}
<canvas
+ key={compositorKey}
ref={viewportCanvasRef}
className="absolute inset-0 pointer-events-none z-10"
style={{
diff --git a/src/components/DeleteDocumentModal.tsx b/src/components/DeleteDocumentModal.tsx
index 97fd8fa..2623673 100644
--- a/src/components/DeleteDocumentModal.tsx
+++ b/src/components/DeleteDocumentModal.tsx
@@ -1,4 +1,4 @@
-import React from 'react';
+import React, { useEffect } from 'react';
import { Trash2, EyeOff, AlertTriangle, X, FileText } from 'lucide-react';
import { RecentDocument, formatFileSize } from '../utils/recentDocumentsManager';
@@ -17,37 +17,60 @@ export const DeleteDocumentModal: React.FC<DeleteDocumentModalProps> = ({
onHideFromApp,
onPermanentlyDelete,
}) => {
+ useEffect(() => {
+ if (!isOpen) return;
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ onClose();
+ }
+ };
+ window.addEventListener('keydown', handleKeyDown, true);
+ return () => window.removeEventListener('keydown', handleKeyDown, true);
+ }, [isOpen, onClose]);
+
if (!isOpen || !document) return null;
return (
<div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 select-none"
- onKeyDown={(e) => {
- if (e.key === 'Escape') onClose();
- }}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="delete-document-modal-title"
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none"
+ onClick={onClose}
>
- <div className="bg-[#444447] border border-[#242426] rounded-[2px] shadow-[0_8px_24px_rgba(0,0,0,0.7)] w-full max-w-md overflow-hidden text-[#d6d6da]">
+ <div
+ onClick={(e) => e.stopPropagation()}
+ className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] w-full max-w-[430px] overflow-hidden text-xs text-[#e5e5e5] border border-[#2c2c2c]"
+ >
{/* Title Bar */}
- <div className="px-3.5 py-2 border-b border-[#242426] bg-gradient-to-b from-[#525255] to-[#3e3e40] flex items-center justify-between">
- <div className="flex items-center space-x-2">
- <Trash2 className="w-3.5 h-3.5 text-rose-400" />
- <span className="text-xs font-semibold text-[#f0f0f4] tracking-wide">
+ <div className="h-9 px-3.5 flex items-center justify-between bg-[#161616] border-b border-[#2c2c2c]">
+ <div className="flex items-center gap-2 min-w-0">
+ <Trash2 className="w-3.5 h-3.5 text-red-400 shrink-0" />
+ <span
+ id="delete-document-modal-title"
+ className="text-xs font-medium text-[#e5e5e5] tracking-wide"
+ >
Delete Document
</span>
</div>
<button
+ type="button"
onClick={onClose}
- className="p-0.5 rounded-[2px] text-[#a0a0a5] hover:text-white hover:bg-[#525255] transition-colors"
+ aria-label="Close"
+ title="Cancel (Esc)"
+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
{/* Content */}
- <div className="p-4 space-y-3.5 text-xs">
+ <div className="p-4 space-y-3">
{/* Target File Info */}
- <div className="bg-[#2b2b2e] border border-[#1e1e20] rounded-[2px] p-2.5 flex items-center space-x-3 shadow-[inset_1px_1px_2px_rgba(0,0,0,0.4)]">
- <div className="w-10 h-10 bg-[#202022] border border-[#1a1a1c] overflow-hidden shrink-0 flex items-center justify-center rounded-[1px]">
+ <div className="bg-[#161616] border border-[#2c2c2c] rounded-md p-2.5 flex items-center gap-3">
+ <div className="w-11 h-11 bg-[#202020] border border-[#2c2c2c] overflow-hidden shrink-0 flex items-center justify-center rounded">
{document.coverUrl ? (
<img
src={document.coverUrl}
@@ -55,64 +78,70 @@ export const DeleteDocumentModal: React.FC<DeleteDocumentModalProps> = ({
className="w-full h-full object-cover"
/>
) : (
- <FileText className="w-5 h-5 text-[#6c6c72]" />
+ <FileText className="w-4 h-4 text-[#8a8a8a]" />
)}
</div>
<div className="flex-1 min-w-0">
- <div className="font-medium text-[#f0f0f4] truncate" title={document.title}>
+ <div className="text-xs font-medium text-[#e5e5e5] truncate" title={document.title}>
{document.title}
</div>
- <div className="text-[10px] text-[#8c8c92] font-mono truncate" title={document.path}>
+ <div className="text-[10px] text-[#8a8a8a] font-mono truncate mt-0.5" title={document.path}>
{formatFileSize(document.size)} • {document.path}
</div>
</div>
</div>
- <p className="text-[11px] text-[#a0a0a5]">
- Select action:
- </p>
+ <div className="text-[11px] font-medium text-[#8a8a8a] uppercase tracking-wider pt-0.5">
+ Select action
+ </div>
- {/* Action 1: Remove from list */}
- <button
- type="button"
- onClick={() => onHideFromApp(document)}
- className="w-full flex items-start space-x-2.5 p-2.5 rounded-[2px] border border-[#2b2b2e] bg-[#3a3a3d] hover:bg-[#46464a] hover:border-[#525256] text-left transition-colors cursor-pointer"
- >
- <EyeOff className="w-4 h-4 text-[#93c5fd] shrink-0 mt-0.5" />
- <div>
- <div className="font-medium text-[#f0f0f4]">
- Remove from Recent List
+ <div className="space-y-2">
+ {/* Action 1: Remove from list */}
+ <button
+ type="button"
+ onClick={() => onHideFromApp(document)}
+ className="w-full flex items-start gap-3 p-3 rounded-md bg-[#262626] hover:bg-[#2c2c2c] border border-[#2c2c2c] hover:border-[#3a3a3a] text-left transition-colors cursor-pointer"
+ >
+ <div className="w-7 h-7 rounded bg-[#161616] border border-[#2c2c2c] flex items-center justify-center shrink-0 text-[#8a8a8a]">
+ <EyeOff className="w-3.5 h-3.5" />
</div>
- <div className="text-[10px] text-[#8c8c92] mt-0.5">
- Removes entry from the studio. Keeps the file intact on disk.
+ <div className="min-w-0">
+ <div className="text-xs font-medium text-[#e5e5e5]">
+ Remove from Recent List
+ </div>
+ <div className="text-[11px] text-[#8a8a8a] mt-0.5 leading-snug">
+ Removes entry from the studio. Keeps the file intact on disk.
+ </div>
</div>
- </div>
- </button>
+ </button>
- {/* Action 2: Permanently delete */}
- <button
- type="button"
- onClick={() => onPermanentlyDelete(document)}
- className="w-full flex items-start space-x-2.5 p-2.5 rounded-[2px] border border-rose-900/50 bg-[#3d2c2f] hover:bg-[#4a3438] hover:border-rose-700/60 text-left transition-colors cursor-pointer"
- >
- <AlertTriangle className="w-4 h-4 text-rose-400 shrink-0 mt-0.5" />
- <div>
- <div className="font-medium text-rose-200">
- Permanently Delete from Disk
+ {/* Action 2: Permanently delete */}
+ <button
+ type="button"
+ onClick={() => onPermanentlyDelete(document)}
+ className="w-full flex items-start gap-3 p-3 rounded-md bg-red-500/[0.08] hover:bg-red-500/[0.14] border border-red-500/25 hover:border-red-500/45 text-left transition-colors cursor-pointer"
+ >
+ <div className="w-7 h-7 rounded bg-red-500/15 border border-red-500/25 flex items-center justify-center shrink-0 text-red-400">
+ <AlertTriangle className="w-3.5 h-3.5" />
</div>
- <div className="text-[10px] text-rose-300/70 mt-0.5">
- Erases file permanently from storage. Cannot be undone.
+ <div className="min-w-0">
+ <div className="text-xs font-medium text-red-300">
+ Permanently Delete from Disk
+ </div>
+ <div className="text-[11px] text-red-300/70 mt-0.5 leading-snug">
+ Erases file permanently from storage. Cannot be undone.
+ </div>
</div>
- </div>
- </button>
+ </button>
+ </div>
</div>
{/* Footer */}
- <div className="px-4 py-2 bg-[#3a3a3d] border-t border-[#242426] flex justify-end">
+ <div className="px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-end">
<button
type="button"
onClick={onClose}
- className="px-3 py-1 rounded-[2px] text-xs font-medium bg-gradient-to-b from-[#56565a] to-[#424245] hover:from-[#626266] hover:to-[#4b4b4e] border border-[#242426] text-[#d6d6da] shadow-[inset_0_1px_0_rgba(255,255,255,0.18)] cursor-pointer"
+ className="px-3.5 py-1.5 rounded bg-[#2a2a2a] hover:bg-[#363636] text-xs font-medium text-[#e5e5e5] transition-colors cursor-pointer"
>
Cancel
</button>
diff --git a/src/components/DockWorkspace.tsx b/src/components/DockWorkspace.tsx
index bbd2af0..5099aa4 100644
--- a/src/components/DockWorkspace.tsx
+++ b/src/components/DockWorkspace.tsx
@@ -20,6 +20,7 @@ import {
Eye,
Compass,
Images,
+ Info,
Play,
} from 'lucide-react';
import { CanvasColorMode, CspBrush } from '../types/editor';
@@ -57,6 +58,7 @@ import { RightSidebar, RightSidebarColorSection, RightSidebarProps } from './Rig
import { QuickAccessPanel } from './QuickAccessPanel';
import { NavigatorPanel, NavigatorPanelProps } from './NavigatorPanel';
import { SubViewPanel } from './SubViewPanel';
+import { InfoPanel } from './InfoPanel';
import { AutoActionPanel, AutoActionPanelProps } from './AutoActionPanel';
import { WorkspaceCommandHandlers } from './CommandBar';
@@ -76,6 +78,8 @@ export function renderPanelIcon(panelId: DockPanelId, className = 'w-3.5 h-3.5')
return <Compass className={className} />;
case 'sub-view':
return <Images className={className} />;
+ case 'info':
+ return <Info className={className} />;
case 'color':
return <Palette className={className} />;
case 'layers':
@@ -913,6 +917,14 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({
) : null;
case 'sub-view':
return <SubViewPanel colorMode={colorMode} themePreset={themePreset} />;
+ case 'info':
+ return (
+ <InfoPanel
+ layers={layerSidebarProps.layers}
+ colorMode={colorMode}
+ themePreset={themePreset}
+ />
+ );
case 'color':
return (
<RightSidebarColorSection
diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsx
index 6f7f79b..abeb405 100644
--- a/src/components/DocumentLifecycleManager.tsx
+++ b/src/components/DocumentLifecycleManager.tsx
@@ -17,10 +17,20 @@ import {
saveToExistingHandle,
} from '../utils/saveManager';
import { globalTimelapseManager } from '../utils/timelapseEngine';
-import { saveRecentDocument, RecentDocument } from '../utils/recentDocumentsManager';
+import {
+ FileSystemFileHandleLike,
+ RecentDocument,
+ saveRecentDocument,
+} from '../utils/recentDocumentsManager';
import { enforceColorMode } from '../utils/colorUtils';
import { importBrushFile, isSupportedBrushFileName } from '../utils/inkbBrushFormat';
import { documentStore } from '../utils/documentStore';
+import { computeRecommendedSettings, performanceManager } from '../utils/performanceManager';
+import { WebGlBrushEngine } from '../engine/WebGlBrushEngine';
+import {
+ artworkTimeTracker,
+ sanitizeWorkTimeMs,
+} from '../utils/artworkTimeTracker';
import { shortcutManager } from '../utils/shortcutManager';
import { recoveryService, CrashedSessionInfo } from '../services/recoveryService';
import { multiplayerService } from '../services/multiplayerService';
@@ -40,6 +50,48 @@ import {
requestAppClose,
} from '../utils/appCloseFlow';
+function hasMeaningfulLayerEdit(prev: LayerItem[], next: LayerItem[]): boolean {
+ if (prev === next) return false;
+ if (prev.length !== next.length) return true;
+ for (let i = 0; i < prev.length; i++) {
+ const a = prev[i];
+ const b = next[i];
+ if (a === b) continue;
+ if (
+ a.id !== b.id ||
+ a.name !== b.name ||
+ a.type !== b.type ||
+ a.visible !== b.visible ||
+ a.opacity !== b.opacity ||
+ a.blendMode !== b.blendMode ||
+ a.locked !== b.locked ||
+ a.alphaLocked !== b.alphaLocked ||
+ a.clipped !== b.clipped ||
+ a.parentId !== b.parentId ||
+ a.isReference !== b.isReference ||
+ a.toneEnabled !== b.toneEnabled ||
+ a.toneFrequency !== b.toneFrequency ||
+ a.toneAngle !== b.toneAngle ||
+ a.toneDensity !== b.toneDensity ||
+ a.layerColorEnabled !== b.layerColorEnabled ||
+ a.layerColor !== b.layerColor ||
+ a.expressionColor !== b.expressionColor ||
+ a.maskEnabled !== b.maskEnabled ||
+ a.maskLinked !== b.maskLinked ||
+ a.maskVersion !== b.maskVersion ||
+ a.adjustmentData !== b.adjustmentData ||
+ a.styles !== b.styles ||
+ a.vectorStrokes !== b.vectorStrokes ||
+ a.textData !== b.textData ||
+ a.balloonData !== b.balloonData ||
+ a.comicFrames !== b.comicFrames
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
+
function computeEffectiveOpacityForLayers(allLayers: LayerItem[], layer: LayerItem): number {
let opacity = layer.opacity;
let parentId = layer.parentId;
@@ -76,6 +128,55 @@ interface TauriWindow extends Window {
__TAURI_INTERNALS__?: unknown;
}
+interface PickerWindow extends Window {
+ showOpenFilePicker?: (options?: {
+ types?: Array<{ description?: string; accept: Record<string, string[]> }>;
+ multiple?: boolean;
+ }) => Promise<FileSystemFileHandleLike[]>;
+}
+
+interface ProcessFileOptions {
+ handle?: FileSystemFileHandleLike | null;
+ sourcePath?: string;
+ docId?: string;
+ isStarred?: boolean;
+}
+
+const DIRECT_SAVE_EXTENSIONS = new Set([
+ '.ink',
+ '.psd',
+ '.psb',
+ '.png',
+ '.jpg',
+ '.jpeg',
+ '.webp',
+]);
+
+const OPEN_FILE_PICKER_TYPES = [
+ {
+ description: 'Ink Studio & Image Files',
+ accept: {
+ 'application/octet-stream': [
+ '.ink',
+ '.psd',
+ '.psb',
+ '.clip',
+ '.csp',
+ '.lip',
+ '.inkb',
+ '.sut',
+ '.sora',
+ ],
+ 'image/png': ['.png'],
+ 'image/jpeg': ['.jpg', '.jpeg'],
+ 'image/webp': ['.webp'],
+ 'image/bmp': ['.bmp'],
+ 'image/gif': ['.gif'],
+ 'image/svg+xml': ['.svg'],
+ },
+ },
+];
+
export interface UseDocumentLifecycleParams {
layers: LayerItem[];
activeLayer: LayerItem | undefined;
@@ -222,8 +323,10 @@ export function useDocumentLifecycle({
activeLayerId: topId,
perspectiveRuler: null,
defaultFrequency: defaultFreq,
+ workTimeMs: 0,
};
+ artworkTimeTracker.initDocument(newDocId, 0);
documentStoreActions.setPerspectiveRuler(null);
documentStoreActions.setStraightRuler(null);
documentStoreActions.setDocuments((prev) => [...prev, newDoc]);
@@ -349,6 +452,28 @@ export function useDocumentLifecycle({
if (prev.tileMemoryBudgetMb !== newSettings.tileMemoryBudgetMb) {
documentStore.setTileBudgetMb(newSettings.tileMemoryBudgetMb || 1024);
}
+ if (prev.undoRamSteps !== newSettings.undoRamSteps) {
+ documentStore.setSharedUndoRamStepsBudget(newSettings.undoRamSteps || 15);
+ }
+ if (prev.offloadInactiveTabs !== newSettings.offloadInactiveTabs) {
+ documentStore.setOffloadInactiveUndoOnSwitch(newSettings.offloadInactiveTabs);
+ }
+ if (
+ prev.renderBackend !== newSettings.renderBackend ||
+ prev.gpuPowerPreference !== newSettings.gpuPowerPreference ||
+ prev.gpuBrushAcceleration !== newSettings.gpuBrushAcceleration
+ ) {
+ WebGlBrushEngine.getInstance().reconfigureFromPerformance();
+ }
+ if (
+ prev.gpuPowerPreference !== newSettings.gpuPowerPreference ||
+ prev.desktopGraphicsApi !== newSettings.desktopGraphicsApi ||
+ prev.scratchDiskPath !== newSettings.scratchDiskPath ||
+ prev.scratchDiskCompression !== newSettings.scratchDiskCompression ||
+ prev.cpuWorkerThreads !== newSettings.cpuWorkerThreads
+ ) {
+ void performanceManager.syncDesktopBackendConfig(newSettings);
+ }
if (
prev.defaultStabilization !== newSettings.defaultStabilization ||
prev.usePressureByDefault !== newSettings.usePressureByDefault ||
@@ -363,7 +488,7 @@ export function useDocumentLifecycle({
}, []);
const handleProcessFile = useCallback(
- async (file: File) => {
+ async (file: File, options?: ProcessFileOptions) => {
if (isSupportedBrushFileName(file.name)) {
try {
uiStoreActions.setLoading(true, `Importing Brush: ${file.name}...`);
@@ -385,11 +510,26 @@ export function useDocumentLifecycle({
uiStoreActions.setLoading(true, `Loading ${file.name}...`);
const doc = await openFile(file);
- const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
+ const alreadyOpenId = options?.docId
+ ? useDocumentStore.getState().documents.some((d) => d.id === options.docId)
+ : false;
+ const newDocId =
+ options?.docId && !alreadyOpenId
+ ? options.docId
+ : `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
+ const openedExt = file.name.includes('.')
+ ? file.name.slice(file.name.lastIndexOf('.')).toLowerCase()
+ : '';
+ const fileHandle = options?.handle ?? undefined;
+ const initialSavedInfo =
+ fileHandle && DIRECT_SAVE_EXTENSIONS.has(openedExt)
+ ? { name: file.name, handle: fileHandle, extension: openedExt }
+ : null;
+
documentStoreActions.setDimensions(doc.dimensions);
documentStoreActions.setColorMode(doc.colorMode);
documentStoreActions.setDocumentName(doc.name);
- documentStoreActions.setSavedFileInfo(null);
+ documentStoreActions.setSavedFileInfo(initialSavedInfo);
loadDocument(doc, newDocId);
needsAdaptiveFitRef.current = true;
@@ -398,6 +538,8 @@ export function useDocumentLifecycle({
resetHistory(newDocId);
const topEditableLayer = doc.layers.find((l) => l.type === 'raster');
+ const restoredWorkTimeMs = sanitizeWorkTimeMs(doc.workTimeMs);
+ artworkTimeTracker.initDocument(newDocId, restoredWorkTimeMs);
const newDoc: DocumentTab = {
id: newDocId,
name: doc.name,
@@ -406,6 +548,8 @@ export function useDocumentLifecycle({
layers: doc.layers,
activeLayerId: topEditableLayer?.id || doc.layers[0]?.id || 'layer-1',
perspectiveRuler: doc.perspectiveRuler ?? null,
+ savedFileInfo: initialSavedInfo ?? undefined,
+ workTimeMs: restoredWorkTimeMs,
};
documentStoreActions.setPerspectiveRuler(doc.perspectiveRuler ?? null);
@@ -415,22 +559,24 @@ export function useDocumentLifecycle({
}
documentStoreActions.setDocuments((prev) => [...prev, newDoc]);
documentStoreActions.setActiveDocumentId(newDocId);
+ uiStoreActions.setAppView('workspace');
const fileWithPath = file as FileWithOptionalPath;
saveRecentDocument({
id: newDocId,
title: file.name,
- path: fileWithPath.path || `C:\\Users\\Artist\\Documents\\InkStudio\\${file.name}`,
+ path:
+ options?.sourcePath ||
+ fileWithPath.path ||
+ `C:\\Users\\Artist\\Documents\\InkStudio\\${file.name}`,
size: file.size || 1048576,
coverUrl: doc.previewDataUrl || doc.layers[0]?.thumbnailUrl,
- isStarred: false,
- fileType: file.name.slice(file.name.lastIndexOf('.')),
+ isStarred: options?.isStarred ?? false,
+ fileType: openedExt || undefined,
isSaved: true,
+ handle: fileHandle,
}).catch(console.warn);
- const openedExt = file.name.includes('.')
- ? file.name.slice(file.name.lastIndexOf('.')).toLowerCase()
- : '';
showToast(
openedExt === '.sora'
? `Migrated legacy ${file.name} (read-only) — save as .ink`
@@ -536,6 +682,7 @@ export function useDocumentLifecycle({
return next;
});
if (id) {
+ artworkTimeTracker.removeDocument(id);
documentStore.closeSession(id).catch(console.warn);
recoveryService.closeSession(id).catch(console.warn);
}
@@ -575,6 +722,8 @@ export function useDocumentLifecycle({
documentStoreActions.setColorMode(manifest.colorMode);
documentStoreActions.setDocumentName(manifest.documentName);
+ const restoredWorkTimeMs = sanitizeWorkTimeMs(manifest.workTimeMs);
+ artworkTimeTracker.initDocument(session.session_id, restoredWorkTimeMs);
const restoredDoc: DocumentTab = {
id: session.session_id,
name: manifest.documentName,
@@ -583,6 +732,7 @@ export function useDocumentLifecycle({
colorMode: manifest.colorMode,
layers: manifest.layers,
activeLayerId: manifest.activeLayerId || manifest.layers[0]?.id || '',
+ workTimeMs: restoredWorkTimeMs,
};
documentStoreActions.setDocuments((prev) => {
@@ -655,8 +805,29 @@ export function useDocumentLifecycle({
);
const handleTriggerOpenFile = useCallback(() => {
+ const pickerWindow = typeof window !== 'undefined' ? (window as PickerWindow) : undefined;
+ if (pickerWindow && typeof pickerWindow.showOpenFilePicker === 'function') {
+ void pickerWindow
+ .showOpenFilePicker({
+ types: OPEN_FILE_PICKER_TYPES,
+ multiple: false,
+ })
+ .then(async ([handle]) => {
+ if (!handle) return;
+ const file = await handle.getFile();
+ await handleProcessFile(file, { handle });
+ })
+ .catch((err: unknown) => {
+ if (err && typeof err === 'object' && 'name' in err && err.name === 'AbortError') {
+ return;
+ }
+ console.warn('showOpenFilePicker failed, falling back to file input:', err);
+ fileInputRef.current?.click();
+ });
+ return;
+ }
fileInputRef.current?.click();
- }, []);
+ }, [handleProcessFile]);
const handleFileInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
@@ -673,6 +844,8 @@ export function useDocumentLifecycle({
const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';
const docStoreState = useDocumentStore.getState();
const tlStats = globalTimelapseManager.getStats(activeDocumentId);
+ artworkTimeTracker.flush(activeDocumentId);
+ const workTimeMs = artworkTimeTracker.getWorkTimeMs(activeDocumentId);
return {
name: cleanNameForSave,
dimensions,
@@ -688,6 +861,7 @@ export function useDocumentLifecycle({
tlStats.enabled || tlStats.frameCount > 0
? { enabled: tlStats.enabled, frameCount: tlStats.frameCount }
: null,
+ workTimeMs,
onProgress,
};
},
@@ -717,6 +891,8 @@ export function useDocumentLifecycle({
documentStore.getSession(docId)?.tileGrid ?? documentStore.getActiveTileGrid();
const cleanNameForSave = targetDoc.name.replace(/\*+$/, '') || 'Untitled';
const tlStats = globalTimelapseManager.getStats(docId);
+ artworkTimeTracker.flush(docId);
+ const docWorkTimeMs = artworkTimeTracker.getWorkTimeMs(docId);
const onProgress = (p: SaveProgress) => {
uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);
@@ -744,6 +920,7 @@ export function useDocumentLifecycle({
tlStats.enabled || tlStats.frameCount > 0
? { enabled: tlStats.enabled, frameCount: tlStats.frameCount }
: null,
+ workTimeMs: docWorkTimeMs,
onProgress,
};
@@ -771,6 +948,7 @@ export function useDocumentLifecycle({
name: info.name,
...(updateHandle ? { savedFileInfo: info } : {}),
isDirty: false,
+ workTimeMs: docWorkTimeMs,
}
: d
)
@@ -784,6 +962,7 @@ export function useDocumentLifecycle({
isStarred: false,
fileType: info.extension,
isSaved: true,
+ handle: info.handle,
}).catch(console.warn);
showToast(`Saved to ${info.name}`);
};
@@ -861,7 +1040,9 @@ export function useDocumentLifecycle({
documentStoreActions.setDocumentName(info.name);
documentStoreActions.setDocuments((prev) =>
prev.map((d) =>
- d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info, isDirty: false } : d
+ d.id === activeDocumentId
+ ? { ...d, name: info.name, savedFileInfo: info, isDirty: false, workTimeMs: docData.workTimeMs }
+ : d
)
);
saveRecentDocument({
@@ -873,6 +1054,7 @@ export function useDocumentLifecycle({
isStarred: false,
fileType: info.extension,
isSaved: true,
+ handle: info.handle,
}).catch(console.warn);
showToast(`Saved as ${info.name}`);
} catch (err: unknown) {
@@ -907,37 +1089,74 @@ export function useDocumentLifecycle({
const handleSelectWelcomeDocument = useCallback(
async (doc: RecentDocument) => {
- if (typeof window !== 'undefined' && (window as TauriWindow).__TAURI_INTERNALS__) {
+ const openDoc = useDocumentStore.getState().documents.find((d) => d.id === doc.id);
+ if (openDoc) {
+ handleSelectDocument(openDoc.id);
+ return;
+ }
+
+ if (doc.handle && typeof doc.handle.getFile === 'function') {
+ try {
+ let permission: 'granted' | 'denied' | 'prompt' = 'granted';
+ if (typeof doc.handle.queryPermission === 'function') {
+ permission = await doc.handle.queryPermission({ mode: 'read' });
+ if (permission !== 'granted' && typeof doc.handle.requestPermission === 'function') {
+ permission = await doc.handle.requestPermission({ mode: 'read' });
+ }
+ }
+ if (permission === 'granted') {
+ const file = await doc.handle.getFile();
+ await handleProcessFile(file, {
+ handle: doc.handle,
+ sourcePath: doc.path,
+ docId: doc.id,
+ isStarred: doc.isStarred,
+ });
+ return;
+ }
+ showToast(`Permission denied to open "${doc.title}"`);
+ return;
+ } catch (err) {
+ console.warn('Direct FileSystemFileHandle read failed:', err);
+ }
+ }
+
+ if (typeof window !== 'undefined' && (window as TauriWindow).__TAURI_INTERNALS__ && doc.path) {
try {
const { invoke } = await import('@tauri-apps/api/core');
- const bytes = await invoke<number[]>('read_file_from_disk', { path: doc.path });
- if (bytes && bytes.length > 0) {
- const uint8 = new Uint8Array(bytes);
- const file = new File([uint8], doc.title, { type: 'application/octet-stream' });
- await handleProcessFile(file);
- uiStoreActions.setAppView('workspace');
+ let bytes: Uint8Array;
+ try {
+ const buf = await invoke<ArrayBuffer>('read_file_binary', { path: doc.path });
+ bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
+ } catch (binErr) {
+ const msg = binErr instanceof Error ? binErr.message : String(binErr);
+ if (msg.toLowerCase().includes('not found') || msg.toLowerCase().includes('unknown')) {
+ const arr = await invoke<number[]>('read_file_from_disk', { path: doc.path });
+ bytes = new Uint8Array(arr);
+ } else {
+ throw binErr;
+ }
+ }
+ if (bytes.byteLength > 0) {
+ const copy = new Uint8Array(bytes.byteLength);
+ copy.set(bytes);
+ const file = new File([copy.buffer], doc.title, { type: 'application/octet-stream' });
+ await handleProcessFile(file, {
+ sourcePath: doc.path,
+ docId: doc.id,
+ isStarred: doc.isStarred,
+ });
return;
}
} catch (err) {
- console.warn('Direct disk read via Tauri failed, fallback:', err);
+ console.warn('Direct disk read via Tauri failed:', err);
}
}
- handleCreateNewCanvas({
- width: 1920,
- height: 1080,
- dpi: 300,
- colorMode: 'color',
- name: doc.title,
- backgroundColor: '#ffffff',
- aspectRatioPreset: '16:9',
- aspectRatioX: 16,
- aspectRatioY: 9,
- lockAspectRatio: true,
- });
- showToast(`Loaded workspace for "${doc.title}"`);
+ showToast(`Cannot reopen "${doc.title}" directly — select the file to open`);
+ handleTriggerOpenFile();
},
- [handleCreateNewCanvas, handleProcessFile, showToast]
+ [handleProcessFile, handleSelectDocument, handleTriggerOpenFile, showToast]
);
return {
@@ -1013,6 +1232,8 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =
const documentName = useDocumentStore((s) => s.documentName);
const appSettings = useUiStore((s) => s.appSettings);
const appClosePrompt = useUiStore((s) => s.appClosePrompt);
+ const appView = useUiStore((s) => s.appView);
+ const isLoadingFile = useUiStore((s) => s.isLoadingFile);
// 1. Scan for unfinalized crashed WAL sessions on launch
useEffect(() => {
@@ -1028,10 +1249,63 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =
});
}, []);
- // 2. Synchronize tile memory budget across all open documents
+ // 2. Synchronize tile RAM, undo RAM, inactive tab offload, and memory telemetry hooks
useEffect(() => {
documentStore.setTileBudgetMb(appSettings.tileMemoryBudgetMb || 1024);
- }, [appSettings.tileMemoryBudgetMb]);
+ documentStore.setSharedUndoRamStepsBudget(appSettings.undoRamSteps || 15);
+ documentStore.setOffloadInactiveUndoOnSwitch(appSettings.offloadInactiveTabs);
+ }, [
+ appSettings.tileMemoryBudgetMb,
+ appSettings.undoRamSteps,
+ appSettings.offloadInactiveTabs,
+ ]);
+
+ useEffect(() => {
+ performanceManager.registerMemoryHooks({
+ getActiveTileBytes: () => documentStore.getTotalActiveTileBytes(),
+ getTileBudgetBytes: () => documentStore.getTileBudgetBytes(),
+ getUndoStats: () => documentStore.getUndoMemoryStats(),
+ getActiveSessionIds: () => documentStore.getActiveSessionIds(),
+ purgeTiles: () => documentStore.purgeTileMemory(),
+ purgeUndo: () => documentStore.purgeUndoMemory(),
+ flushBrushGpuCaches: () => WebGlBrushEngine.getInstance().releaseCaches(),
+ });
+
+ let cancelled = false;
+ const current = useUiStore.getState().appSettings;
+ if (current.autoOptimizePerformance !== false) {
+ performanceManager
+ .detectHardwareInfo(false)
+ .then((hw) => {
+ if (cancelled) return;
+ const latest = useUiStore.getState().appSettings;
+ if (latest.autoOptimizePerformance === false) return;
+ const rec = computeRecommendedSettings(hw);
+ const next: AppSettings = { ...latest, ...rec.settings };
+ const changed = (
+ Object.keys(rec.settings) as Array<keyof AppSettings>
+ ).some((k) => latest[k] !== next[k]);
+ if (changed) {
+ uiStoreActions.updateAppSettings(next);
+ documentStore.setTileBudgetMb(next.tileMemoryBudgetMb || 1024);
+ documentStore.setSharedUndoRamStepsBudget(next.undoRamSteps || 15);
+ documentStore.setOffloadInactiveUndoOnSwitch(next.offloadInactiveTabs);
+ WebGlBrushEngine.getInstance().reconfigureFromPerformance();
+ }
+ void performanceManager.syncDesktopBackendConfig(next);
+ })
+ .catch(() => {
+ void performanceManager.syncDesktopBackendConfig(current);
+ });
+ } else {
+ void performanceManager.syncDesktopBackendConfig(current);
+ }
+
+ return () => {
+ cancelled = true;
+ performanceManager.registerMemoryHooks(null);
+ };
+ }, []);
// 3. Auto-create initial white canvas on launch
const hasAutoCreatedInitialDocRef = useRef(false);
@@ -1061,6 +1335,7 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =
pendingFitDimsRef.current = initDims;
resetZoomAndCenter(initDims);
resetHistory(newDocId);
+ artworkTimeTracker.initDocument(newDocId, 0);
documentStoreActions.setDocuments([
{
id: newDocId,
@@ -1071,6 +1346,7 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =
activeLayerId: topId,
perspectiveRuler: null,
defaultFrequency: 60,
+ workTimeMs: 0,
},
]);
documentStoreActions.setActiveDocumentId(newDocId);
@@ -1128,6 +1404,7 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =
layers: doc?.layers || cur.layers,
activeLayerId: doc?.activeLayerId || cur.activeLayerId,
timestamp: Date.now(),
+ workTimeMs: artworkTimeTracker.getWorkTimeMs(activeDocumentId),
};
},
async () => {
@@ -1237,6 +1514,139 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =
onSelectDocument(pendingCloseDocId);
}, [pendingCloseDocId, onSelectDocument]);
+ // 8. Smart, action-gated artwork time tracking (never starts until genuine artwork action; adapts to drawing cadence)
+ const isWorkspaceTimeTrackable = Boolean(
+ activeDocumentId && appView === 'workspace' && !isLoadingFile
+ );
+
+ useEffect(() => {
+ artworkTimeTracker.setActiveDocument(activeDocumentId, isWorkspaceTimeTrackable);
+ }, [activeDocumentId, isWorkspaceTimeTrackable]);
+
+ // Detect genuine layer structure/property edits on the active document (ignores doc switch / initial mount)
+ const lastTrackedLayersRef = useRef<{ docId: string | null; layers: LayerItem[] }>({
+ docId: null,
+ layers,
+ });
+ useEffect(() => {
+ if (!isWorkspaceTimeTrackable || !activeDocumentId) {
+ lastTrackedLayersRef.current = { docId: activeDocumentId, layers };
+ return;
+ }
+ const prev = lastTrackedLayersRef.current;
+ if (prev.docId === activeDocumentId && hasMeaningfulLayerEdit(prev.layers, layers)) {
+ artworkTimeTracker.recordArtworkAction(activeDocumentId);
+ }
+ lastTrackedLayersRef.current = { docId: activeDocumentId, layers };
+ }, [activeDocumentId, isWorkspaceTimeTrackable, layers]);
+
+ // Detect genuine canvas pixel/tile mutations (strokes, undo/redo, paste, filters, tonal edits, fills)
+ useEffect(() => {
+ if (!isWorkspaceTimeTrackable || !activeDocumentId) return;
+ const tileGrid = documentStore.getSession(activeDocumentId)?.tileGrid;
+ if (!tileGrid || typeof tileGrid.subscribe !== 'function') return;
+
+ let lastContentVersion =
+ typeof tileGrid.getContentVersion === 'function' ? tileGrid.getContentVersion() : 0;
+
+ return tileGrid.subscribe(() => {
+ if (typeof tileGrid.getContentVersion !== 'function') return;
+ const nextVersion = tileGrid.getContentVersion();
+ if (nextVersion !== lastContentVersion) {
+ lastContentVersion = nextVersion;
+ artworkTimeTracker.recordArtworkAction(activeDocumentId);
+ }
+ });
+ }, [activeDocumentId, isWorkspaceTimeTrackable]);
+
+ useEffect(() => {
+ if (!isWorkspaceTimeTrackable || typeof window === 'undefined' || typeof document === 'undefined') {
+ return;
+ }
+
+ const isFocusedNow = () =>
+ document.visibilityState === 'visible' &&
+ (typeof document.hasFocus !== 'function' || document.hasFocus());
+
+ artworkTimeTracker.setWindowFocused(isFocusedNow());
+
+ let lastSupportReportAt = 0;
+ let lastStylusReportAt = 0;
+
+ const isInsideInfoPanel = (target: EventTarget | null): boolean => {
+ if (!target || typeof Element === 'undefined' || !(target instanceof Element)) {
+ return false;
+ }
+ return Boolean(target.closest('[data-testid="info-panel"]'));
+ };
+
+ // Supporting workspace interactions (zoom, shortcuts, tool/color clicks, active drags):
+ // NEVER wake an idle timer; only sustain an already-active artwork session up to the safety cap.
+ const handleSupportingEvent = (e: Event) => {
+ if (isInsideInfoPanel(e.target)) return;
+ const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ if (now - lastSupportReportAt >= 350) {
+ lastSupportReportAt = now;
+ artworkTimeTracker.recordSupportingActivity();
+ }
+ };
+
+ const handlePointerMove = (e: PointerEvent) => {
+ // Hovering without holding a button never counts as activity
+ if (e.buttons === 0 || isInsideInfoPanel(e.target)) return;
+ const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ if (now - lastSupportReportAt >= 350) {
+ lastSupportReportAt = now;
+ artworkTimeTracker.recordSupportingActivity();
+ }
+ };
+
+ // Native WinTab / Windows Ink stylus pressure stream (bypasses DOM pointer events)
+ const handleCanvasPointerStat = (e: Event) => {
+ const detail = (e as CustomEvent<{ x: number | null; y: number | null; pressure: number }>)
+ .detail;
+ if (!detail || (detail.pressure ?? 0) <= 0) return;
+ const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ if (now - lastStylusReportAt >= 350) {
+ lastStylusReportAt = now;
+ artworkTimeTracker.recordArtworkAction();
+ }
+ };
+
+ const handleBlur = () => {
+ artworkTimeTracker.setWindowFocused(false);
+ };
+
+ const handleFocus = () => {
+ artworkTimeTracker.setWindowFocused(document.visibilityState === 'visible');
+ };
+
+ const handleVisibilityChange = () => {
+ artworkTimeTracker.setWindowFocused(isFocusedNow());
+ };
+
+ window.addEventListener('pointerdown', handleSupportingEvent, { passive: true });
+ window.addEventListener('pointermove', handlePointerMove, { passive: true });
+ window.addEventListener('wheel', handleSupportingEvent, { passive: true });
+ window.addEventListener('keydown', handleSupportingEvent, { passive: true });
+ window.addEventListener('canvas-pointer-stat', handleCanvasPointerStat);
+ window.addEventListener('blur', handleBlur);
+ window.addEventListener('focus', handleFocus);
+ document.addEventListener('visibilitychange', handleVisibilityChange);
+
+ return () => {
+ artworkTimeTracker.flush();
+ window.removeEventListener('pointerdown', handleSupportingEvent);
+ window.removeEventListener('pointermove', handlePointerMove);
+ window.removeEventListener('wheel', handleSupportingEvent);
+ window.removeEventListener('keydown', handleSupportingEvent);
+ window.removeEventListener('canvas-pointer-stat', handleCanvasPointerStat);
+ window.removeEventListener('blur', handleBlur);
+ window.removeEventListener('focus', handleFocus);
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
+ };
+ }, [isWorkspaceTimeTrackable]);
+
return null;
}
);
diff --git a/src/components/InfoPanel.tsx b/src/components/InfoPanel.tsx
new file mode 100644
index 0000000..4a79799
--- /dev/null
+++ b/src/components/InfoPanel.tsx
@@ -0,0 +1,352 @@
+import React, { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
+import { Clock, Crosshair, Layers, Cpu, Monitor, Trash2 } from 'lucide-react';
+import { CanvasColorMode, LayerItem } from '../types/editor';
+import { ThemePreset, hexToRgb } from '../types/settings';
+import { useDocumentStore, useToolStore, uiStoreActions } from '../stores';
+import { documentStore } from '../utils/documentStore';
+import { performanceManager } from '../utils/performanceManager';
+import {
+ ArtworkTimeTracker,
+ artworkTimeTracker,
+ formatWorkTimeClock,
+ formatWorkTimeHoursMinutes,
+} from '../utils/artworkTimeTracker';
+
+function rgbToHsv(r: number, g: number, b: number): { h: number; s: number; v: number } {
+ const rn = r / 255;
+ const gn = g / 255;
+ const bn = b / 255;
+ const max = Math.max(rn, gn, bn);
+ const min = Math.min(rn, gn, bn);
+ const d = max - min;
+ let h = 0;
+ if (d !== 0) {
+ if (max === rn) h = ((gn - bn) / d) % 6;
+ else if (max === gn) h = (bn - rn) / d + 2;
+ else h = (rn - gn) / d + 4;
+ h = Math.round(h * 60);
+ if (h < 0) h += 360;
+ }
+ const s = max === 0 ? 0 : Math.round((d / max) * 100);
+ const v = Math.round(max * 100);
+ return { h, s, v };
+}
+
+function formatColorModeLabel(mode: CanvasColorMode): string {
+ switch (mode) {
+ case 'monochrome':
+ return '1-bit Mono';
+ case 'grayscale':
+ return 'Grayscale';
+ case 'color':
+ default:
+ return 'RGB Color';
+ }
+}
+
+export interface InfoPanelProps {
+ layers?: LayerItem[];
+ colorMode?: CanvasColorMode;
+ themePreset?: ThemePreset;
+ /** Optional custom tracker instance (primarily for unit tests). */
+ tracker?: ArtworkTimeTracker;
+}
+
+export const InfoPanel: React.FC<InfoPanelProps> = React.memo(
+ ({ layers = [], colorMode: colorModeProp, themePreset = 'modern', tracker = artworkTimeTracker }) => {
+ const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
+ const dimensions = useDocumentStore((s) => s.dimensions);
+ const storeColorMode = useDocumentStore((s) => s.colorMode);
+ const primaryColor = useToolStore((s) => s.primaryColor);
+ const colorMode = colorModeProp ?? storeColorMode;
+
+ const getSnapshot = useCallback(
+ () => tracker.getSnapshot(activeDocumentId),
+ [tracker, activeDocumentId]
+ );
+
+ const timeSnap = useSyncExternalStore(tracker.subscribe, getSnapshot, getSnapshot);
+
+ // Zero-rerender live cursor X / Y / Pressure readout via canvas-pointer-stat
+ const posXRef = useRef<HTMLSpanElement | null>(null);
+ const posYRef = useRef<HTMLSpanElement | null>(null);
+ const pressureRef = useRef<HTMLSpanElement | null>(null);
+
+ useEffect(() => {
+ if (typeof window === 'undefined') return;
+ let rafId = 0;
+ let latest: { x: number | null; y: number | null; pressure: number } | null = null;
+
+ const handlePointerStat = (e: Event) => {
+ latest = (e as CustomEvent).detail;
+ cancelAnimationFrame(rafId);
+ rafId = requestAnimationFrame(() => {
+ if (!latest) return;
+ const hasCoords =
+ latest.x !== null &&
+ latest.y !== null &&
+ latest.x !== undefined &&
+ latest.y !== undefined;
+ if (posXRef.current) {
+ posXRef.current.textContent = hasCoords ? String(latest.x) : '—';
+ }
+ if (posYRef.current) {
+ posYRef.current.textContent = hasCoords ? String(latest.y) : '—';
+ }
+ if (pressureRef.current) {
+ const pct = Math.round((latest.pressure || 0) * 100);
+ pressureRef.current.textContent = `${pct}%`;
+ }
+ });
+ };
+
+ window.addEventListener('canvas-pointer-stat', handlePointerStat);
+ return () => {
+ window.removeEventListener('canvas-pointer-stat', handlePointerStat);
+ cancelAnimationFrame(rafId);
+ };
+ }, []);
+
+ // Lightweight periodic memory & renderer poll (every 2s while Info tab is visible)
+ const [memoryStats, setMemoryStats] = useState<{
+ usedMb: number;
+ budgetMb: number;
+ backend: 'webgl2' | 'canvas2d';
+ vramMb: number;
+ }>(() => {
+ const cfg = performanceManager.getConfig();
+ return {
+ usedMb: Math.round((documentStore.getTotalActiveTileBytes() / (1024 * 1024)) * 10) / 10,
+ budgetMb: Math.max(1, Math.round(documentStore.getTileBudgetBytes() / (1024 * 1024))),
+ backend: cfg.renderBackend === 'canvas2d' ? 'canvas2d' : 'webgl2',
+ vramMb: 0,
+ };
+ });
+
+ useEffect(() => {
+ let active = true;
+ const updateMem = async () => {
+ const t = await performanceManager.getMemoryTelemetry();
+ if (!active) return;
+ const usedMb =
+ Math.round((documentStore.getTotalActiveTileBytes() / (1024 * 1024)) * 10) / 10;
+ const budgetMb = Math.max(
+ 1,
+ Math.round(documentStore.getTileBudgetBytes() / (1024 * 1024))
+ );
+ const backend = t.compositor.backend;
+ const vramMb = t.compositor.estimatedVramMb;
+ setMemoryStats((prev) =>
+ prev.usedMb === usedMb &&
+ prev.budgetMb === budgetMb &&
+ prev.backend === backend &&
+ prev.vramMb === vramMb
+ ? prev
+ : { usedMb, budgetMb, backend, vramMb }
+ );
+ };
+ void updateMem();
+ const id = setInterval(() => void updateMem(), 2000);
+ return () => {
+ active = false;
+ clearInterval(id);
+ };
+ }, []);
+
+ const colorBreakdown = useMemo(() => {
+ const rgb = hexToRgb(primaryColor) || { r: 0, g: 0, b: 0 };
+ const hsv = rgbToHsv(rgb.r, rgb.g, rgb.b);
+ return { rgb, hsv, hex: primaryColor.toUpperCase() };
+ }, [primaryColor]);
+
+ const visibleLayerCount = useMemo(
+ () => layers.filter((l) => l.visible).length,
+ [layers]
+ );
+
+ const memPercent = Math.min(100, Math.round((memoryStats.usedMb / memoryStats.budgetMb) * 100));
+
+ return (
+ <div
+ data-testid="info-panel"
+ data-theme-preset={themePreset}
+ className="flex flex-col h-full min-h-0 overflow-y-auto no-scrollbar select-none bg-[#202020] text-[#e5e5e5] p-2 gap-2 text-[11px]"
+ >
+ {/* Clean Automatic Artwork Time Counter (Text-Only, No Manual Controls) */}
+ <section
+ data-testid="info-work-time-section"
+ data-status={timeSnap.status}
+ className="rounded-md bg-[#181818] border border-white/[0.06] px-2 py-1.5 flex flex-col gap-1"
+ title="Automatically tracks active time spent drawing and editing this artwork"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <span className="flex items-center gap-1 text-[10px] text-[#8a8a8a]">
+ <Clock className="w-3 h-3 text-[#7a7a7a]" />
+ <span>Work Time</span>
+ </span>
+ <span
+ data-testid="info-work-time-hm"
+ className="font-mono tabular-nums text-[10px] text-[#8a8a8a]"
+ >
+ {formatWorkTimeHoursMinutes(timeSnap.accumulatedMs)}
+ </span>
+ </div>
+
+ <div className="flex items-baseline justify-between gap-2">
+ <span
+ data-testid="info-work-time-clock"
+ className="font-mono tabular-nums text-[15px] leading-tight font-medium text-[#f0f0f0] tracking-tight"
+ >
+ {formatWorkTimeClock(timeSnap.accumulatedMs)}
+ </span>
+ <span
+ data-testid="info-session-time"
+ className="font-mono tabular-nums text-[10px] text-[#7a7a7a]"
+ title="Time spent in the current session"
+ >
+ Session {formatWorkTimeClock(timeSnap.sessionMs)}
+ </span>
+ </div>
+ </section>
+
+ {/* CSP-Style Cursor Coordinates & Active Color */}
+ <section className="rounded-md bg-[#181818] border border-white/[0.06] p-2 flex flex-col gap-1.5">
+ <div className="flex items-center justify-between text-[10px] text-[#8a8a8a]">
+ <div className="flex items-center gap-1 uppercase tracking-wider font-medium">
+ <Crosshair className="w-3 h-3 text-[#7a7a7a]" />
+ <span>Cursor</span>
+ </div>
+ <span className="font-mono tabular-nums text-[#9a9a9a]">
+ P: <span ref={pressureRef} className="text-[#d4d4d4]">0%</span>
+ </span>
+ </div>
+
+ <div className="grid grid-cols-2 gap-1.5 font-mono tabular-nums text-[10px]">
+ <div className="flex items-center justify-between px-1.5 py-0.5 rounded bg-[#222222] border border-white/[0.04]">
+ <span className="text-[#7a7a7a]">X</span>
+ <span ref={posXRef} data-testid="info-cursor-x" className="text-[#e5e5e5]">
+ —
+ </span>
+ </div>
+ <div className="flex items-center justify-between px-1.5 py-0.5 rounded bg-[#222222] border border-white/[0.04]">
+ <span className="text-[#7a7a7a]">Y</span>
+ <span ref={posYRef} data-testid="info-cursor-y" className="text-[#e5e5e5]">
+ —
+ </span>
+ </div>
+ </div>
+
+ {/* Active Color RGB / HSV */}
+ <div className="flex items-center gap-2 pt-1 border-t border-white/[0.05]">
+ <div
+ className="w-6 h-6 rounded border border-white/[0.15] shrink-0 shadow-inner"
+ style={{ backgroundColor: colorBreakdown.hex }}
+ title={`Active Color: ${colorBreakdown.hex}`}
+ />
+ <div className="flex-1 min-w-0 grid grid-cols-2 gap-x-2 gap-y-0.5 font-mono tabular-nums text-[10px]">
+ <div className="flex justify-between">
+ <span className="text-[#7a7a7a]">R</span>
+ <span className="text-[#d4d4d4]">{colorBreakdown.rgb.r}</span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#7a7a7a]">H</span>
+ <span className="text-[#d4d4d4]">{colorBreakdown.hsv.h}°</span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#7a7a7a]">G</span>
+ <span className="text-[#d4d4d4]">{colorBreakdown.rgb.g}</span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#7a7a7a]">S</span>
+ <span className="text-[#d4d4d4]">{colorBreakdown.hsv.s}%</span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#7a7a7a]">B</span>
+ <span className="text-[#d4d4d4]">{colorBreakdown.rgb.b}</span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#7a7a7a]">V</span>
+ <span className="text-[#d4d4d4]">{colorBreakdown.hsv.v}%</span>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ {/* Canvas & Memory Info (CSP Info Palette Style) */}
+ <section className="rounded-md bg-[#181818] border border-white/[0.06] p-2 flex flex-col gap-1">
+ <div className="flex items-center justify-between text-[10px]">
+ <span className="text-[#8a8a8a]">Canvas</span>
+ <span className="font-mono tabular-nums text-[#d4d4d4]">
+ {dimensions.width} × {dimensions.height} px
+ </span>
+ </div>
+ <div className="flex items-center justify-between text-[10px]">
+ <span className="text-[#8a8a8a]">Resolution</span>
+ <span className="font-mono tabular-nums text-[#d4d4d4]">
+ {dimensions.dpi ?? 300} dpi · {formatColorModeLabel(colorMode)}
+ </span>
+ </div>
+ <div className="flex items-center justify-between text-[10px]">
+ <span className="text-[#8a8a8a] flex items-center gap-1">
+ <Layers className="w-2.5 h-2.5 text-[#7a7a7a]" />
+ <span>Layers</span>
+ </span>
+ <span className="font-mono tabular-nums text-[#d4d4d4]">
+ {visibleLayerCount} / {layers.length}
+ </span>
+ </div>
+ <div className="flex items-center justify-between text-[10px]">
+ <span className="text-[#8a8a8a] flex items-center gap-1">
+ <Monitor className="w-2.5 h-2.5 text-[#7a7a7a]" />
+ <span>Engine</span>
+ </span>
+ <span className="font-mono tabular-nums text-[#d4d4d4]">
+ {memoryStats.backend === 'webgl2'
+ ? `WebGL2${memoryStats.vramMb > 0 ? ` · ${memoryStats.vramMb} MB` : ''}`
+ : 'Canvas 2D (CPU)'}
+ </span>
+ </div>
+ <div className="flex flex-col gap-1 pt-1 mt-0.5 border-t border-white/[0.05]">
+ <div className="flex items-center justify-between text-[10px]">
+ <span className="text-[#8a8a8a] flex items-center gap-1">
+ <Cpu className="w-2.5 h-2.5 text-[#7a7a7a]" />
+ <span>Tile RAM</span>
+ </span>
+ <div className="flex items-center gap-1.5">
+ <span className="font-mono tabular-nums text-[#d4d4d4]">
+ {memoryStats.usedMb} / {memoryStats.budgetMb} MB
+ </span>
+ <button
+ type="button"
+ onClick={async () => {
+ const res = await performanceManager.purgeMemory('all');
+ uiStoreActions.showToast(
+ res.freedTileMb > 0 || res.offloadedUndoSteps > 0
+ ? `Freed ${res.freedTileMb} MB tiles, ${res.offloadedUndoSteps} undo steps`
+ : 'Memory & GPU caches flushed'
+ );
+ }}
+ className="p-0.5 rounded text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-white/10 transition-colors cursor-pointer"
+ title="Purge Tile, Undo & GPU Caches"
+ >
+ <Trash2 className="w-2.5 h-2.5" />
+ </button>
+ </div>
+ </div>
+ <div className="w-full h-1 rounded-full bg-white/[0.08] overflow-hidden">
+ <div
+ className="h-full rounded-full transition-all duration-300"
+ style={{
+ width: `${memPercent}%`,
+ backgroundColor: memPercent > 85 ? '#f43f5e' : 'var(--accent)',
+ }}
+ />
+ </div>
+ </div>
+ </section>
+ </div>
+ );
+ }
+);
+
+InfoPanel.displayName = 'InfoPanel';
diff --git a/src/components/Local3DContainer.tsx b/src/components/Local3DContainer.tsx
index ce56674..34d022f 100644
--- a/src/components/Local3DContainer.tsx
+++ b/src/components/Local3DContainer.tsx
@@ -15,6 +15,7 @@ import {
createSafeWebGLRenderer,
disposeThreeResources,
} from '../services/bake3DService';
+import { performanceManager } from '../utils/performanceManager';
import {
createProceduralMannequin,
findHumanoidBones,
@@ -139,6 +140,10 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({
m.userData.silhouetteMaterial.dispose();
m.userData.silhouetteMaterial = null;
}
+ if (m.userData.shadedMaterial) {
+ m.userData.shadedMaterial.dispose();
+ m.userData.shadedMaterial = null;
+ }
if (m.userData.smoothMaterial) {
if (Array.isArray(m.userData.smoothMaterial)) {
m.userData.smoothMaterial.forEach((mat: THREE.Material) => mat.dispose());
@@ -233,11 +238,14 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({
if (mesh.userData.origMaterial && mesh.userData.hasCustomMaterial) {
mesh.material = mesh.userData.origMaterial;
} else {
- mesh.material = new THREE.MeshStandardMaterial({
- color: 0xe2e8f0,
- roughness: 0.35,
- metalness: 0.1,
- });
+ if (!mesh.userData.shadedMaterial) {
+ mesh.userData.shadedMaterial = new THREE.MeshStandardMaterial({
+ color: 0xe2e8f0,
+ roughness: 0.35,
+ metalness: 0.1,
+ });
+ }
+ mesh.material = mesh.userData.shadedMaterial;
}
}
});
@@ -265,7 +273,8 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({
const docAspect = dimensions.width / Math.max(1, dimensions.height);
- const MAX_PREVIEW = 1920;
+ const perf = performanceManager.getConfig();
+ const MAX_PREVIEW = perf.preview3DMaxResolution || 1920;
let previewW = dimensions.width;
let previewH = dimensions.height;
if (previewW > MAX_PREVIEW || previewH > MAX_PREVIEW) {
@@ -283,8 +292,8 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({
try {
renderer = createSafeWebGLRenderer({
alpha: true,
- antialias: true,
- powerPreference: 'high-performance',
+ antialias: perf.preview3DAntialias,
+ powerPreference: perf.gpuPowerPreference,
preserveDrawingBuffer: true,
});
} catch (err) {
@@ -397,15 +406,17 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({
transformControlsRef.current = transformControls;
transformHelperRef.current = transformHelper;
- // 8. Render Loop
+ // 8. Render Loop (skips GPU work while document/tab is hidden to save battery & VRAM bandwidth)
let running = true;
const animate = () => {
if (!running) return;
- try {
- controls.update();
- renderer.render(scene, camera);
- } catch (err) {
- console.warn('[3D Render Loop Error]:', err);
+ if (typeof document === 'undefined' || !document.hidden) {
+ try {
+ controls.update();
+ renderer.render(scene, camera);
+ } catch (err) {
+ console.warn('[3D Render Loop Error]:', err);
+ }
}
animFrameRef.current = requestAnimationFrame(animate);
};
diff --git a/src/components/PerformanceSettingsTab.tsx b/src/components/PerformanceSettingsTab.tsx
new file mode 100644
index 0000000..c6d0cb7
--- /dev/null
+++ b/src/components/PerformanceSettingsTab.tsx
@@ -0,0 +1,962 @@
+import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import {
+ Sparkles,
+ MemoryStick,
+ Monitor,
+ HardDrive,
+ ChevronDown,
+ ChevronRight,
+ RefreshCw,
+ Trash2,
+ RotateCw,
+ Check,
+ AlertTriangle,
+ SlidersHorizontal,
+} from 'lucide-react';
+import {
+ AppSettings,
+ CanvasFilteringQuality,
+ DEFAULT_APP_SETTINGS,
+ DesktopGraphicsApi,
+ GpuPowerPreference,
+ GpuTexturePoolPreset,
+ PerformancePresetId,
+ Preview3DMaxResolution,
+ RenderBackend,
+ ScratchDiskCompression,
+ ViewportResolutionScale,
+} from '../types/settings';
+import {
+ GPU_TEXTURE_POOL_CONFIGS,
+ LiveMemoryTelemetry,
+ PurgeScope,
+ SystemHardwareInfo,
+ buildPerformancePreset,
+ computeAdobeMemoryLimits,
+ computeRecommendedSettings,
+ memoryMbToPercent,
+ memoryPercentToMb,
+ performanceManager,
+} from '../utils/performanceManager';
+
+interface PerformanceSettingsTabProps {
+ settings: AppSettings;
+ isDesktopTauri: boolean;
+ onUpdateSettings: (next: AppSettings) => void;
+ onShowToast: (message: string) => void;
+}
+
+function formatMb(mb: number): string {
+ if (mb >= 1024) {
+ return `${(mb / 1024).toFixed(mb % 1024 === 0 ? 0 : 1)} GB`;
+ }
+ return `${Math.round(mb)} MB`;
+}
+
+function formatGpuKindLabel(kind: string): string {
+ switch (kind) {
+ case 'discrete':
+ return 'Dedicated';
+ case 'integrated':
+ return 'Integrated';
+ case 'software':
+ return 'Software';
+ default:
+ return 'GPU';
+ }
+}
+
+export const PerformanceSettingsTab: React.FC<PerformanceSettingsTabProps> = ({
+ settings: rawSettings,
+ isDesktopTauri,
+ onUpdateSettings,
+ onShowToast,
+}) => {
+ // Defensive merge so hot-reloaded or legacy partial settings objects never have undefined fields
+ const settings: AppSettings = useMemo(
+ () => ({
+ ...DEFAULT_APP_SETTINGS,
+ ...rawSettings,
+ }),
+ [rawSettings]
+ );
+
+ const [hwInfo, setHwInfo] = useState<SystemHardwareInfo | null>(null);
+ const [telemetry, setTelemetry] = useState<LiveMemoryTelemetry | null>(null);
+ const [isRefreshingHw, setIsRefreshingHw] = useState(false);
+ const [isPurging, setIsPurging] = useState(false);
+ const [showAdvanced, setShowAdvanced] = useState(false);
+ const [scratchPathInput, setScratchPathInput] = useState(settings.scratchDiskPath || '');
+ const [scratchError, setScratchError] = useState<string | null>(null);
+ const [isApplyingScratch, setIsApplyingScratch] = useState(false);
+
+ useEffect(() => {
+ setScratchPathInput(settings.scratchDiskPath || '');
+ }, [settings.scratchDiskPath]);
+
+ const refreshHardware = useCallback(async (force = false) => {
+ setIsRefreshingHw(true);
+ try {
+ const info = await performanceManager.detectHardwareInfo(force);
+ setHwInfo(info);
+ return info;
+ } finally {
+ setIsRefreshingHw(false);
+ }
+ }, []);
+
+ const refreshTelemetry = useCallback(async () => {
+ const t = await performanceManager.getMemoryTelemetry();
+ setTelemetry(t);
+ }, []);
+
+ useEffect(() => {
+ void refreshHardware(false);
+ void refreshTelemetry();
+ const id = setInterval(() => {
+ void refreshTelemetry();
+ }, 1500);
+ return () => clearInterval(id);
+ }, [refreshHardware, refreshTelemetry]);
+
+ const totalRamMb = hwInfo?.totalRamMb ?? 8192;
+ const cpuCores = hwInfo?.cpuLogicalCores ?? 4;
+ const memLimits = useMemo(() => computeAdobeMemoryLimits(totalRamMb), [totalRamMb]);
+
+ const recommended = useMemo(
+ () =>
+ computeRecommendedSettings(
+ hwInfo ?? {
+ totalRamMb,
+ cpuLogicalCores: cpuCores,
+ gpus: [],
+ activeWebGl: {
+ available: true,
+ renderer: 'WebGL2 GPU',
+ vendor: 'Generic',
+ glVersion: 'WebGL 2.0',
+ maxTextureSize: 4096,
+ maxArrayLayers: 256,
+ },
+ }
+ ),
+ [hwInfo, totalRamMb, cpuCores]
+ );
+
+ const currentBudgetMb = Math.max(
+ memLimits.minMb,
+ Math.min(memLimits.maxMb, settings.tileMemoryBudgetMb || 1024)
+ );
+ const currentPercent = memoryMbToPercent(currentBudgetMb, totalRamMb);
+ const isAutoMode = Boolean(settings.autoOptimizePerformance);
+
+ const patchManual = (patch: Partial<AppSettings>) => {
+ onUpdateSettings({
+ ...settings,
+ ...patch,
+ autoOptimizePerformance: false,
+ });
+ };
+
+ const handleEnableAuto = async (showFeedback = true) => {
+ const info = hwInfo ?? (await refreshHardware(false));
+ const rec = computeRecommendedSettings(info);
+ onUpdateSettings({
+ ...settings,
+ ...rec.settings,
+ autoOptimizePerformance: true,
+ });
+ if (showFeedback) {
+ onShowToast(`Automatic optimization enabled (${rec.summary})`);
+ }
+ };
+
+ const handleToggleAuto = (checked: boolean) => {
+ if (checked) {
+ void handleEnableAuto(true);
+ } else {
+ onUpdateSettings({ ...settings, autoOptimizePerformance: false });
+ }
+ };
+
+ const handleApplyPreset = (presetId: PerformancePresetId, label: string) => {
+ const presetPatch = buildPerformancePreset(presetId, totalRamMb);
+ onUpdateSettings({
+ ...settings,
+ ...presetPatch,
+ autoOptimizePerformance: false,
+ });
+ onShowToast(`Switched to "${label}" mode`);
+ };
+
+ const handlePercentSliderChange = (nextPct: number) => {
+ const nextMb = memoryPercentToMb(nextPct, totalRamMb);
+ patchManual({
+ memoryAllocationPercent: nextPct,
+ tileMemoryBudgetMb: nextMb,
+ });
+ };
+
+ const handleBudgetMbInputChange = (rawMb: number) => {
+ if (!Number.isFinite(rawMb)) return;
+ const clampedMb = Math.max(memLimits.minMb, Math.min(memLimits.maxMb, Math.round(rawMb)));
+ const nextPct = memoryMbToPercent(clampedMb, totalRamMb);
+ patchManual({
+ tileMemoryBudgetMb: clampedMb,
+ memoryAllocationPercent: nextPct,
+ });
+ };
+
+ const handlePurge = async (scope: PurgeScope) => {
+ if (isPurging) return;
+ setIsPurging(true);
+ try {
+ const res = await performanceManager.purgeMemory(scope);
+ await refreshTelemetry();
+ const parts: string[] = [];
+ if (res.freedTileMb > 0) parts.push(`${res.freedTileMb} MB tiles`);
+ if (res.offloadedUndoSteps > 0) parts.push(`${res.offloadedUndoSteps} undo steps`);
+ if (res.flushedGpuTextures) parts.push('GPU cache');
+ if (res.freedScratchDiskMb > 0) parts.push(`${res.freedScratchDiskMb} MB scratch`);
+ onShowToast(
+ parts.length > 0 ? `Freed ${parts.join(', ')}` : 'Memory caches are already clean'
+ );
+ } finally {
+ setIsPurging(false);
+ }
+ };
+
+ const handleApplyScratchPath = async (nextPath: string) => {
+ setScratchError(null);
+ setIsApplyingScratch(true);
+ try {
+ const candidate: AppSettings = { ...settings, scratchDiskPath: nextPath.trim() };
+ const result = await performanceManager.syncDesktopBackendConfig(candidate);
+ if (!result.ok) {
+ setScratchError(result.error || 'Unable to validate scratch disk directory');
+ return;
+ }
+ if (result.info) {
+ setHwInfo(result.info);
+ }
+ onUpdateSettings(candidate);
+ onShowToast(
+ nextPath.trim()
+ ? 'Scratch disk location updated'
+ : 'Scratch disk reset to system temporary folder'
+ );
+ } finally {
+ setIsApplyingScratch(false);
+ }
+ };
+
+ const handleRelaunchDesktop = async () => {
+ if (!isDesktopTauri) return;
+ try {
+ await performanceManager.syncDesktopBackendConfig(settings);
+ const { relaunch } = await import('@tauri-apps/plugin-process');
+ await relaunch();
+ } catch (err) {
+ onShowToast(
+ err instanceof Error ? `Restart failed: ${err.message}` : 'Please restart Ink Studio manually'
+ );
+ }
+ };
+
+ const needsRestart = performanceManager.needsRestartForDesktopGpuFlags(settings);
+ const activeRendererName =
+ telemetry?.compositor?.rendererName || hwInfo?.activeWebGl?.renderer || 'Detecting...';
+ const activeRendererLower = activeRendererName.toLowerCase();
+ const activePoolSpec =
+ GPU_TEXTURE_POOL_CONFIGS[settings.gpuTexturePoolPreset] ?? GPU_TEXTURE_POOL_CONFIGS.high;
+ const workerThreadsValue = Number.isFinite(settings.cpuWorkerThreads)
+ ? settings.cpuWorkerThreads
+ : 0;
+
+ const barScaleMax = memLimits.totalRamMb;
+ const allocatedPctOfTotal = Math.min(100, (currentBudgetMb / barScaleMax) * 100);
+ const idealLeftPct = (memLimits.idealMinMb / barScaleMax) * 100;
+ const idealWidthPct = Math.max(
+ 4,
+ ((memLimits.idealMaxMb - memLimits.idealMinMb) / barScaleMax) * 100
+ );
+ const isOverIdeal = currentBudgetMb > memLimits.idealMaxMb;
+
+ return (
+ <div className="space-y-4" data-testid="performance-settings-tab">
+ {/* 1. Automatic Optimization Hero & Quick Mode Selector */}
+ <section className="rounded-md bg-[#161616] p-3.5 space-y-3 border border-white/[0.06]">
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex items-start gap-2.5 min-w-0">
+ <Sparkles className="w-4 h-4 text-[var(--accent)] mt-0.5 shrink-0" />
+ <div className="min-w-0">
+ <div className="flex items-center gap-2">
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Automatic Settings</h3>
+ {isAutoMode && (
+ <span className="text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/15 text-emerald-300 font-medium">
+ Active
+ </span>
+ )}
+ </div>
+ <p className="text-[11px] text-[#8a8a8a] mt-0.5">
+ {isAutoMode
+ ? `Automatically tuned for your hardware: ${recommended.summary}`
+ : 'Custom settings active. Turn on to let Ink Studio tune RAM, GPU, and caches automatically.'}
+ </p>
+ </div>
+ </div>
+
+ <label className="flex items-center gap-2 shrink-0 cursor-pointer pt-0.5">
+ <input
+ type="checkbox"
+ aria-label="Automatic performance settings"
+ checked={isAutoMode}
+ onChange={(e) => handleToggleAuto(e.target.checked)}
+ />
+ </label>
+ </div>
+
+ {/* Quick Mode Bar */}
+ <div className="grid grid-cols-4 gap-1.5">
+ <button
+ type="button"
+ onClick={() => void handleEnableAuto(true)}
+ className={`py-1.5 px-2 rounded text-[11px] transition-colors cursor-pointer ${
+ isAutoMode
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium ring-1 ring-[var(--accent-border)]'
+ : 'bg-[#202020] text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ Auto
+ </button>
+ <button
+ type="button"
+ onClick={() => handleApplyPreset('maximum', 'Max Performance')}
+ className={`py-1.5 px-2 rounded text-[11px] transition-colors cursor-pointer ${
+ !isAutoMode && settings.renderBackend === 'webgl2' && settings.gpuPowerPreference === 'high-performance'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium ring-1 ring-[var(--accent-border)]'
+ : 'bg-[#202020] text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ Performance
+ </button>
+ <button
+ type="button"
+ onClick={() => handleApplyPreset('battery', 'Battery Saver')}
+ className={`py-1.5 px-2 rounded text-[11px] transition-colors cursor-pointer ${
+ !isAutoMode && settings.gpuPowerPreference === 'low-power'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium ring-1 ring-[var(--accent-border)]'
+ : 'bg-[#202020] text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ Battery
+ </button>
+ <button
+ type="button"
+ onClick={() => handleApplyPreset('compatibility', 'CPU Safe Mode')}
+ className={`py-1.5 px-2 rounded text-[11px] transition-colors cursor-pointer ${
+ !isAutoMode && settings.renderBackend === 'canvas2d'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium ring-1 ring-[var(--accent-border)]'
+ : 'bg-[#202020] text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ CPU Safe
+ </button>
+ </div>
+
+ {/* Compact System Strip */}
+ <div className="flex items-center justify-between gap-2 pt-2 border-t border-white/[0.05] text-[10px] text-[#8a8a8a] font-mono">
+ <div className="flex items-center gap-2 min-w-0 truncate">
+ <span>{formatMb(totalRamMb)} RAM</span>
+ <span>·</span>
+ <span>{cpuCores} threads</span>
+ <span>·</span>
+ <span className="truncate text-[#cfcfcf]" title={activeRendererName}>
+ {telemetry?.compositor?.backend === 'canvas2d'
+ ? 'Canvas 2D (CPU)'
+ : activeRendererName}
+ </span>
+ </div>
+ <button
+ type="button"
+ onClick={() => {
+ void refreshHardware(true);
+ void refreshTelemetry();
+ }}
+ disabled={isRefreshingHw}
+ className="p-1 rounded hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer shrink-0 disabled:opacity-50"
+ title="Refresh hardware & memory telemetry"
+ >
+ <RefreshCw className={`w-3 h-3 ${isRefreshingHw ? 'animate-spin' : ''}`} />
+ </button>
+ </div>
+ </section>
+
+ {/* 2. Memory (RAM Limit) */}
+ <section className="rounded-md bg-[#161616] p-3.5 space-y-3 border border-white/[0.05]">
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <MemoryStick className="w-3.5 h-3.5 text-[var(--accent)]" />
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Memory Usage (Max RAM)</h3>
+ </div>
+ <div className="flex items-center gap-1.5 shrink-0">
+ <input
+ type="number"
+ aria-label="Maximum RAM in MB"
+ min={memLimits.minMb}
+ max={memLimits.maxMb}
+ step={128}
+ value={currentBudgetMb}
+ onChange={(e) => handleBudgetMbInputChange(Number(e.target.value))}
+ className="w-20 bg-[#202020] px-2 py-1 rounded font-mono text-xs text-right text-[#e5e5e5] border border-white/10"
+ />
+ <span className="text-[11px] font-mono text-[#8a8a8a]">MB ({currentPercent}%)</span>
+ </div>
+ </div>
+
+ <div className="space-y-1.5">
+ <div className="relative h-2 rounded-full bg-[#2a2a2a] overflow-hidden">
+ <div
+ className="absolute top-0 bottom-0 bg-emerald-500/20 border-x border-emerald-400/40"
+ style={{ left: `${idealLeftPct}%`, width: `${idealWidthPct}%` }}
+ title={`Ideal range: ${formatMb(memLimits.idealMinMb)} – ${formatMb(memLimits.idealMaxMb)}`}
+ />
+ <div
+ className="h-full rounded-full transition-all duration-150"
+ style={{
+ width: `${allocatedPctOfTotal}%`,
+ backgroundColor: isOverIdeal ? '#f59e0b' : 'var(--accent)',
+ }}
+ />
+ </div>
+
+ <input
+ type="range"
+ aria-label="RAM allocation percentage"
+ min={20}
+ max={85}
+ step={1}
+ value={currentPercent}
+ onChange={(e) => handlePercentSliderChange(Number(e.target.value))}
+ className="w-full"
+ />
+
+ <div className="flex items-center justify-between text-[10px] font-mono text-[#8a8a8a]">
+ <span>{formatMb(memLimits.minMb)}</span>
+ <span className="text-emerald-400/90">
+ Ideal: {formatMb(memLimits.idealMinMb)} – {formatMb(memLimits.idealMaxMb)}
+ </span>
+ <span>{formatMb(memLimits.maxMb)}</span>
+ </div>
+ </div>
+
+ {isOverIdeal && (
+ <div className="flex items-center gap-1.5 text-[10px] text-amber-300 bg-amber-500/10 border border-amber-500/30 rounded px-2 py-1">
+ <AlertTriangle className="w-3 h-3 shrink-0" />
+ <span>Above 70% of system RAM may slow down other apps.</span>
+ </div>
+ )}
+
+ {/* Compact Live Usage + Single Free Memory Action */}
+ <div className="flex items-center justify-between gap-2 pt-2 border-t border-white/[0.05]">
+ <div className="text-[10px] font-mono text-[#8a8a8a] truncate">
+ {telemetry
+ ? `In use: ${telemetry.activeTileMb} MB tiles · ${telemetry.ramUndoSteps} undo · ~${telemetry.compositor.estimatedVramMb} MB VRAM`
+ : 'Measuring memory usage...'}
+ </div>
+ <button
+ type="button"
+ disabled={isPurging}
+ onClick={() => void handlePurge('all')}
+ className="flex items-center gap-1 px-2.5 py-1 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[10px] text-[#e5e5e5] font-medium cursor-pointer shrink-0 disabled:opacity-50"
+ title="Offload inactive tiles & undo states and flush GPU texture cache"
+ >
+ <Trash2 className="w-3 h-3 text-[var(--accent)]" />
+ <span>Free Memory</span>
+ </button>
+ </div>
+ </section>
+
+ {/* 3. Graphics & Rendering */}
+ <section className="rounded-md bg-[#161616] p-3.5 space-y-3 border border-white/[0.05]">
+ <div className="flex items-center gap-2">
+ <Monitor className="w-3.5 h-3.5 text-[var(--accent)]" />
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Graphics & Rendering</h3>
+ </div>
+
+ <div className="grid grid-cols-3 gap-1.5">
+ {(
+ [
+ { id: 'auto', label: 'Auto (GPU)' },
+ { id: 'webgl2', label: 'WebGL2 GPU' },
+ { id: 'canvas2d', label: 'Canvas 2D (CPU)' },
+ ] as Array<{ id: RenderBackend; label: string }>
+ ).map((opt) => {
+ const selected = settings.renderBackend === opt.id;
+ return (
+ <button
+ key={opt.id}
+ type="button"
+ onClick={() => patchManual({ renderBackend: opt.id })}
+ className={`py-1.5 px-2 rounded text-[11px] transition-colors cursor-pointer ${
+ selected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium ring-1 ring-[var(--accent-border)]'
+ : 'bg-[#202020] text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {opt.label}
+ </button>
+ );
+ })}
+ </div>
+
+ <div className="flex items-center justify-between gap-3 pt-2 border-t border-white/[0.05]">
+ <span className="text-xs text-[#e5e5e5]">Graphics Card</span>
+ <select
+ aria-label="Graphics Card Preference"
+ disabled={settings.renderBackend === 'canvas2d'}
+ value={settings.gpuPowerPreference}
+ onChange={(e) =>
+ patchManual({ gpuPowerPreference: e.target.value as GpuPowerPreference })
+ }
+ className="bg-[#202020] text-[#e5e5e5] text-xs px-2.5 py-1.5 rounded border border-white/10 cursor-pointer disabled:opacity-40"
+ >
+ <option value="high-performance">High-Performance (Dedicated)</option>
+ <option value="low-power">Power-Saving (Integrated)</option>
+ <option value="default">System Default</option>
+ </select>
+ </div>
+
+ {/* Detected GPUs (compact rows) */}
+ {hwInfo && Array.isArray(hwInfo.gpus) && hwInfo.gpus.length > 0 && (
+ <div className="space-y-1 pt-2 border-t border-white/[0.05]">
+ {hwInfo.gpus.map((gpu) => {
+ const gpuName = gpu.name || 'Graphics Adapter';
+ const isActive =
+ telemetry?.compositor?.backend === 'webgl2' &&
+ gpuName.length > 0 &&
+ activeRendererLower.includes(gpuName.toLowerCase().slice(0, 14));
+ return (
+ <div
+ key={gpu.id}
+ className={`flex items-center justify-between gap-2 px-2.5 py-1.5 rounded text-[11px] ${
+ isActive ? 'bg-[#252525] ring-1 ring-[var(--accent-border)]' : 'bg-[#202020]'
+ }`}
+ >
+ <div className="flex items-center gap-1.5 min-w-0">
+ <span className="text-[#e5e5e5] truncate">{gpuName}</span>
+ <span className="text-[9px] px-1.5 py-0.5 rounded bg-[#161616] text-[#8a8a8a] shrink-0">
+ {formatGpuKindLabel(gpu.kind)}
+ {gpu.vramMb > 0 ? ` · ${formatMb(gpu.vramMb)}` : ''}
+ </span>
+ </div>
+ {isActive && (
+ <span className="flex items-center gap-1 text-[10px] font-medium text-emerald-400 shrink-0">
+ <Check className="w-3 h-3" />
+ Active
+ </span>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {needsRestart && (
+ <div className="flex items-center justify-between gap-2 p-2 rounded bg-amber-500/10 border border-amber-500/35 text-[11px]">
+ <span className="text-amber-200">
+ Restart Ink Studio to apply the OS-level GPU preference.
+ </span>
+ <button
+ type="button"
+ onClick={() => void handleRelaunchDesktop()}
+ className="flex items-center gap-1 px-2.5 py-1 rounded bg-amber-500 text-black font-medium shrink-0 cursor-pointer hover:opacity-90"
+ >
+ <RotateCw className="w-3 h-3" />
+ <span>Restart</span>
+ </button>
+ </div>
+ )}
+ </section>
+
+ {/* 4. Collapsible Advanced Settings */}
+ <section className="rounded-md bg-[#161616] border border-white/[0.05] overflow-hidden">
+ <button
+ type="button"
+ onClick={() => setShowAdvanced((v) => !v)}
+ aria-expanded={showAdvanced}
+ className="w-full px-3.5 py-2.5 flex items-center justify-between text-left hover:bg-[#1e1e1e] transition-colors cursor-pointer"
+ >
+ <div className="flex items-center gap-2">
+ <SlidersHorizontal className="w-3.5 h-3.5 text-[#8a8a8a]" />
+ <div>
+ <span className="text-xs font-medium text-[#e5e5e5]">Advanced Settings</span>
+ <span className="ml-2 text-[10px] text-[#8a8a8a]">
+ VRAM Cache, HiDPI, Undo, CPU Threads & Scratch Disk
+ </span>
+ </div>
+ </div>
+ {showAdvanced ? (
+ <ChevronDown className="w-3.5 h-3.5 text-[#8a8a8a]" />
+ ) : (
+ <ChevronRight className="w-3.5 h-3.5 text-[#8a8a8a]" />
+ )}
+ </button>
+
+ {showAdvanced && (
+ <div className="px-3.5 pb-3.5 pt-2 border-t border-white/[0.06] space-y-4">
+ {/* GPU & Display Tuning */}
+ <div className="space-y-2.5">
+ <div className="text-[10px] uppercase tracking-wider text-[#8a8a8a] font-medium">
+ GPU & Display
+ </div>
+
+ <div className="space-y-1.5">
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-[#e5e5e5]">GPU Tile Cache (VRAM)</span>
+ <span className="font-mono text-[10px] text-[#8a8a8a]">
+ {activePoolSpec.arrayLayers} slices
+ </span>
+ </div>
+ <div className="grid grid-cols-4 gap-1.5">
+ {(['low', 'balanced', 'high', 'ultra'] as GpuTexturePoolPreset[]).map((preset) => {
+ const spec = GPU_TEXTURE_POOL_CONFIGS[preset];
+ const selected = settings.gpuTexturePoolPreset === preset;
+ return (
+ <button
+ key={preset}
+ type="button"
+ disabled={settings.renderBackend === 'canvas2d'}
+ onClick={() => patchManual({ gpuTexturePoolPreset: preset })}
+ className={`py-1 px-1.5 rounded text-[10px] transition-colors cursor-pointer disabled:opacity-40 ${
+ selected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium ring-1 ring-[var(--accent-border)]'
+ : 'bg-[#202020] text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {spec.label}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-xs text-[#e5e5e5]">Viewport Resolution (HiDPI)</span>
+ <select
+ aria-label="Viewport Resolution Scaling"
+ value={settings.viewportResolutionScale}
+ onChange={(e) =>
+ patchManual({
+ viewportResolutionScale: e.target.value as ViewportResolutionScale,
+ })
+ }
+ className="bg-[#202020] text-[#e5e5e5] text-xs px-2 py-1 rounded border border-white/10 cursor-pointer"
+ >
+ <option value="native">Native Display DPI</option>
+ <option value="capped-2x">Capped 2× (Recommended)</option>
+ <option value="1x">Standard 1× (High FPS)</option>
+ <option value="0.75x">Performance 0.75×</option>
+ </select>
+ </div>
+
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-xs text-[#e5e5e5]">Zoom Texture Filtering</span>
+ <select
+ aria-label="Canvas Texture Filtering"
+ value={settings.canvasFilteringQuality}
+ onChange={(e) =>
+ patchManual({
+ canvasFilteringQuality: e.target.value as CanvasFilteringQuality,
+ })
+ }
+ className="bg-[#202020] text-[#e5e5e5] text-xs px-2 py-1 rounded border border-white/10 cursor-pointer"
+ >
+ <option value="auto">Auto (Crisp ≥200%)</option>
+ <option value="smooth">Always Smooth</option>
+ <option value="pixelated">Always Sharp (Nearest)</option>
+ </select>
+ </div>
+
+ {isDesktopTauri && (
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-xs text-[#e5e5e5]">Desktop Graphics API (ANGLE)</span>
+ <select
+ aria-label="Desktop Graphics API"
+ value={settings.desktopGraphicsApi}
+ onChange={(e) =>
+ patchManual({ desktopGraphicsApi: e.target.value as DesktopGraphicsApi })
+ }
+ className="bg-[#202020] text-[#e5e5e5] text-xs px-2 py-1 rounded border border-white/10 cursor-pointer"
+ >
+ <option value="auto">Auto (OS Default)</option>
+ <option value="d3d11">Direct3D 11</option>
+ <option value="vulkan">Vulkan</option>
+ <option value="gl">OpenGL</option>
+ <option value="warp">WARP (Software)</option>
+ </select>
+ </div>
+ )}
+
+ <label className="flex items-center justify-between py-0.5 cursor-pointer">
+ <span className="text-xs text-[#e5e5e5]">GPU Brush Acceleration</span>
+ <input
+ type="checkbox"
+ disabled={settings.renderBackend === 'canvas2d'}
+ checked={settings.gpuBrushAcceleration}
+ onChange={(e) => patchManual({ gpuBrushAcceleration: e.target.checked })}
+ />
+ </label>
+
+ <label className="flex items-center justify-between py-0.5 cursor-pointer">
+ <span className="text-xs text-[#e5e5e5]">Baked Layer Stack Cache</span>
+ <input
+ type="checkbox"
+ disabled={settings.renderBackend === 'canvas2d'}
+ checked={settings.layerStackCaching}
+ onChange={(e) => patchManual({ layerStackCaching: e.target.checked })}
+ />
+ </label>
+ </div>
+
+ {/* Undo & Multi-Tab Memory */}
+ <div className="space-y-2.5 pt-3 border-t border-white/[0.06]">
+ <div className="text-[10px] uppercase tracking-wider text-[#8a8a8a] font-medium">
+ Undo & Multi-Document Memory
+ </div>
+
+ <div className="space-y-1">
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-[#e5e5e5]">Max History States</span>
+ <span className="font-mono text-[11px] text-[#e5e5e5]">
+ {settings.maxHistorySteps}
+ </span>
+ </div>
+ <div className="grid grid-cols-6 gap-1">
+ {[25, 50, 75, 100, 150, 200].map((steps) => (
+ <button
+ key={steps}
+ type="button"
+ onClick={() => patchManual({ maxHistorySteps: steps })}
+ className={`py-1 rounded font-mono text-[10px] cursor-pointer ${
+ settings.maxHistorySteps === steps
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium ring-1 ring-[var(--accent-border)]'
+ : 'bg-[#202020] text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {steps}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="space-y-1">
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-[#e5e5e5]">In-RAM Undo Steps</span>
+ <span className="font-mono text-[11px] text-[#e5e5e5]">
+ {settings.undoRamSteps} steps
+ </span>
+ </div>
+ <input
+ type="range"
+ aria-label="In-RAM undo steps"
+ min={4}
+ max={50}
+ step={1}
+ value={settings.undoRamSteps}
+ onChange={(e) => patchManual({ undoRamSteps: Number(e.target.value) })}
+ className="w-full"
+ />
+ </div>
+
+ <label className="flex items-center justify-between py-0.5 cursor-pointer">
+ <span className="text-xs text-[#e5e5e5]">Offload Inactive Document Tabs</span>
+ <input
+ type="checkbox"
+ checked={settings.offloadInactiveTabs}
+ onChange={(e) => patchManual({ offloadInactiveTabs: e.target.checked })}
+ />
+ </label>
+
+ <div className="flex items-center justify-between gap-2 pt-1">
+ <span className="text-[10px] text-[#8a8a8a]">Granular Cache Purge</span>
+ <div className="flex items-center gap-1.5">
+ <button
+ type="button"
+ disabled={isPurging}
+ onClick={() => void handlePurge('tiles')}
+ className="px-2 py-1 rounded bg-[#202020] hover:bg-[#2c2c2c] text-[10px] text-[#e5e5e5] cursor-pointer disabled:opacity-50"
+ >
+ Tiles
+ </button>
+ <button
+ type="button"
+ disabled={isPurging}
+ onClick={() => void handlePurge('undo')}
+ className="px-2 py-1 rounded bg-[#202020] hover:bg-[#2c2c2c] text-[10px] text-[#e5e5e5] cursor-pointer disabled:opacity-50"
+ >
+ Undo
+ </button>
+ <button
+ type="button"
+ disabled={isPurging}
+ onClick={() => void handlePurge('gpu')}
+ className="px-2 py-1 rounded bg-[#202020] hover:bg-[#2c2c2c] text-[10px] text-[#e5e5e5] cursor-pointer disabled:opacity-50"
+ >
+ GPU
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* 3D & CPU Threading */}
+ <div className="space-y-2.5 pt-3 border-t border-white/[0.06]">
+ <div className="text-[10px] uppercase tracking-wider text-[#8a8a8a] font-medium">
+ 3D & CPU
+ </div>
+
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-xs text-[#e5e5e5]">3D Preview Resolution</span>
+ <div className="flex items-center gap-2">
+ <select
+ aria-label="3D Preview Resolution Cap"
+ value={settings.preview3DMaxResolution}
+ onChange={(e) =>
+ patchManual({
+ preview3DMaxResolution: Number(e.target.value) as Preview3DMaxResolution,
+ })
+ }
+ className="bg-[#202020] text-[#e5e5e5] text-xs px-2 py-1 rounded border border-white/10 cursor-pointer"
+ >
+ <option value={1024}>1024 px</option>
+ <option value={1920}>1920 px</option>
+ <option value={2560}>2560 px</option>
+ </select>
+ <label className="flex items-center gap-1 text-[11px] text-[#e5e5e5] cursor-pointer">
+ <input
+ type="checkbox"
+ checked={settings.preview3DAntialias}
+ onChange={(e) => patchManual({ preview3DAntialias: e.target.checked })}
+ />
+ <span>AA</span>
+ </label>
+ </div>
+ </div>
+
+ {isDesktopTauri && (
+ <>
+ <div className="space-y-1">
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-[#e5e5e5]">CPU Worker Threads</span>
+ <span className="font-mono text-[11px] text-[#e5e5e5]">
+ {workerThreadsValue === 0
+ ? `Auto (${cpuCores})`
+ : `${workerThreadsValue} / ${cpuCores}`}
+ </span>
+ </div>
+ <input
+ type="range"
+ aria-label="CPU worker threads"
+ min={0}
+ max={cpuCores}
+ step={1}
+ value={Math.min(workerThreadsValue, cpuCores)}
+ onChange={(e) => patchManual({ cpuWorkerThreads: Number(e.target.value) })}
+ className="w-full"
+ />
+ </div>
+
+ <label className="flex items-center justify-between py-0.5 cursor-pointer">
+ <span className="text-xs text-[#e5e5e5]">Native Rust Acceleration</span>
+ <input
+ type="checkbox"
+ checked={settings.useNativeRustAcceleration}
+ onChange={(e) =>
+ patchManual({ useNativeRustAcceleration: e.target.checked })
+ }
+ />
+ </label>
+ </>
+ )}
+ </div>
+
+ {/* Scratch Disk */}
+ <div className="space-y-2 pt-3 border-t border-white/[0.06]">
+ <div className="flex items-center justify-between">
+ <span className="text-[10px] uppercase tracking-wider text-[#8a8a8a] font-medium flex items-center gap-1.5">
+ <HardDrive className="w-3 h-3" />
+ <span>Scratch Disk</span>
+ </span>
+ <span
+ className="font-mono text-[10px] text-[#8a8a8a] truncate max-w-[260px]"
+ title={hwInfo?.scratchDiskPath}
+ >
+ {hwInfo?.scratchDiskPath || 'System Temp'}
+ {isDesktopTauri && hwInfo && hwInfo.scratchDiskFreeMb > 0
+ ? ` · ${formatMb(hwInfo.scratchDiskFreeMb)} free`
+ : ''}
+ </span>
+ </div>
+
+ {isDesktopTauri && (
+ <>
+ <div className="flex items-center gap-1.5">
+ <input
+ type="text"
+ value={scratchPathInput}
+ onChange={(e) => {
+ setScratchPathInput(e.target.value);
+ setScratchError(null);
+ }}
+ placeholder="Custom folder (optional, e.g. secondary SSD)"
+ className="flex-1 bg-[#202020] px-2.5 py-1 rounded font-mono text-[11px] text-[#e5e5e5] placeholder-[#8a8a8a]/50 border border-white/10"
+ />
+ <button
+ type="button"
+ disabled={isApplyingScratch}
+ onClick={() => void handleApplyScratchPath(scratchPathInput)}
+ className="px-2.5 py-1 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[11px] text-[#e5e5e5] font-medium cursor-pointer shrink-0 disabled:opacity-50"
+ >
+ Apply
+ </button>
+ {settings.scratchDiskPath && (
+ <button
+ type="button"
+ disabled={isApplyingScratch}
+ onClick={() => {
+ setScratchPathInput('');
+ void handleApplyScratchPath('');
+ }}
+ className="px-2 py-1 rounded bg-[#202020] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer shrink-0"
+ >
+ Reset
+ </button>
+ )}
+ </div>
+ {scratchError && <div className="text-[10px] text-red-400">{scratchError}</div>}
+
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-xs text-[#e5e5e5]">Scratch Compression</span>
+ <select
+ aria-label="Scratch Disk Compression"
+ value={settings.scratchDiskCompression}
+ onChange={(e) =>
+ patchManual({
+ scratchDiskCompression: e.target.value as ScratchDiskCompression,
+ })
+ }
+ className="bg-[#202020] text-[#e5e5e5] text-xs px-2 py-1 rounded border border-white/10 cursor-pointer"
+ >
+ <option value="lz4">LZ4 Fast (Recommended)</option>
+ <option value="none">Uncompressed</option>
+ </select>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ )}
+ </section>
+ </div>
+ );
+};
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index e5f45dd..6947dbe 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -8,6 +8,7 @@ import {
Paintbrush,
Keyboard,
SlidersHorizontal,
+ Gauge,
Info,
RotateCcw,
Check,
@@ -39,6 +40,7 @@ import {
import { CanvasColorMode } from '../types/editor';
import { DPI_PRESETS } from './NewCanvasModal';
import { PressureCurveEditor } from './PressureCurveEditor';
+import { PerformanceSettingsTab } from './PerformanceSettingsTab';
import {
CommandDefinition,
DEFAULT_COMMANDS,
@@ -57,7 +59,14 @@ interface SettingsModalProps {
onShowToast: (message: string) => void;
}
-type SettingsTab = 'appearance' | 'canvas' | 'brush' | 'shortcuts' | 'modifiers' | 'about';
+type SettingsTab =
+ | 'appearance'
+ | 'canvas'
+ | 'brush'
+ | 'performance'
+ | 'shortcuts'
+ | 'modifiers'
+ | 'about';
const MODIFIER_ACTION_OPTIONS: Array<{ value: ModifierAction; label: string }> = [
{ value: 'none', label: 'None' },
@@ -122,7 +131,10 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onShowToast,
}) => {
const [activeTab, setActiveTab] = useState<SettingsTab>('appearance');
- const [localSettings, setLocalSettings] = useState<AppSettings>(settings);
+ const [localSettings, setLocalSettings] = useState<AppSettings>(() => ({
+ ...DEFAULT_APP_SETTINGS,
+ ...settings,
+ }));
const [searchQuery, setSearchQuery] = useState<string>('');
const [selectedCategory, setSelectedCategory] = useState<'All' | ShortcutCategory>('All');
const [recordingCommandId, setRecordingCommandId] = useState<string | null>(null);
@@ -140,7 +152,10 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
const updateErrorMessage = useUpdaterStore((s) => s.errorMessage);
useEffect(() => {
- setLocalSettings(settings);
+ setLocalSettings({
+ ...DEFAULT_APP_SETTINGS,
+ ...settings,
+ });
}, [settings]);
useEffect(() => {
@@ -304,6 +319,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
{ id: 'appearance', label: 'Appearance', icon: <Palette className="w-3.5 h-3.5" /> },
{ id: 'canvas', label: 'Canvas', icon: <Layers className="w-3.5 h-3.5" /> },
{ id: 'brush', label: 'Brush & Stylus', icon: <Paintbrush className="w-3.5 h-3.5" /> },
+ { id: 'performance', label: 'Performance', icon: <Gauge className="w-3.5 h-3.5" /> },
{ id: 'shortcuts', label: 'Shortcuts', icon: <Keyboard className="w-3.5 h-3.5" /> },
{
id: 'modifiers',
@@ -616,26 +632,36 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
</div>
</section>
- <section className="space-y-2">
- <div className="flex items-center justify-between">
- <h3 className="text-xs font-medium text-[#e5e5e5]">Tile RAM Budget</h3>
- <span className="font-mono text-xs text-[#e5e5e5]">
- {localSettings.tileMemoryBudgetMb || 1024} MB
- </span>
+ <section className="p-3 rounded bg-[#161616] flex items-center justify-between gap-3">
+ <div>
+ <h3 className="text-xs font-medium text-[#e5e5e5]">RAM, GPU & Scratch Disk</h3>
+ <p className="text-[11px] text-[#8a8a8a]">
+ Configure RAM allocation ({localSettings.tileMemoryBudgetMb || 1024} MB), GPU adapter, and rendering optimization
+ </p>
</div>
- <input
- type="range"
- min="512"
- max="4096"
- step="128"
- value={localSettings.tileMemoryBudgetMb || 1024}
- onChange={(e) => handleChange('tileMemoryBudgetMb', Number(e.target.value))}
- className="w-full"
- />
+ <button
+ type="button"
+ onClick={() => setActiveTab('performance')}
+ className="px-2.5 py-1.5 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[11px] text-[#e5e5e5] font-medium shrink-0 cursor-pointer transition-colors"
+ >
+ Open Performance
+ </button>
</section>
</>
)}
+ {activeTab === 'performance' && (
+ <PerformanceSettingsTab
+ settings={localSettings}
+ isDesktopTauri={isDesktopTauri}
+ onUpdateSettings={(updated) => {
+ setLocalSettings(updated);
+ onUpdateSettings(updated);
+ }}
+ onShowToast={onShowToast}
+ />
+ )}
+
{activeTab === 'brush' && (
<>
<PressureCurveEditor
diff --git a/src/components/canvasArea/useCanvasPointerHandlers.ts b/src/components/canvasArea/useCanvasPointerHandlers.ts
index 86a8580..d36801c 100644
--- a/src/components/canvasArea/useCanvasPointerHandlers.ts
+++ b/src/components/canvasArea/useCanvasPointerHandlers.ts
@@ -11,6 +11,7 @@ import { CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
import { screenToCanvas } from '../../utils/canvasUtils';
import { resolvePointerModifierAction } from '../../utils/shortcutManager';
import { isNativePenStreamActive } from '../../utils/nativeTabletInput';
+import { artworkTimeTracker } from '../../utils/artworkTimeTracker';
import { toolStoreActions, useToolStore, useUiStore } from '../../stores';
import { extractCoalescedEvents, extractPredictedEvents } from './types';
@@ -301,6 +302,7 @@ export function useCanvasPointerHandlers({
if (e.nativeEvent) {
(e.nativeEvent as any).coalescedEvents = coalesced;
}
+ artworkTimeTracker.recordArtworkAction();
onPointerDown(e, coalesced);
};
diff --git a/src/components/canvasArea/useCompositorViewport.ts b/src/components/canvasArea/useCompositorViewport.ts
index bbe19c8..c80042b 100644
--- a/src/components/canvasArea/useCompositorViewport.ts
+++ b/src/components/canvasArea/useCompositorViewport.ts
@@ -1,4 +1,4 @@
-import React, { useEffect, useMemo, useRef } from 'react';
+import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
AnimationTimeline as AnimationTimelineType,
CanvasColorMode,
@@ -10,6 +10,11 @@ import { CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
import { ViewportCompositor } from '../../utils/compositor';
import { SparseTileGrid } from '../../utils/tileEngine';
import { getOnionSkinFrames } from '../../utils/animationEngine';
+import {
+ RuntimePerformanceConfig,
+ performanceManager,
+ resolveEffectiveDpr,
+} from '../../utils/performanceManager';
import {
CursorConfig,
formatArtboardTransform,
@@ -107,6 +112,58 @@ export function useCompositorViewport({
const viewportCanvasRef = useRef<HTMLCanvasElement | null>(null);
const compositorRef = useRef<ViewportCompositor | null>(null);
const viewportCssSizeRef = useRef<{ width: number; height: number } | null>(null);
+ const [perfConfig, setPerfConfig] = useState<RuntimePerformanceConfig>(() =>
+ performanceManager.getConfig()
+ );
+ const perfConfigRef = useRef<RuntimePerformanceConfig>(perfConfig);
+ perfConfigRef.current = perfConfig;
+
+ useEffect(() => {
+ return performanceManager.subscribe((next) => {
+ setPerfConfig(next);
+ });
+ }, []);
+
+ const compositorKey = `${perfConfig.renderBackend}:${perfConfig.gpuPowerPreference}:${perfConfig.gpuTexturePoolPreset}`;
+
+ const getEffectiveDpr = () =>
+ resolveEffectiveDpr(
+ typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1,
+ perfConfigRef.current.viewportResolutionScale
+ );
+
+ // Register live compositor telemetry & GPU cache flush hooks with performanceManager
+ useEffect(() => {
+ performanceManager.registerCompositorHooks({
+ getTelemetry: () => {
+ if (compositorRef.current) {
+ return compositorRef.current.getTelemetry();
+ }
+ return {
+ backend: perfConfigRef.current.renderBackend === 'canvas2d' ? 'canvas2d' : 'webgl2',
+ rendererName:
+ perfConfigRef.current.renderBackend === 'canvas2d'
+ ? 'Canvas 2D (CPU Software)'
+ : 'WebGL2',
+ arrayPoolUsed: 0,
+ arrayPoolCapacity: 0,
+ texture2DPoolUsed: 0,
+ estimatedVramMb: 0,
+ stackCacheHits: 0,
+ stackCacheRebuilds: 0,
+ };
+ },
+ flushGpuCaches: () => {
+ if (compositorRef.current) {
+ compositorRef.current.flushGpuCaches();
+ tileGridRef.current.notifyChange(true);
+ }
+ },
+ });
+ return () => {
+ performanceManager.registerCompositorHooks(null);
+ };
+ }, []);
const renderParamsRef = useRef({
effectiveLayers,
pan: livePan,
@@ -161,6 +218,7 @@ export function useCompositorViewport({
return {
dimensions: rp.dimensions,
showCheckerboard: rp.showCheckerboard,
+ bypassStackCache: !perfConfigRef.current.layerStackCaching,
devicePixelRatio: dpr,
onionSkinFrames: rp.onionSkinFrames,
softProof: rp.softProofSettings,
@@ -231,7 +289,7 @@ export function useCompositorViewport({
compositorRef.current = new ViewportCompositor(viewportCanvasRef.current);
}
if (compositorRef.current) {
- const dpr = window.devicePixelRatio || 1;
+ const dpr = getEffectiveDpr();
compositorRef.current.render(
rp.effectiveLayers,
{
@@ -260,7 +318,7 @@ export function useCompositorViewport({
if (rect.width > 0 && rect.height > 0) {
viewportCssSizeRef.current = { width: rect.width, height: rect.height };
}
- const dpr = window.devicePixelRatio || 1;
+ const dpr = getEffectiveDpr();
const w = Math.max(1, Math.round(rect.width * dpr));
const h = Math.max(1, Math.round(rect.height * dpr));
@@ -346,7 +404,14 @@ export function useCompositorViewport({
dprMql?.removeEventListener?.('change', handleDprChange);
ro?.disconnect();
};
- }, [viewportRef, effectiveDraftCanvasRef, effectivePredictedCanvasRef, hasOpenDocument]);
+ }, [
+ viewportRef,
+ effectiveDraftCanvasRef,
+ effectivePredictedCanvasRef,
+ hasOpenDocument,
+ compositorKey,
+ perfConfig.viewportResolutionScale,
+ ]);
useEffect(() => {
if (viewportRef.current) {
@@ -371,8 +436,9 @@ export function useCompositorViewport({
if (!compositorRef.current) {
compositorRef.current = new ViewportCompositor(vCanvas);
}
+ compositorRef.current.setFilteringQuality(perfConfig.canvasFilteringQuality);
- const dpr = window.devicePixelRatio || 1;
+ const dpr = getEffectiveDpr();
const rp = renderParamsRef.current;
compositorRef.current.render(
effectiveLayers,
@@ -387,7 +453,27 @@ export function useCompositorViewport({
tileGrid,
buildCompositorOptions(rp, dpr)
);
- }, [effectiveLayers, layers, pan, zoom, rotation, flipX, flipY, dimensions, showCheckerboard, onionSkinFrames, softProofSettings, activeLayerId, brushOpacity, colorMode, tileGrid]);
+ }, [
+ effectiveLayers,
+ layers,
+ pan,
+ zoom,
+ rotation,
+ flipX,
+ flipY,
+ dimensions,
+ showCheckerboard,
+ onionSkinFrames,
+ softProofSettings,
+ activeLayerId,
+ brushOpacity,
+ colorMode,
+ tileGrid,
+ compositorKey,
+ perfConfig.layerStackCaching,
+ perfConfig.canvasFilteringQuality,
+ perfConfig.viewportResolutionScale,
+ ]);
// Event-Driven Compositor Invalidation via active document's SparseTileGrid subscription
useEffect(() => {
@@ -395,7 +481,7 @@ export function useCompositorViewport({
const activeGrid = tileGrid;
const renderCompositor = () => {
if (compositorRef.current) {
- const dpr = window.devicePixelRatio || 1;
+ const dpr = getEffectiveDpr();
const rp = renderParamsRef.current;
compositorRef.current.render(
rp.effectiveLayers,
@@ -447,5 +533,6 @@ export function useCompositorViewport({
return {
viewportCanvasRef,
+ compositorKey,
};
}
diff --git a/src/engine/BrushEngine.ts b/src/engine/BrushEngine.ts
index 80c4177..8df2f2c 100644
--- a/src/engine/BrushEngine.ts
+++ b/src/engine/BrushEngine.ts
@@ -39,6 +39,7 @@ import {
rgbToHex,
} from '../utils/colorMixingEngine';
import { GpuDab, WebGlBrushEngine } from './WebGlBrushEngine';
+import { performanceManager } from '../utils/performanceManager';
import { isNaturalPaintBrush, renderCompleteNaturalPaintStroke } from './NaturalPaintRenderer';
// ============================================================================
@@ -1542,6 +1543,10 @@ function applyCpuPerPixelPaperGrain(
// ============================================================================
export function canUseWebGlForBrush(options?: BrushRenderOptions): boolean {
+ const perf = performanceManager.getConfig();
+ if (perf.renderBackend === 'canvas2d' || !perf.gpuBrushAcceleration) {
+ return false;
+ }
if (!options) return WebGlBrushEngine.getInstance().isAvailable();
if (options.useGpu === false) return false;
if (options.colorMixing) return false;
diff --git a/src/engine/WebGlBrushEngine.ts b/src/engine/WebGlBrushEngine.ts
index a66e9ac..a589369 100644
--- a/src/engine/WebGlBrushEngine.ts
+++ b/src/engine/WebGlBrushEngine.ts
@@ -1,5 +1,6 @@
import { Point, BrushSettings, ToolType, SurfaceTextureId, ImpastoSettings } from '../types/editor';
import { getSurfaceTextureHeightField, SURFACE_TEXTURE_SIZE } from '../utils/proceduralBrushTips';
+import { performanceManager } from '../utils/performanceManager';
export interface GpuInfo {
isSupported: boolean;
@@ -643,7 +644,26 @@ export class WebGlBrushEngine {
}
}
+ private activePowerPreference: WebGLPowerPreference = 'high-performance';
+
private constructor() {
+ this.initCanvasAndGl();
+ }
+
+ private initCanvasAndGl() {
+ const perf = performanceManager.getConfig();
+ if (perf.renderBackend === 'canvas2d' || !perf.gpuBrushAcceleration) {
+ this.isGpuAvailable = false;
+ this.gpuInfo = {
+ isSupported: false,
+ renderer: 'CPU Fallback (GPU Brush Disabled)',
+ vendor: 'Standard',
+ glVersion: 'None',
+ };
+ return;
+ }
+ this.activePowerPreference = perf.gpuPowerPreference || 'high-performance';
+
if (typeof document !== 'undefined') {
const c = document.createElement('canvas');
c.width = 1024;
@@ -653,20 +673,7 @@ export class WebGlBrushEngine {
c.addEventListener('webglcontextlost', (ev) => {
ev.preventDefault();
this.isGpuAvailable = false;
- this.tipTexturesMap.clear();
- this.multiTipAtlasCache.clear();
- this.surfaceTexturesMap.clear();
- this.builtinPaperTexture = null;
- this.canvasLayerTexture = null;
- this.canvasLayerWidth = 0;
- this.canvasLayerHeight = 0;
- this.canvasLayerSource = null;
- this.impastoColorTex = null;
- this.impastoHeightTex = null;
- this.dabFbo = null;
- this.dabFboTex = null;
- this.dabFboWidth = 0;
- this.dabFboHeight = 0;
+ this.clearTextureMapsState();
});
c.addEventListener('webglcontextrestored', () => {
this.initGl();
@@ -676,6 +683,94 @@ export class WebGlBrushEngine {
}
}
+ private clearTextureMapsState() {
+ this.tipTexturesMap.clear();
+ this.multiTipAtlasCache.clear();
+ this.surfaceTexturesMap.clear();
+ this.builtinPaperTexture = null;
+ this.canvasLayerTexture = null;
+ this.canvasLayerWidth = 0;
+ this.canvasLayerHeight = 0;
+ this.canvasLayerSource = null;
+ this.impastoColorTex = null;
+ this.impastoHeightTex = null;
+ this.dabFbo = null;
+ this.dabFboTex = null;
+ this.dabFboWidth = 0;
+ this.dabFboHeight = 0;
+ }
+
+ /**
+ * Releases cached brush tip/surface/layer textures to immediately reclaim GPU VRAM.
+ */
+ public releaseCaches(): void {
+ const gl = this.gl;
+ if (gl) {
+ for (const tex of this.tipTexturesMap.values()) gl.deleteTexture(tex);
+ for (const entry of this.multiTipAtlasCache.values()) gl.deleteTexture(entry.tex);
+ for (const tex of this.surfaceTexturesMap.values()) gl.deleteTexture(tex);
+ if (this.canvasLayerTexture) gl.deleteTexture(this.canvasLayerTexture);
+ if (this.impastoColorTex) gl.deleteTexture(this.impastoColorTex);
+ if (this.impastoHeightTex) gl.deleteTexture(this.impastoHeightTex);
+ }
+ this.tipTexturesMap.clear();
+ this.multiTipAtlasCache.clear();
+ this.surfaceTexturesMap.clear();
+ this.canvasLayerTexture = null;
+ this.canvasLayerWidth = 0;
+ this.canvasLayerHeight = 0;
+ this.canvasLayerSource = null;
+ this.impastoColorTex = null;
+ this.impastoHeightTex = null;
+ }
+
+ /**
+ * Reconfigures GPU brush engine when renderBackend, gpuPowerPreference, or gpuBrushAcceleration changes.
+ */
+ public reconfigureFromPerformance(): void {
+ const perf = performanceManager.getConfig();
+ const shouldEnable = perf.renderBackend !== 'canvas2d' && perf.gpuBrushAcceleration;
+ const nextPower: WebGLPowerPreference = perf.gpuPowerPreference || 'high-performance';
+
+ if (!shouldEnable) {
+ this.releaseCaches();
+ if (this.gl) {
+ this.gl.getExtension?.('WEBGL_lose_context')?.loseContext?.();
+ }
+ this.gl = null;
+ this.program = null;
+ this.ribbonProgram = null;
+ this.impastoProgram = null;
+ this.canvas = null;
+ this.isGpuAvailable = false;
+ this.clearTextureMapsState();
+ this.gpuInfo = {
+ isSupported: false,
+ renderer: 'CPU Fallback (GPU Brush Disabled)',
+ vendor: 'Standard',
+ glVersion: 'None',
+ };
+ return;
+ }
+
+ if (this.isGpuAvailable && this.activePowerPreference === nextPower) {
+ return;
+ }
+
+ this.releaseCaches();
+ if (this.gl) {
+ this.gl.getExtension?.('WEBGL_lose_context')?.loseContext?.();
+ }
+ this.gl = null;
+ this.program = null;
+ this.ribbonProgram = null;
+ this.impastoProgram = null;
+ this.canvas = null;
+ this.isGpuAvailable = false;
+ this.clearTextureMapsState();
+ this.initCanvasAndGl();
+ }
+
public static getInstance(): WebGlBrushEngine {
if (!WebGlBrushEngine.instance) {
WebGlBrushEngine.instance = new WebGlBrushEngine();
@@ -696,7 +791,7 @@ export class WebGlBrushEngine {
stencil: false,
premultipliedAlpha: true,
preserveDrawingBuffer: true,
- powerPreference: 'high-performance',
+ powerPreference: this.activePowerPreference,
};
const gl2 = this.canvas.getContext('webgl2', glOpts) as WebGL2RenderingContext | null;
diff --git a/src/hooks/drawing/useDrawingHistory.ts b/src/hooks/drawing/useDrawingHistory.ts
index 1472888..19418ed 100644
--- a/src/hooks/drawing/useDrawingHistory.ts
+++ b/src/hooks/drawing/useDrawingHistory.ts
@@ -19,6 +19,7 @@ import {
} from '../../utils/tileEngine';
import { UndoCacheManager, globalUndoCache } from '../../utils/undoCache';
import { documentStore } from '../../utils/documentStore';
+import { performanceManager } from '../../utils/performanceManager';
import { multiplayerService } from '../../services/multiplayerService';
import { recoveryService } from '../../services/recoveryService';
import { renderVectorLayer } from '../../utils/vectorEngine';
@@ -296,7 +297,11 @@ export function useDrawingHistory({
const newHistory = historyRef.current.slice(0, historyIndexRef.current + 1);
newHistory.push(item);
- if (newHistory.length > 50) {
+ const maxHistorySteps = Math.max(
+ 10,
+ Math.min(200, performanceManager.getConfig().maxHistorySteps || 50)
+ );
+ while (newHistory.length > maxHistorySteps) {
newHistory.shift();
}
@@ -322,7 +327,11 @@ export function useDrawingHistory({
if (tileDeltas && tileDeltas.length > 0) {
const registerPromise = docId
? documentStore.registerUndoStep(docId, item)
- : undoCache.registerStep(item, historyRef.current);
+ : undoCache.registerStep(
+ item,
+ historyRef.current,
+ performanceManager.getConfig().undoRamSteps
+ );
registerPromise.catch((err) => {
console.warn('[History] LRU cache registration failed:', err);
});
diff --git a/src/services/bake3DService.ts b/src/services/bake3DService.ts
index 23d0f39..354b6c8 100644
--- a/src/services/bake3DService.ts
+++ b/src/services/bake3DService.ts
@@ -1,6 +1,7 @@
import * as THREE from 'three';
import { LayerItem, BlendMode } from '../types/editor';
import { documentStore } from '../utils/documentStore';
+import { performanceManager } from '../utils/performanceManager';
import { multiplayerService } from './multiplayerService';
import { applyScreentoneCPU } from '../utils/screentoneEngine';
@@ -79,9 +80,10 @@ export function createSafeWebGLRenderer(
options: SafeWebGLRendererOptions = {}
): THREE.WebGLRenderer {
const alpha = options.alpha ?? true;
- const antialias = options.antialias ?? true;
+ const antialias = options.antialias ?? performanceManager.getConfig().preview3DAntialias;
const preserveDrawingBuffer = options.preserveDrawingBuffer ?? true;
- const preferredPower = options.powerPreference ?? 'high-performance';
+ const preferredPower =
+ options.powerPreference ?? performanceManager.getConfig().gpuPowerPreference ?? 'high-performance';
const attempts: Array<{ antialias: boolean; powerPreference?: WebGLPowerPreference }> = [
{ antialias, powerPreference: preferredPower },
diff --git a/src/services/recoveryService.ts b/src/services/recoveryService.ts
index 390330c..e8ffb38 100644
--- a/src/services/recoveryService.ts
+++ b/src/services/recoveryService.ts
@@ -22,6 +22,7 @@ import {
} from '../utils/tileEngine';
import { deflateAsync } from '../utils/asyncCompression';
import { documentStore } from '../utils/documentStore';
+import { artworkTimeTracker } from '../utils/artworkTimeTracker';
export const WAL_MAGIC_BYTES = new Uint8Array([0x49, 0x4e, 0x4b, 0x57]); // 'INKW'
export const WAL_ENTRY_STROKE_TILE_DELTA = 1;
@@ -135,6 +136,7 @@ export interface DocumentManifest {
layers: LayerItem[];
activeLayerId: string;
timestamp: number;
+ workTimeMs?: number;
}
export interface CrashedSessionInfo {
@@ -404,6 +406,7 @@ class RecoveryService {
*/
public setDrawingActive(active: boolean): void {
this.isDrawingActive = active;
+ artworkTimeTracker.setDrawingActive(active);
if (active) {
if (this.idleCheckpointTimer) {
clearTimeout(this.idleCheckpointTimer);
diff --git a/src/stores/useUiStore.ts b/src/stores/useUiStore.ts
index fc2310b..845e3b9 100644
--- a/src/stores/useUiStore.ts
+++ b/src/stores/useUiStore.ts
@@ -2,6 +2,7 @@ import { AppSettings, loadAppSettings, saveAppSettings } from '../types/settings
import { CrashedSessionInfo } from '../services/recoveryService';
import { TonalCorrectionType, ProcessingBounds, TileHistogramMap } from '../utils/tonalEngine';
import type { TileSnapshotEntry } from '../utils/tileEngine';
+import { performanceManager } from '../utils/performanceManager';
import { safeLocalStorageSetItem, setStorageQuotaNotifier } from '../utils/safeStorage';
import { createStore } from './createStore';
import { useUpdaterStore } from './useUpdaterStore';
@@ -104,37 +105,41 @@ function readStoredNumber(key: string, fallback: number): number {
return fallback;
}
-const createInitialUiState = (): UiStoreState => ({
- appView: 'workspace',
- leftPanelWidth: readStoredNumber('ink_left_panel_width_v3', 118),
- isLeftPanelHidden: false,
- rightSidebarWidth: readStoredNumber('ink_right_sidebar_width_v3', 162),
- isRightSidebarHidden: false,
- isWebtoonMode: false,
- is3DLayerOpen: false,
- initial3DFile: null,
- appSettings: loadAppSettings(),
-
- isNewCanvasModalOpen: false,
- isResizeCanvasModalOpen: false,
- isSettingsModalOpen: false,
- isAboutModalOpen: false,
- isToneModalOpen: false,
- isMangaEffectsModalOpen: false,
- isWebtoonExportModalOpen: false,
- isTimelapseExportModalOpen: false,
- isBrushStudioModalOpen: false,
- isRecoveryModalOpen: false,
- crashedSessions: [],
- tonalModalState: { ...DEFAULT_TONAL_MODAL_STATE },
- adjustmentModalState: { isOpen: false },
- layerStylesModalState: { isOpen: false },
- appClosePrompt: { ...INITIAL_APP_CLOSE_PROMPT_STATE },
-
- isLoadingFile: false,
- loadingStatus: '',
- toastMessage: null,
-});
+const createInitialUiState = (): UiStoreState => {
+ const initialSettings = loadAppSettings();
+ performanceManager.applySettings(initialSettings);
+ return {
+ appView: 'workspace',
+ leftPanelWidth: readStoredNumber('ink_left_panel_width_v3', 118),
+ isLeftPanelHidden: false,
+ rightSidebarWidth: readStoredNumber('ink_right_sidebar_width_v3', 162),
+ isRightSidebarHidden: false,
+ isWebtoonMode: false,
+ is3DLayerOpen: false,
+ initial3DFile: null,
+ appSettings: initialSettings,
+
+ isNewCanvasModalOpen: false,
+ isResizeCanvasModalOpen: false,
+ isSettingsModalOpen: false,
+ isAboutModalOpen: false,
+ isToneModalOpen: false,
+ isMangaEffectsModalOpen: false,
+ isWebtoonExportModalOpen: false,
+ isTimelapseExportModalOpen: false,
+ isBrushStudioModalOpen: false,
+ isRecoveryModalOpen: false,
+ crashedSessions: [],
+ tonalModalState: { ...DEFAULT_TONAL_MODAL_STATE },
+ adjustmentModalState: { isOpen: false },
+ layerStylesModalState: { isOpen: false },
+ appClosePrompt: { ...INITIAL_APP_CLOSE_PROMPT_STATE },
+
+ isLoadingFile: false,
+ loadingStatus: '',
+ toastMessage: null,
+ };
+};
export const useUiStore = createStore<UiStoreState>(createInitialUiState);
@@ -197,6 +202,7 @@ export const uiStoreActions = {
},
updateAppSettings(newSettings: AppSettings): void {
+ performanceManager.applySettings(newSettings);
useUiStore.setState({ appSettings: newSettings });
saveAppSettings(newSettings);
},
diff --git a/src/stores/useWorkspaceStore.ts b/src/stores/useWorkspaceStore.ts
index 0ce41b9..d08ff31 100644
--- a/src/stores/useWorkspaceStore.ts
+++ b/src/stores/useWorkspaceStore.ts
@@ -37,6 +37,7 @@ export interface WorkspaceStoreState {
showStatusBar: boolean;
showDocumentTabs: boolean;
showCommandBar: boolean;
+ migratedPanels?: DockPanelId[];
}
const createInitialWorkspaceState = (): WorkspaceStoreState => {
@@ -53,6 +54,7 @@ const createInitialWorkspaceState = (): WorkspaceStoreState => {
showStatusBar: loaded.showStatusBar,
showDocumentTabs: loaded.showDocumentTabs,
showCommandBar: loaded.showCommandBar,
+ migratedPanels: loaded.migratedPanels,
};
};
@@ -71,6 +73,7 @@ function persistCurrentWorkspace(): void {
showStatusBar: s.showStatusBar,
showDocumentTabs: s.showDocumentTabs,
showCommandBar: s.showCommandBar,
+ migratedPanels: s.migratedPanels,
};
saveWorkspaceState(payload);
}
diff --git a/src/types/editor.ts b/src/types/editor.ts
index 13233d9..9b54f95 100644
--- a/src/types/editor.ts
+++ b/src/types/editor.ts
@@ -544,6 +544,8 @@ export interface DocumentTab {
straightRuler?: StraightRuler | null;
defaultFrequency?: number;
animation?: AnimationTimeline | null;
+ /** Total active time spent working on this artwork, in milliseconds. */
+ workTimeMs?: number;
}
export type HistoryActionType =
@@ -1137,6 +1139,8 @@ export interface LoadedDocument {
animationTimeline?: AnimationTimeline | null;
timelapse?: InkTimelapseMetadata | null;
previewDataUrl?: string;
+ /** Persisted active work time in milliseconds (restored from .ink, .sora, .psd/.psb). */
+ workTimeMs?: number;
}
export type CmykStandard = 'japan-color-2001' | 'us-web-coated-swop' | 'iso-coated-v2';
diff --git a/src/types/settings.ts b/src/types/settings.ts
index f5450d4..7f656b0 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -179,6 +179,16 @@ export const DEFAULT_PRESSURE_CURVE_SETTINGS: PressureCurveSettings = {
],
};
+export type RenderBackend = 'auto' | 'webgl2' | 'canvas2d';
+export type GpuPowerPreference = 'high-performance' | 'low-power' | 'default';
+export type DesktopGraphicsApi = 'auto' | 'd3d11' | 'vulkan' | 'gl' | 'warp';
+export type GpuTexturePoolPreset = 'low' | 'balanced' | 'high' | 'ultra';
+export type ViewportResolutionScale = 'native' | 'capped-2x' | '1x' | '0.75x';
+export type CanvasFilteringQuality = 'auto' | 'smooth' | 'pixelated';
+export type ScratchDiskCompression = 'lz4' | 'none';
+export type Preview3DMaxResolution = 1024 | 1920 | 2560;
+export type PerformancePresetId = 'battery' | 'balanced' | 'maximum' | 'compatibility';
+
export interface AppSettings {
// User Profile
userName: string;
@@ -213,8 +223,26 @@ export interface AppSettings {
modifierKeys: ModifierKeySettings;
pressureCurve: PressureCurveSettings;
- // Performance & Scratch Disk
+ // Performance, GPU, Memory & Scratch Disk
+ autoOptimizePerformance: boolean;
tileMemoryBudgetMb: number;
+ memoryAllocationPercent: number;
+ undoRamSteps: number;
+ offloadInactiveTabs: boolean;
+ renderBackend: RenderBackend;
+ gpuPowerPreference: GpuPowerPreference;
+ desktopGraphicsApi: DesktopGraphicsApi;
+ gpuBrushAcceleration: boolean;
+ gpuTexturePoolPreset: GpuTexturePoolPreset;
+ layerStackCaching: boolean;
+ viewportResolutionScale: ViewportResolutionScale;
+ canvasFilteringQuality: CanvasFilteringQuality;
+ scratchDiskPath: string;
+ scratchDiskCompression: ScratchDiskCompression;
+ cpuWorkerThreads: number; // 0 = Auto (all logical cores)
+ useNativeRustAcceleration: boolean;
+ preview3DMaxResolution: Preview3DMaxResolution;
+ preview3DAntialias: boolean;
// Auto-Updater (Desktop)
autoCheckUpdates: boolean;
@@ -252,7 +280,25 @@ export const DEFAULT_APP_SETTINGS: AppSettings = {
points: DEFAULT_PRESSURE_CURVE_SETTINGS.points.map(([x, y]) => [x, y] as PressureCurvePoint),
},
+ autoOptimizePerformance: true,
tileMemoryBudgetMb: 1024,
+ memoryAllocationPercent: 60,
+ undoRamSteps: 15,
+ offloadInactiveTabs: true,
+ renderBackend: 'auto',
+ gpuPowerPreference: 'high-performance',
+ desktopGraphicsApi: 'auto',
+ gpuBrushAcceleration: true,
+ gpuTexturePoolPreset: 'high',
+ layerStackCaching: true,
+ viewportResolutionScale: 'capped-2x',
+ canvasFilteringQuality: 'auto',
+ scratchDiskPath: '',
+ scratchDiskCompression: 'lz4',
+ cpuWorkerThreads: 0,
+ useNativeRustAcceleration: true,
+ preview3DMaxResolution: 1920,
+ preview3DAntialias: true,
autoCheckUpdates: true,
skippedUpdateVersion: '',
@@ -405,10 +451,112 @@ export function loadAppSettings(): AppSettings {
const validTone: 'slate' | 'oled' | 'charcoal' = ['slate', 'oled', 'charcoal'].includes(parsed.uiTone)
? parsed.uiTone
: 'charcoal';
+ const validAutoOptimizePerformance: boolean =
+ typeof parsed.autoOptimizePerformance === 'boolean'
+ ? parsed.autoOptimizePerformance
+ : DEFAULT_APP_SETTINGS.autoOptimizePerformance;
const validBudget: number =
- typeof parsed.tileMemoryBudgetMb === 'number' && parsed.tileMemoryBudgetMb >= 256 && parsed.tileMemoryBudgetMb <= 8192
- ? parsed.tileMemoryBudgetMb
- : 1024;
+ typeof parsed.tileMemoryBudgetMb === 'number' &&
+ Number.isFinite(parsed.tileMemoryBudgetMb) &&
+ parsed.tileMemoryBudgetMb >= 256 &&
+ parsed.tileMemoryBudgetMb <= 32768
+ ? Math.round(parsed.tileMemoryBudgetMb)
+ : DEFAULT_APP_SETTINGS.tileMemoryBudgetMb;
+ const validMemoryPercent: number =
+ typeof parsed.memoryAllocationPercent === 'number' &&
+ Number.isFinite(parsed.memoryAllocationPercent)
+ ? Math.max(20, Math.min(85, Math.round(parsed.memoryAllocationPercent)))
+ : DEFAULT_APP_SETTINGS.memoryAllocationPercent;
+ const validMaxHistorySteps: number =
+ typeof parsed.maxHistorySteps === 'number' && Number.isFinite(parsed.maxHistorySteps)
+ ? Math.max(10, Math.min(200, Math.round(parsed.maxHistorySteps)))
+ : DEFAULT_APP_SETTINGS.maxHistorySteps;
+ const validUndoRamSteps: number =
+ typeof parsed.undoRamSteps === 'number' && Number.isFinite(parsed.undoRamSteps)
+ ? Math.max(4, Math.min(50, Math.round(parsed.undoRamSteps)))
+ : DEFAULT_APP_SETTINGS.undoRamSteps;
+ const validOffloadInactiveTabs: boolean =
+ typeof parsed.offloadInactiveTabs === 'boolean'
+ ? parsed.offloadInactiveTabs
+ : DEFAULT_APP_SETTINGS.offloadInactiveTabs;
+ const validRenderBackend: RenderBackend = ['auto', 'webgl2', 'canvas2d'].includes(
+ parsed.renderBackend
+ )
+ ? parsed.renderBackend
+ : DEFAULT_APP_SETTINGS.renderBackend;
+ const validGpuPowerPreference: GpuPowerPreference = [
+ 'high-performance',
+ 'low-power',
+ 'default',
+ ].includes(parsed.gpuPowerPreference)
+ ? parsed.gpuPowerPreference
+ : DEFAULT_APP_SETTINGS.gpuPowerPreference;
+ const validDesktopGraphicsApi: DesktopGraphicsApi = [
+ 'auto',
+ 'd3d11',
+ 'vulkan',
+ 'gl',
+ 'warp',
+ ].includes(parsed.desktopGraphicsApi)
+ ? parsed.desktopGraphicsApi
+ : DEFAULT_APP_SETTINGS.desktopGraphicsApi;
+ const validGpuBrushAcceleration: boolean =
+ typeof parsed.gpuBrushAcceleration === 'boolean'
+ ? parsed.gpuBrushAcceleration
+ : DEFAULT_APP_SETTINGS.gpuBrushAcceleration;
+ const validGpuTexturePoolPreset: GpuTexturePoolPreset = [
+ 'low',
+ 'balanced',
+ 'high',
+ 'ultra',
+ ].includes(parsed.gpuTexturePoolPreset)
+ ? parsed.gpuTexturePoolPreset
+ : DEFAULT_APP_SETTINGS.gpuTexturePoolPreset;
+ const validLayerStackCaching: boolean =
+ typeof parsed.layerStackCaching === 'boolean'
+ ? parsed.layerStackCaching
+ : DEFAULT_APP_SETTINGS.layerStackCaching;
+ const validViewportResolutionScale: ViewportResolutionScale = [
+ 'native',
+ 'capped-2x',
+ '1x',
+ '0.75x',
+ ].includes(parsed.viewportResolutionScale)
+ ? parsed.viewportResolutionScale
+ : DEFAULT_APP_SETTINGS.viewportResolutionScale;
+ const validCanvasFilteringQuality: CanvasFilteringQuality = [
+ 'auto',
+ 'smooth',
+ 'pixelated',
+ ].includes(parsed.canvasFilteringQuality)
+ ? parsed.canvasFilteringQuality
+ : DEFAULT_APP_SETTINGS.canvasFilteringQuality;
+ const validScratchDiskPath: string =
+ typeof parsed.scratchDiskPath === 'string' && !parsed.scratchDiskPath.includes('\0')
+ ? parsed.scratchDiskPath.trim()
+ : DEFAULT_APP_SETTINGS.scratchDiskPath;
+ const validScratchDiskCompression: ScratchDiskCompression = ['lz4', 'none'].includes(
+ parsed.scratchDiskCompression
+ )
+ ? parsed.scratchDiskCompression
+ : DEFAULT_APP_SETTINGS.scratchDiskCompression;
+ const validCpuWorkerThreads: number =
+ typeof parsed.cpuWorkerThreads === 'number' && Number.isFinite(parsed.cpuWorkerThreads)
+ ? Math.max(0, Math.min(64, Math.round(parsed.cpuWorkerThreads)))
+ : DEFAULT_APP_SETTINGS.cpuWorkerThreads;
+ const validUseNativeRustAcceleration: boolean =
+ typeof parsed.useNativeRustAcceleration === 'boolean'
+ ? parsed.useNativeRustAcceleration
+ : DEFAULT_APP_SETTINGS.useNativeRustAcceleration;
+ const validPreview3DMaxResolution: Preview3DMaxResolution = [1024, 1920, 2560].includes(
+ parsed.preview3DMaxResolution
+ )
+ ? parsed.preview3DMaxResolution
+ : DEFAULT_APP_SETTINGS.preview3DMaxResolution;
+ const validPreview3DAntialias: boolean =
+ typeof parsed.preview3DAntialias === 'boolean'
+ ? parsed.preview3DAntialias
+ : DEFAULT_APP_SETTINGS.preview3DAntialias;
const validAutoCheckUpdates: boolean =
typeof parsed.autoCheckUpdates === 'boolean'
? parsed.autoCheckUpdates
@@ -426,7 +574,26 @@ export function loadAppSettings(): AppSettings {
modernAccent: validAccent,
modernCustomColor: validCustomColor,
uiTone: validTone,
+ maxHistorySteps: validMaxHistorySteps,
+ autoOptimizePerformance: validAutoOptimizePerformance,
tileMemoryBudgetMb: validBudget,
+ memoryAllocationPercent: validMemoryPercent,
+ undoRamSteps: validUndoRamSteps,
+ offloadInactiveTabs: validOffloadInactiveTabs,
+ renderBackend: validRenderBackend,
+ gpuPowerPreference: validGpuPowerPreference,
+ desktopGraphicsApi: validDesktopGraphicsApi,
+ gpuBrushAcceleration: validGpuBrushAcceleration,
+ gpuTexturePoolPreset: validGpuTexturePoolPreset,
+ layerStackCaching: validLayerStackCaching,
+ viewportResolutionScale: validViewportResolutionScale,
+ canvasFilteringQuality: validCanvasFilteringQuality,
+ scratchDiskPath: validScratchDiskPath,
+ scratchDiskCompression: validScratchDiskCompression,
+ cpuWorkerThreads: validCpuWorkerThreads,
+ useNativeRustAcceleration: validUseNativeRustAcceleration,
+ preview3DMaxResolution: validPreview3DMaxResolution,
+ preview3DAntialias: validPreview3DAntialias,
autoCheckUpdates: validAutoCheckUpdates,
skippedUpdateVersion: validSkippedUpdateVersion,
shortcuts: sanitizeShortcuts(parsed.shortcuts),
diff --git a/src/types/workspace.ts b/src/types/workspace.ts
index 42c75be..4a2a24b 100644
--- a/src/types/workspace.ts
+++ b/src/types/workspace.ts
@@ -7,6 +7,7 @@ export type DockPanelId =
| 'brush-size'
| 'navigator'
| 'sub-view'
+ | 'info'
| 'color'
| 'layers'
| 'history'
@@ -84,6 +85,7 @@ export interface PersistedWorkspaceState {
showStatusBar: boolean;
showDocumentTabs: boolean;
showCommandBar: boolean;
+ migratedPanels?: DockPanelId[];
}
export interface DockPanelMeta {
@@ -103,6 +105,7 @@ export const ALL_DOCK_PANEL_IDS: DockPanelId[] = [
'brush-size',
'navigator',
'sub-view',
+ 'info',
'color',
'layers',
'history',
@@ -165,6 +168,15 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {
minWidth: 176,
maxWidth: 400,
},
+ info: {
+ id: 'info',
+ title: 'Info',
+ shortTitle: 'Info',
+ defaultSide: 'right',
+ defaultWidth: 224,
+ minWidth: 176,
+ maxWidth: 380,
+ },
color: {
id: 'color',
title: 'Color Wheel',
diff --git a/src/utils/__tests__/artworkTimeTracker.test.tsx b/src/utils/__tests__/artworkTimeTracker.test.tsx
new file mode 100644
index 0000000..7592259
--- /dev/null
+++ b/src/utils/__tests__/artworkTimeTracker.test.tsx
@@ -0,0 +1,770 @@
+import { act } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { zipSync } from 'fflate';
+import {
+ ArtworkTimeTracker,
+ buildInkStudioXmpMetadata,
+ extractWorkTimeMsFromPsdBuffer,
+ extractWorkTimeMsFromXmp,
+ formatWorkTimeClock,
+ formatWorkTimeHoursMinutes,
+ sanitizeWorkTimeMs,
+} from '../artworkTimeTracker';
+import { parseInkProject, serializeDocument, serializeInkProject } from '../saveManager';
+import { openFile } from '../imageLoader';
+import { migrateLegacySoraBytes } from '../legacySoraMigrator';
+import { parsePsdFile } from '../psdParser';
+import { SparseTileGrid } from '../tileEngine';
+import { LayerItem } from '../../types/editor';
+import {
+ WORKSPACE_STORAGE_KEY,
+ findPanelLocation,
+ loadWorkspaceState,
+} from '../workspacePresets';
+import { useWorkspaceStore, workspaceStoreActions } from '../../stores/useWorkspaceStore';
+import { useDocumentStore, documentStoreActions } from '../../stores/useDocumentStore';
+import { useToolStore } from '../../stores/useToolStore';
+import { InfoPanel } from '../../components/InfoPanel';
+
+const THREE_HOURS_FIFTEEN_MIN_MS = (3 * 60 + 15) * 60 * 1000; // 11,700,000 ms
+
+function createMemoryStorage(): Storage {
+ const store = new Map<string, string>();
+ return {
+ get length() {
+ return store.size;
+ },
+ clear() {
+ store.clear();
+ },
+ getItem(key: string) {
+ return store.has(key) ? store.get(key)! : null;
+ },
+ key(index: number) {
+ return Array.from(store.keys())[index] ?? null;
+ },
+ removeItem(key: string) {
+ store.delete(key);
+ },
+ setItem(key: string, value: string) {
+ store.set(key, String(value));
+ },
+ };
+}
+
+class MiniText {
+ nodeType = 3;
+ nodeName = '#text';
+ parentNode: MiniEl | null = null;
+ constructor(public nodeValue: string, public ownerDocument: MiniDoc) {}
+}
+
+class MiniComment {
+ nodeType = 8;
+ nodeName = '#comment';
+ parentNode: MiniEl | null = null;
+ constructor(public nodeValue: string, public ownerDocument: MiniDoc) {}
+}
+
+class MiniEl extends EventTarget {
+ nodeType = 1;
+ nodeName: string;
+ tagName: string;
+ namespaceURI = 'http://www.w3.org/1999/xhtml';
+ parentNode: MiniEl | null = null;
+ childNodes: Array<MiniEl | MiniText | MiniComment> = [];
+ style: Record<string, string> = {};
+ className = '';
+ disabled = false;
+ value = '';
+ attrs = new Map<string, string>();
+
+ constructor(tag: string, public ownerDocument: MiniDoc) {
+ super();
+ this.nodeName = tag.toUpperCase();
+ this.tagName = tag.toUpperCase();
+ }
+
+ get firstChild() {
+ return this.childNodes[0] ?? null;
+ }
+
+ get textContent(): string {
+ return this.childNodes
+ .map((c) => (c instanceof MiniText ? c.nodeValue : c instanceof MiniEl ? c.textContent : ''))
+ .join('');
+ }
+
+ set textContent(val: string) {
+ this.childNodes = val ? [new MiniText(val, this.ownerDocument)] : [];
+ }
+
+ appendChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {
+ if (child.parentNode) child.parentNode.removeChild(child);
+ child.parentNode = this;
+ this.childNodes.push(child);
+ return child;
+ }
+
+ removeChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {
+ const idx = this.childNodes.indexOf(child);
+ if (idx >= 0) {
+ this.childNodes.splice(idx, 1);
+ child.parentNode = null;
+ }
+ return child;
+ }
+
+ insertBefore<T extends MiniEl | MiniText | MiniComment>(
+ node: T,
+ ref: MiniEl | MiniText | MiniComment | null
+ ): T {
+ if (node.parentNode) node.parentNode.removeChild(node);
+ node.parentNode = this;
+ const idx = ref ? this.childNodes.indexOf(ref) : -1;
+ if (idx >= 0) this.childNodes.splice(idx, 0, node);
+ else this.childNodes.push(node);
+ return node;
+ }
+
+ setAttribute(k: string, v: string) {
+ this.attrs.set(k, String(v));
+ }
+
+ getAttribute(k: string): string | null {
+ return this.attrs.get(k) ?? null;
+ }
+
+ removeAttribute(k: string) {
+ this.attrs.delete(k);
+ }
+
+ findByAttr(attr: string, value: string): MiniEl | null {
+ if (this.getAttribute(attr) === value) return this;
+ for (const c of this.childNodes) {
+ if (c instanceof MiniEl) {
+ const found = c.findByAttr(attr, value);
+ if (found) return found;
+ }
+ }
+ return null;
+ }
+
+ findByTag(tag: string): MiniEl | null {
+ if (this.tagName === tag.toUpperCase()) return this;
+ for (const c of this.childNodes) {
+ if (c instanceof MiniEl) {
+ const found = c.findByTag(tag);
+ if (found) return found;
+ }
+ }
+ return null;
+ }
+}
+
+interface MiniDoc {
+ nodeType: number;
+ nodeName: string;
+ documentElement: MiniEl;
+ body: MiniEl;
+ activeElement: MiniEl;
+ defaultView: Record<string, unknown>;
+ createElement: (tag: string) => MiniEl;
+ createElementNS: (_ns: string, tag: string) => MiniEl;
+ createTextNode: (text: string) => MiniText;
+ createComment: (text: string) => MiniComment;
+ addEventListener: EventTarget['addEventListener'];
+ removeEventListener: EventTarget['removeEventListener'];
+ dispatchEvent: EventTarget['dispatchEvent'];
+}
+
+function installMiniDom() {
+ const g = globalThis as unknown as Record<string, unknown>;
+ const saved: Record<string, unknown> = {
+ window: g.window,
+ document: g.document,
+ HTMLElement: g.HTMLElement,
+ Node: g.Node,
+ Element: g.Element,
+ requestAnimationFrame: g.requestAnimationFrame,
+ cancelAnimationFrame: g.cancelAnimationFrame,
+ IS_REACT_ACT_ENVIRONMENT: g.IS_REACT_ACT_ENVIRONMENT,
+ };
+ g.IS_REACT_ACT_ENVIRONMENT = true;
+
+ const winTarget = new EventTarget();
+ const docTarget = new EventTarget();
+ const rafQueue: FrameRequestCallback[] = [];
+
+ const mockDoc = {
+ nodeType: 9,
+ nodeName: '#document',
+ documentElement: null as unknown as MiniEl,
+ body: null as unknown as MiniEl,
+ activeElement: null as unknown as MiniEl,
+ defaultView: null as unknown as Record<string, unknown>,
+ createElement: (tag: string) => new MiniEl(tag, mockDoc),
+ createElementNS: (_ns: string, tag: string) => new MiniEl(tag, mockDoc),
+ createTextNode: (text: string) => new MiniText(text, mockDoc),
+ createComment: (text: string) => new MiniComment(text, mockDoc),
+ addEventListener: docTarget.addEventListener.bind(docTarget),
+ removeEventListener: docTarget.removeEventListener.bind(docTarget),
+ dispatchEvent: docTarget.dispatchEvent.bind(docTarget),
+ } as MiniDoc;
+
+ mockDoc.documentElement = new MiniEl('html', mockDoc);
+ mockDoc.body = new MiniEl('body', mockDoc);
+ mockDoc.documentElement.appendChild(mockDoc.body);
+ mockDoc.activeElement = mockDoc.body;
+
+ class MockIFrame extends MiniEl {}
+
+ const rafMock = (cb: FrameRequestCallback) => {
+ rafQueue.push(cb);
+ return rafQueue.length;
+ };
+ const cancelRafMock = () => {};
+
+ const mockWin: Record<string, unknown> = {
+ innerWidth: 1440,
+ innerHeight: 900,
+ document: mockDoc,
+ Node: MiniEl,
+ Element: MiniEl,
+ HTMLElement: MiniEl,
+ SVGElement: MiniEl,
+ HTMLIFrameElement: MockIFrame,
+ Event,
+ CustomEvent,
+ addEventListener: winTarget.addEventListener.bind(winTarget),
+ removeEventListener: winTarget.removeEventListener.bind(winTarget),
+ dispatchEvent: winTarget.dispatchEvent.bind(winTarget),
+ requestAnimationFrame: rafMock,
+ cancelAnimationFrame: cancelRafMock,
+ };
+ mockDoc.defaultView = mockWin;
+
+ g.window = mockWin;
+ g.document = mockDoc;
+ g.HTMLElement = MiniEl;
+ g.Node = MiniEl;
+ g.Element = MiniEl;
+ g.requestAnimationFrame = rafMock;
+ g.cancelAnimationFrame = cancelRafMock;
+
+ const container = new MiniEl('div', mockDoc);
+ mockDoc.body.appendChild(container);
+
+ return {
+ container,
+ flushRaf: () => {
+ const batch = rafQueue.splice(0, rafQueue.length);
+ for (const cb of batch) cb(16);
+ },
+ cleanup: () => {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete g[k];
+ else g[k] = v;
+ }
+ },
+ };
+}
+
+describe('ArtworkTimeTracker Smart Adaptive Safety & Accuracy Engine', () => {
+ it('formats hours, minutes, seconds, and sanitizes invalid values accurately', () => {
+ expect(formatWorkTimeClock(0)).toBe('00:00:00');
+ expect(formatWorkTimeClock(THREE_HOURS_FIFTEEN_MIN_MS)).toBe('03:15:00');
+ expect(formatWorkTimeClock(THREE_HOURS_FIFTEEN_MIN_MS + 42_000)).toBe('03:15:42');
+ expect(formatWorkTimeClock((105 * 3600 + 2 * 60 + 9) * 1000)).toBe('105:02:09');
+
+ expect(formatWorkTimeHoursMinutes(0)).toBe('0m');
+ expect(formatWorkTimeHoursMinutes(45 * 60 * 1000)).toBe('45m');
+ expect(formatWorkTimeHoursMinutes(THREE_HOURS_FIFTEEN_MIN_MS)).toBe('3h 15m');
+
+ expect(sanitizeWorkTimeMs(-500)).toBe(0);
+ expect(sanitizeWorkTimeMs(Number.NaN)).toBe(0);
+ expect(sanitizeWorkTimeMs(Number.POSITIVE_INFINITY)).toBe(0);
+ expect(sanitizeWorkTimeMs('1234')).toBe(0);
+ expect(sanitizeWorkTimeMs(1234.6)).toBe(1235);
+ });
+
+ it('never starts counting on file open or non-artwork supporting interactions until a genuine artwork action occurs', () => {
+ let clock = 10_000;
+ const tracker = new ArtworkTimeTracker({
+ now: () => clock,
+ baseIdleTimeoutMs: 25_000,
+ });
+
+ tracker.initDocument('doc-a', THREE_HOURS_FIFTEEN_MIN_MS);
+ tracker.setActiveDocument('doc-a', true);
+
+ // Clicking UI panels, zooming, or sitting idle must NOT wake the timer
+ for (let s = 0; s < 30; s++) {
+ clock += 1_000;
+ tracker.recordSupportingActivity();
+ tracker.tick();
+ }
+ expect(tracker.getWorkTimeMs('doc-a')).toBe(THREE_HOURS_FIFTEEN_MIN_MS);
+ expect(tracker.getSnapshot('doc-a').status).toBe('idle');
+
+ // Once user draws or edits artwork, counting starts cleanly
+ tracker.recordArtworkAction();
+ expect(tracker.getSnapshot('doc-a').status).toBe('recording');
+ clock += 1_000;
+ tracker.tick();
+ expect(tracker.getWorkTimeMs('doc-a')).toBe(THREE_HOURS_FIFTEEN_MIN_MS + 1_000);
+
+ tracker.resetAll();
+ });
+
+ it('adapts inactivity timeout to fast sketching vs deliberate painting and enforces the non-edit sustain cap', () => {
+ // 1. Brisk sketching cadence (strokes every 2s -> adapts down to ~17s idle threshold)
+ let fastClock = 1_000;
+ const fastTracker = new ArtworkTimeTracker({
+ now: () => fastClock,
+ baseIdleTimeoutMs: 25_000,
+ minAdaptiveIdleMs: 15_000,
+ maxAdaptiveIdleMs: 60_000,
+ maxNonEditSustainMs: 90_000,
+ });
+ fastTracker.initDocument('sketch', 0);
+ fastTracker.setActiveDocument('sketch', true);
+
+ fastTracker.recordArtworkAction();
+ for (let i = 0; i < 6; i++) {
+ fastClock += 1_000;
+ fastTracker.tick();
+ fastClock += 1_000;
+ fastTracker.tick();
+ fastTracker.recordArtworkAction();
+ }
+ // 2s * 2.5 + 12s = 17s adaptive timeout
+ expect(fastTracker.getEffectiveIdleTimeoutMs()).toBe(17_000);
+
+ // User stops sketching -> pauses automatically after 17s (not 60s)
+ for (let s = 0; s < 60; s++) {
+ fastClock += 1_000;
+ fastTracker.tick();
+ }
+ expect(fastTracker.getSnapshot('sketch').status).toBe('idle');
+ expect(fastTracker.getWorkTimeMs('sketch')).toBe(12_000 + 17_000);
+ fastTracker.resetAll();
+
+ // 2. Deliberate painting cadence (strokes every 15s -> adapts up to ~49.5s)
+ let slowClock = 1_000;
+ const slowTracker = new ArtworkTimeTracker({
+ now: () => slowClock,
+ baseIdleTimeoutMs: 25_000,
+ minAdaptiveIdleMs: 15_000,
+ maxAdaptiveIdleMs: 60_000,
+ maxNonEditSustainMs: 90_000,
+ });
+ slowTracker.initDocument('painting', 0);
+ slowTracker.setActiveDocument('painting', true);
+
+ slowTracker.recordArtworkAction();
+ for (let stroke = 0; stroke < 3; stroke++) {
+ for (let s = 0; s < 15; s++) {
+ slowClock += 1_000;
+ slowTracker.tick();
+ }
+ slowTracker.recordArtworkAction();
+ }
+ // 15s * 2.5 + 12s = 49.5s adaptive timeout
+ expect(slowTracker.getEffectiveIdleTimeoutMs()).toBe(49_500);
+
+ // 3. Supporting interactions (e.g. panning/zooming) sustain active painting,
+ // but hard-stop once maxNonEditSustainMs (90s) elapses without a real artwork edit
+ const timeAtLastEdit = slowTracker.getWorkTimeMs('painting');
+ for (let s = 1; s <= 150; s++) {
+ slowClock += 1_000;
+ slowTracker.tick();
+ if (s % 10 === 0) {
+ slowTracker.recordSupportingActivity();
+ }
+ }
+ expect(slowTracker.getSnapshot('painting').status).toBe('idle');
+ expect(slowTracker.getWorkTimeMs('painting')).toBe(timeAtLastEdit + 90_000);
+ slowTracker.resetAll();
+ });
+
+ it('pauses immediately on window blur / tab hide and protects against OS sleep jumps', () => {
+ let clock = 5_000;
+ const tracker = new ArtworkTimeTracker({
+ now: () => clock,
+ baseIdleTimeoutMs: 25_000,
+ tickIntervalMs: 1_000,
+ maxSleepGapMs: 5_000,
+ });
+
+ tracker.initDocument('doc-a', 10_000);
+ tracker.setActiveDocument('doc-a', true);
+ tracker.recordArtworkAction();
+
+ clock += 3_000;
+ tracker.tick();
+ expect(tracker.getWorkTimeMs('doc-a')).toBe(13_000);
+
+ // User alt-tabs away (window blur) for 2 hours
+ tracker.setWindowFocused(false);
+ expect(tracker.getSnapshot('doc-a').status).toBe('idle');
+ clock += 2 * 60 * 60 * 1000;
+ tracker.tick();
+ expect(tracker.getWorkTimeMs('doc-a')).toBe(13_000);
+
+ // User alt-tabs back without drawing -> stays idle at 13s
+ tracker.setWindowFocused(true);
+ clock += 10_000;
+ tracker.tick();
+ expect(tracker.getWorkTimeMs('doc-a')).toBe(13_000);
+
+ // User resumes drawing, then laptop sleeps for 8 hours
+ tracker.recordArtworkAction();
+ clock += 8 * 60 * 60 * 1000;
+ tracker.tick();
+
+ expect(tracker.getWorkTimeMs('doc-a')).toBeLessThanOrEqual(14_000);
+ expect(tracker.getSnapshot('doc-a').status).toBe('idle');
+
+ tracker.resetAll();
+ });
+
+ it('keeps counting during long continuous strokes and isolates time across multiple open tabs', () => {
+ let clock = 1_000;
+ const tracker = new ArtworkTimeTracker({
+ now: () => clock,
+ baseIdleTimeoutMs: 15_000,
+ tickIntervalMs: 1_000,
+ });
+
+ tracker.initDocument('doc-1', 60_000);
+ tracker.initDocument('doc-2', 120_000);
+ tracker.setActiveDocument('doc-1', true);
+
+ // Hold a continuous stroke down for 25s (> 15s idle timeout)
+ tracker.setDrawingActive(true);
+ for (let s = 0; s < 25; s++) {
+ clock += 1_000;
+ tracker.tick();
+ }
+ tracker.setDrawingActive(false);
+ expect(tracker.getWorkTimeMs('doc-1')).toBe(85_000);
+ expect(tracker.getWorkTimeMs('doc-2')).toBe(120_000);
+
+ // Switch to Doc 2 and work for 10s
+ tracker.setActiveDocument('doc-2', true);
+ tracker.recordArtworkAction();
+ for (let s = 0; s < 10; s++) {
+ clock += 1_000;
+ tracker.tick();
+ }
+ expect(tracker.getWorkTimeMs('doc-1')).toBe(85_000);
+ expect(tracker.getWorkTimeMs('doc-2')).toBe(130_000);
+
+ tracker.resetAll();
+ });
+});
+
+describe('Work Time Persistence Across .ink, Legacy .sora, and .psd Formats', () => {
+ it('saves 3h 15m in .ink format, reopens a day later at 3h 15m, and continues counting on new drawing', async () => {
+ const grid = new SparseTileGrid();
+ grid.fillLayerSolidWhite('layer-1', 256, 256, 'color-32bit');
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-1',
+ name: 'Artwork',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ];
+
+ const serialized = await serializeInkProject(
+ {
+ name: 'Illustration',
+ dimensions: { width: 256, height: 256, dpi: 300 },
+ colorMode: 'color',
+ layers,
+ tileGrid: grid,
+ getEffectiveOpacity: (l) => l.opacity,
+ isLayerEffectivelyVisible: (l) => l.visible,
+ workTimeMs: THREE_HOURS_FIFTEEN_MIN_MS,
+ },
+ grid
+ );
+
+ expect(serialized.manifest.workTimeMs).toBe(THREE_HOURS_FIFTEEN_MIN_MS);
+
+ const parsed = await parseInkProject(serialized.bytes);
+ expect(parsed.workTimeMs).toBe(THREE_HOURS_FIFTEEN_MIN_MS);
+
+ const reopenedFile = new File([serialized.bytes as BlobPart], 'Illustration.ink', {
+ type: 'application/octet-stream',
+ });
+ const loadedDoc = await openFile(reopenedFile);
+ expect(loadedDoc.workTimeMs).toBe(THREE_HOURS_FIFTEEN_MIN_MS);
+
+ let day2Clock = 1_000_000;
+ const day2Tracker = new ArtworkTimeTracker({
+ now: () => day2Clock,
+ baseIdleTimeoutMs: 25_000,
+ });
+ day2Tracker.initDocument('reopened-doc', loadedDoc.workTimeMs ?? 0);
+ day2Tracker.setActiveDocument('reopened-doc', true);
+
+ expect(formatWorkTimeClock(day2Tracker.getWorkTimeMs('reopened-doc'))).toBe('03:15:00');
+ expect(formatWorkTimeHoursMinutes(day2Tracker.getWorkTimeMs('reopened-doc'))).toBe('3h 15m');
+
+ day2Tracker.recordArtworkAction();
+ for (let s = 0; s < 150; s++) {
+ day2Clock += 1_000;
+ day2Tracker.tick();
+ if (s % 10 === 0) day2Tracker.recordArtworkAction();
+ }
+ expect(formatWorkTimeClock(day2Tracker.getWorkTimeMs('reopened-doc'))).toBe('03:17:30');
+ expect(formatWorkTimeHoursMinutes(day2Tracker.getWorkTimeMs('reopened-doc'))).toBe('3h 17m');
+ expect(formatWorkTimeClock(day2Tracker.getSessionTimeMs('reopened-doc'))).toBe('00:02:30');
+
+ day2Tracker.resetAll();
+ });
+
+ it('preserves workTimeMs when migrating legacy .sora v1 JSON and .sora v2 ZIP files', async () => {
+ const v1Json = JSON.stringify({
+ app: 'Sora Paint',
+ version: '1.2',
+ name: 'Legacy V1 Art',
+ dimensions: { width: 512, height: 512, dpi: 300 },
+ colorMode: 'color',
+ workTimeMs: THREE_HOURS_FIFTEEN_MIN_MS,
+ layers: [],
+ canvases: {},
+ masks: {},
+ });
+ const v1 = await migrateLegacySoraBytes(v1Json);
+ expect(v1.workTimeMs).toBe(THREE_HOURS_FIFTEEN_MIN_MS);
+
+ const v2Zip = zipSync({
+ 'manifest.json': new TextEncoder().encode(
+ JSON.stringify({
+ format: 'sora-v2',
+ app: 'Ink Studio',
+ version: '2.0',
+ tileSize: 256,
+ name: 'Legacy V2 Art',
+ dimensions: { width: 512, height: 512, dpi: 300 },
+ colorMode: 'color',
+ layers: [],
+ layerFormats: {},
+ layerTileKeys: {},
+ masksMeta: {},
+ workTimeMs: THREE_HOURS_FIFTEEN_MIN_MS + 60_000,
+ preview: null,
+ savedAt: Date.now(),
+ })
+ ),
+ });
+ const soraFile = new File([v2Zip as BlobPart], 'legacy.sora', {
+ type: 'application/octet-stream',
+ });
+ const loadedSora = await openFile(soraFile);
+ expect(loadedSora.workTimeMs).toBe(THREE_HOURS_FIFTEEN_MIN_MS + 60_000);
+ });
+
+ it('embeds and restores workTimeMs in .psd files via XMP metadata', async () => {
+ const xmp = buildInkStudioXmpMetadata(THREE_HOURS_FIFTEEN_MIN_MS);
+ expect(extractWorkTimeMsFromXmp(xmp)).toBe(THREE_HOURS_FIFTEEN_MIN_MS);
+
+ const grid = new SparseTileGrid();
+ grid.fillLayerSolidWhite('l1', 64, 64, 'color-32bit');
+ const layers: LayerItem[] = [
+ {
+ id: 'l1',
+ name: 'Layer 1',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ];
+
+ const serialized = await serializeDocument(
+ {
+ name: 'PsdArtwork',
+ dimensions: { width: 64, height: 64, dpi: 300 },
+ colorMode: 'color',
+ layers,
+ tileGrid: grid,
+ getEffectiveOpacity: (l) => l.opacity,
+ isLayerEffectivelyVisible: (l) => l.visible,
+ workTimeMs: THREE_HOURS_FIFTEEN_MIN_MS,
+ },
+ '.psd'
+ );
+
+ const buf =
+ serialized.data instanceof Blob
+ ? await serialized.data.arrayBuffer()
+ : serialized.data;
+
+ expect(extractWorkTimeMsFromPsdBuffer(buf)).toBe(THREE_HOURS_FIFTEEN_MIN_MS);
+
+ const parsedPsd = await parsePsdFile(buf, 'PsdArtwork.psd');
+ expect(parsedPsd.workTimeMs).toBe(THREE_HOURS_FIFTEEN_MIN_MS);
+ });
+});
+
+describe('InfoPanel Clean Text-Only UI & Workspace Info Tab Migration', () => {
+ const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;
+ let dom: ReturnType<typeof installMiniDom>;
+ let root: Root | null = null;
+
+ beforeEach(() => {
+ Object.defineProperty(globalThis, 'localStorage', {
+ value: createMemoryStorage(),
+ configurable: true,
+ writable: true,
+ });
+ dom = installMiniDom();
+ useWorkspaceStore.reset();
+ useDocumentStore.reset();
+ useToolStore.reset();
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => {
+ root?.unmount();
+ });
+ root = null;
+ }
+ dom.cleanup();
+ if (prevStorage === undefined) {
+ delete (globalThis as unknown as Record<string, unknown>).localStorage;
+ } else {
+ Object.defineProperty(globalThis, 'localStorage', {
+ value: prevStorage,
+ configurable: true,
+ writable: true,
+ });
+ }
+ });
+
+ it('includes the Info tab in default presets and migrates legacy saved workspaces once without re-opening if closed', () => {
+ const infoLoc = findPanelLocation(useWorkspaceStore.getState().layout, 'info');
+ const navLoc = findPanelLocation(useWorkspaceStore.getState().layout, 'navigator');
+ expect(infoLoc).not.toBeNull();
+ expect(infoLoc?.groupId).toBe(navLoc?.groupId);
+
+ localStorage.setItem(
+ WORKSPACE_STORAGE_KEY,
+ JSON.stringify({
+ version: 1,
+ activePreset: 'custom',
+ layout: {
+ leftDocks: [],
+ rightDocks: [
+ {
+ id: 'col-right-main',
+ width: 224,
+ collapsed: false,
+ groups: [
+ {
+ id: 'grp-navigator-subview',
+ panelIds: ['navigator', 'sub-view'],
+ activePanelId: 'navigator',
+ heightRatio: 1,
+ },
+ ],
+ },
+ ],
+ },
+ savedCustomLayout: null,
+ quickAccessItems: [],
+ quickAccessViewMode: 'grid',
+ commandBarIds: [],
+ showStatusBar: true,
+ showDocumentTabs: true,
+ showCommandBar: true,
+ })
+ );
+
+ const migrated = loadWorkspaceState();
+ expect(findPanelLocation(migrated.layout, 'info')?.groupId).toBe('grp-navigator-subview');
+
+ useWorkspaceStore.reset();
+ workspaceStoreActions.togglePanelVisibility('info');
+ expect(findPanelLocation(useWorkspaceStore.getState().layout, 'info')).toBeNull();
+
+ useWorkspaceStore.reset();
+ expect(findPanelLocation(useWorkspaceStore.getState().layout, 'info')).toBeNull();
+ });
+
+ it('renders a simple text-only automatic time counter without manual pause/reset/dropdown controls', () => {
+ let clock = 500;
+ const tracker = new ArtworkTimeTracker({
+ now: () => clock,
+ baseIdleTimeoutMs: 25_000,
+ });
+
+ documentStoreActions.setActiveDocumentId('doc-ui');
+ documentStoreActions.setDimensions({ width: 1920, height: 1080, dpi: 300 });
+ tracker.initDocument('doc-ui', THREE_HOURS_FIFTEEN_MIN_MS);
+ tracker.setActiveDocument('doc-ui', true);
+
+ act(() => {
+ root = createRoot(dom.container as unknown as Element);
+ root.render(<InfoPanel tracker={tracker} colorMode="color" layers={[]} />);
+ });
+
+ const section = dom.container.findByAttr('data-testid', 'info-work-time-section');
+ const clockEl = dom.container.findByAttr('data-testid', 'info-work-time-clock');
+ const hmEl = dom.container.findByAttr('data-testid', 'info-work-time-hm');
+
+ expect(clockEl?.textContent).toBe('03:15:00');
+ expect(hmEl?.textContent).toBe('3h 15m');
+ expect(section?.getAttribute('data-status')).toBe('idle');
+
+ // Pure text-only: no pause, reset, or timeout selector buttons/selects
+ expect(section?.findByTag('button')).toBeNull();
+ expect(section?.findByTag('select')).toBeNull();
+
+ // Supporting interaction alone does not start counting
+ act(() => {
+ tracker.recordSupportingActivity();
+ clock += 5_000;
+ tracker.tick();
+ });
+ expect(dom.container.findByAttr('data-testid', 'info-work-time-clock')?.textContent).toBe('03:15:00');
+
+ // Genuine artwork action starts counting
+ act(() => {
+ tracker.recordArtworkAction();
+ clock += 5_000;
+ tracker.tick();
+ });
+ expect(dom.container.findByAttr('data-testid', 'info-work-time-clock')?.textContent).toBe('03:15:05');
+ expect(dom.container.findByAttr('data-testid', 'info-work-time-section')?.getAttribute('data-status')).toBe('recording');
+
+ // Live cursor stats update without re-render
+ act(() => {
+ window.dispatchEvent(
+ new CustomEvent('canvas-pointer-stat', { detail: { x: 640, y: 360, pressure: 0.5 } })
+ );
+ dom.flushRaf();
+ });
+ expect(dom.container.findByAttr('data-testid', 'info-cursor-x')?.textContent).toBe('640');
+ expect(dom.container.findByAttr('data-testid', 'info-cursor-y')?.textContent).toBe('360');
+
+ act(() => {
+ root?.unmount();
+ });
+ root = null;
+ tracker.resetAll();
+ });
+});
diff --git a/src/utils/__tests__/homeOpenDirect.test.tsx b/src/utils/__tests__/homeOpenDirect.test.tsx
new file mode 100644
index 0000000..9475715
--- /dev/null
+++ b/src/utils/__tests__/homeOpenDirect.test.tsx
@@ -0,0 +1,267 @@
+import React, { act } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ useDocumentLifecycle,
+ UseDocumentLifecycleParams,
+} from '../../components/DocumentLifecycleManager';
+import {
+ documentStoreActions,
+ uiStoreActions,
+ useDocumentStore,
+ useUiStore,
+} from '../../stores';
+import { DocumentTab, LayerItem } from '../../types/editor';
+import { RecentDocument } from '../recentDocumentsManager';
+import { SparseTileGrid } from '../tileEngine';
+
+const mockOpenFile = vi.fn();
+
+vi.mock('../imageLoader', () => ({
+ openFile: (...args: unknown[]) => mockOpenFile(...args),
+}));
+
+vi.mock('../recentDocumentsManager', () => ({
+ saveRecentDocument: vi.fn().mockResolvedValue(undefined),
+}));
+
+// Minimal DOM shim matching the repo's node-environment React test setup
+class MiniNode {
+ public parentNode: MiniElement | null = null;
+ constructor(
+ public nodeType: number,
+ public nodeName: string,
+ public ownerDocument: MiniDocument
+ ) {}
+}
+
+class MiniElement extends EventTarget {
+ public nodeType = 1;
+ public nodeName: string;
+ public tagName: string;
+ public namespaceURI = 'http://www.w3.org/1999/xhtml';
+ public parentNode: MiniElement | null = null;
+ public childNodes: Array<MiniElement | MiniNode> = [];
+ public style: Record<string, string> = {};
+ constructor(tag: string, public ownerDocument: MiniDocument) {
+ super();
+ this.nodeName = tag.toUpperCase();
+ this.tagName = tag.toUpperCase();
+ }
+ appendChild<T extends MiniElement | MiniNode>(child: T): T {
+ child.parentNode = this;
+ this.childNodes.push(child);
+ return child;
+ }
+ removeChild<T extends MiniElement | MiniNode>(child: T): T {
+ const idx = this.childNodes.indexOf(child);
+ if (idx >= 0) this.childNodes.splice(idx, 1);
+ child.parentNode = null;
+ return child;
+ }
+}
+
+class MiniDocument extends EventTarget {
+ public nodeType = 9;
+ public defaultView: unknown = globalThis;
+ public documentElement: MiniElement;
+ public body: MiniElement;
+ constructor() {
+ super();
+ this.documentElement = new MiniElement('html', this);
+ this.body = new MiniElement('body', this);
+ this.documentElement.appendChild(this.body);
+ }
+ createElement(tag: string): MiniElement {
+ return new MiniElement(tag, this);
+ }
+ createTextNode(): MiniNode {
+ return new MiniNode(3, '#text', this);
+ }
+ createComment(): MiniNode {
+ return new MiniNode(8, '#comment', this);
+ }
+}
+
+describe('Home screen direct file opening', () => {
+ let root: Root | null = null;
+ let container: MiniElement | null = null;
+ let hookApi: ReturnType<typeof useDocumentLifecycle> | null = null;
+
+ const baseLayer: LayerItem = {
+ id: 'layer-1',
+ name: 'Layer 1',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ };
+
+ const makeParams = (): UseDocumentLifecycleParams => ({
+ layers: [baseLayer],
+ activeLayer: baseLayer,
+ activeLayerId: 'layer-1',
+ getEffectiveOpacity: () => 1,
+ isLayerEffectivelyVisible: () => true,
+ setActiveLayerId: vi.fn(),
+ resetToNewCanvas: vi.fn(() => ({ layers: [baseLayer], activeLayerId: 'layer-1' })),
+ setDefaultToneFrequency: vi.fn(),
+ clearDocument: vi.fn(),
+ loadDocument: vi.fn(),
+ switchDocumentSession: vi.fn(),
+ resizeCanvas: vi.fn(),
+ copyLayer: vi.fn(() => null),
+ pasteLayer: vi.fn(async () => ({ success: false })),
+ deleteLayer: vi.fn(),
+ pasteLayerFromFile: vi.fn(async () => 'Pasted'),
+ resetZoomAndCenter: vi.fn(),
+ resetHistory: vi.fn(),
+ pushHistoryStep: vi.fn(),
+ showToast: vi.fn(),
+ });
+
+ beforeEach(() => {
+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
+ const miniDoc = new MiniDocument();
+ (globalThis as Record<string, unknown>).document = miniDoc;
+ (globalThis as Record<string, unknown>).window = globalThis;
+ (globalThis as Record<string, unknown>).HTMLElement = MiniElement;
+ (globalThis as Record<string, unknown>).HTMLIFrameElement = class HTMLIFrameElement {};
+ (globalThis as Record<string, unknown>).Element = MiniElement;
+ (globalThis as Record<string, unknown>).Node = MiniNode;
+ container = miniDoc.createElement('div');
+ miniDoc.body.appendChild(container);
+ root = createRoot(container as unknown as HTMLElement);
+
+ documentStoreActions.setDocuments([]);
+ documentStoreActions.setActiveDocumentId(null);
+ documentStoreActions.setSavedFileInfo(null);
+ uiStoreActions.setAppView('home');
+ mockOpenFile.mockReset();
+ hookApi = null;
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => {
+ root?.unmount();
+ });
+ }
+ root = null;
+ container = null;
+ });
+
+ function mountLifecycle(params: UseDocumentLifecycleParams) {
+ function Harness() {
+ hookApi = useDocumentLifecycle(params);
+ return null;
+ }
+ act(() => {
+ root!.render(React.createElement(Harness));
+ });
+ }
+
+ it('switches directly from home screen to workspace when opening a file via handleProcessFile', async () => {
+ const params = makeParams();
+ mountLifecycle(params);
+
+ mockOpenFile.mockResolvedValue({
+ name: 'sketch.ink',
+ dimensions: { width: 1200, height: 800, dpi: 300 },
+ colorMode: 'color',
+ layers: [baseLayer],
+ tileGrid: new SparseTileGrid(),
+ });
+
+ const file = new File([new Uint8Array([1, 2, 3])], 'sketch.ink');
+ expect(useUiStore.getState().appView).toBe('home');
+
+ await act(async () => {
+ await hookApi!.handleProcessFile(file);
+ });
+
+ expect(useUiStore.getState().appView).toBe('workspace');
+ expect(useDocumentStore.getState().documents).toHaveLength(1);
+ expect(useDocumentStore.getState().activeDocumentId).toBe(
+ useDocumentStore.getState().documents[0].id
+ );
+ });
+
+ it('opens a recent document directly in workspace using its persisted FileSystemFileHandle', async () => {
+ const params = makeParams();
+ mountLifecycle(params);
+
+ mockOpenFile.mockResolvedValue({
+ name: 'chapter1.ink',
+ dimensions: { width: 1600, height: 2400, dpi: 600 },
+ colorMode: 'color',
+ layers: [baseLayer],
+ tileGrid: new SparseTileGrid(),
+ });
+
+ const file = new File([new Uint8Array([4, 5, 6])], 'chapter1.ink');
+ const mockHandle = {
+ name: 'chapter1.ink',
+ queryPermission: vi.fn(async () => 'granted' as const),
+ getFile: vi.fn(async () => file),
+ };
+
+ const recent: RecentDocument = {
+ id: 'recent-doc-1',
+ title: 'chapter1.ink',
+ path: 'InkStudio\\chapter1.ink',
+ size: 4096,
+ lastOpened: Date.now(),
+ isStarred: true,
+ isSaved: true,
+ fileType: '.ink',
+ handle: mockHandle,
+ };
+
+ await act(async () => {
+ await hookApi!.handleSelectWelcomeDocument(recent);
+ });
+
+ expect(mockHandle.getFile).toHaveBeenCalledTimes(1);
+ expect(useUiStore.getState().appView).toBe('workspace');
+ expect(useDocumentStore.getState().activeDocumentId).toBe('recent-doc-1');
+ expect(useDocumentStore.getState().savedFileInfo?.handle).toBe(mockHandle);
+ });
+
+ it('focuses an already-open tab directly in workspace when clicked from home screen', async () => {
+ const params = makeParams();
+ const existingTab: DocumentTab = {
+ id: 'open-doc-42',
+ name: 'existing.ink',
+ dimensions: { width: 1000, height: 1000, dpi: 300 },
+ colorMode: 'color',
+ layers: [baseLayer],
+ activeLayerId: 'layer-1',
+ };
+ documentStoreActions.setDocuments([existingTab]);
+ documentStoreActions.setActiveDocumentId('open-doc-42');
+ uiStoreActions.setAppView('home');
+
+ mountLifecycle(params);
+
+ const recent: RecentDocument = {
+ id: 'open-doc-42',
+ title: 'existing.ink',
+ path: 'InkStudio\\existing.ink',
+ size: 2048,
+ lastOpened: Date.now(),
+ isStarred: false,
+ isSaved: true,
+ };
+
+ await act(async () => {
+ await hookApi!.handleSelectWelcomeDocument(recent);
+ });
+
+ expect(useUiStore.getState().appView).toBe('workspace');
+ expect(useDocumentStore.getState().documents).toHaveLength(1);
+ expect(mockOpenFile).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/utils/__tests__/performanceOptimization.test.ts b/src/utils/__tests__/performanceOptimization.test.ts
new file mode 100644
index 0000000..eae6d67
--- /dev/null
+++ b/src/utils/__tests__/performanceOptimization.test.ts
@@ -0,0 +1,456 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import React from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import {
+ AppSettings,
+ DEFAULT_APP_SETTINGS,
+ loadAppSettings,
+ saveAppSettings,
+} from '../../types/settings';
+import { PerformanceSettingsTab } from '../../components/PerformanceSettingsTab';
+import {
+ GPU_TEXTURE_POOL_CONFIGS,
+ buildPerformancePreset,
+ computeAdobeMemoryLimits,
+ computeRecommendedSettings,
+ memoryMbToPercent,
+ memoryPercentToMb,
+ performanceManager,
+ resolveEffectiveDpr,
+} from '../performanceManager';
+import { ViewportCompositor } from '../compositor';
+import { SparseTileGrid, TILE_SIZE, createTileBuffer } from '../tileEngine';
+import { DocumentStore } from '../documentStore';
+import { canUseWebGlForBrush } from '../../engine/BrushEngine';
+
+describe('Performance & Optimization System', () => {
+ beforeEach(() => {
+ const storage: Record<string, string> = {};
+ (globalThis as any).localStorage = {
+ getItem: (k: string) => storage[k] || null,
+ setItem: (k: string, v: string) => {
+ storage[k] = String(v);
+ },
+ removeItem: (k: string) => {
+ delete storage[k];
+ },
+ clear: () => {
+ Object.keys(storage).forEach((k) => delete storage[k]);
+ },
+ };
+ performanceManager.applySettings(DEFAULT_APP_SETTINGS);
+ });
+
+ it('sanitizes and persists all new performance settings cleanly across legacy & corrupt storage', () => {
+ const defaults = loadAppSettings();
+ expect(defaults.renderBackend).toBe('auto');
+ expect(defaults.gpuPowerPreference).toBe('high-performance');
+ expect(defaults.desktopGraphicsApi).toBe('auto');
+ expect(defaults.gpuBrushAcceleration).toBe(true);
+ expect(defaults.gpuTexturePoolPreset).toBe('high');
+ expect(defaults.layerStackCaching).toBe(true);
+ expect(defaults.viewportResolutionScale).toBe('capped-2x');
+ expect(defaults.canvasFilteringQuality).toBe('auto');
+ expect(defaults.memoryAllocationPercent).toBe(60);
+ expect(defaults.undoRamSteps).toBe(15);
+ expect(defaults.offloadInactiveTabs).toBe(true);
+ expect(defaults.scratchDiskCompression).toBe('lz4');
+ expect(defaults.cpuWorkerThreads).toBe(0);
+ expect(defaults.useNativeRustAcceleration).toBe(true);
+ expect(defaults.preview3DMaxResolution).toBe(1920);
+ expect(defaults.preview3DAntialias).toBe(true);
+
+ // Corrupt values fall back safely
+ localStorage.setItem(
+ 'ink_studio_app_settings',
+ JSON.stringify({
+ renderBackend: 'invalid-backend',
+ gpuPowerPreference: 'turbo',
+ desktopGraphicsApi: 'metal99',
+ gpuTexturePoolPreset: 'massive',
+ viewportResolutionScale: '8x',
+ canvasFilteringQuality: 'blurry',
+ scratchDiskCompression: 'bzip',
+ tileMemoryBudgetMb: 999999,
+ memoryAllocationPercent: 5,
+ maxHistorySteps: 5000,
+ undoRamSteps: 1,
+ cpuWorkerThreads: -3,
+ preview3DMaxResolution: 9999,
+ })
+ );
+ const sanitized = loadAppSettings();
+ expect(sanitized.renderBackend).toBe('auto');
+ expect(sanitized.gpuPowerPreference).toBe('high-performance');
+ expect(sanitized.desktopGraphicsApi).toBe('auto');
+ expect(sanitized.gpuTexturePoolPreset).toBe('high');
+ expect(sanitized.viewportResolutionScale).toBe('capped-2x');
+ expect(sanitized.canvasFilteringQuality).toBe('auto');
+ expect(sanitized.scratchDiskCompression).toBe('lz4');
+ expect(sanitized.tileMemoryBudgetMb).toBe(1024);
+ expect(sanitized.memoryAllocationPercent).toBe(20);
+ expect(sanitized.maxHistorySteps).toBe(200);
+ expect(sanitized.undoRamSteps).toBe(4);
+ expect(sanitized.cpuWorkerThreads).toBe(0);
+ expect(sanitized.preview3DMaxResolution).toBe(1920);
+
+ // Valid high-RAM workstation settings round-trip cleanly
+ saveAppSettings({
+ ...DEFAULT_APP_SETTINGS,
+ tileMemoryBudgetMb: 16384,
+ memoryAllocationPercent: 65,
+ maxHistorySteps: 150,
+ undoRamSteps: 30,
+ renderBackend: 'canvas2d',
+ gpuPowerPreference: 'low-power',
+ desktopGraphicsApi: 'vulkan',
+ gpuTexturePoolPreset: 'ultra',
+ viewportResolutionScale: '1x',
+ canvasFilteringQuality: 'pixelated',
+ scratchDiskCompression: 'none',
+ cpuWorkerThreads: 8,
+ preview3DMaxResolution: 2560,
+ preview3DAntialias: false,
+ });
+
+ const loaded = loadAppSettings();
+ expect(loaded.tileMemoryBudgetMb).toBe(16384);
+ expect(loaded.memoryAllocationPercent).toBe(65);
+ expect(loaded.maxHistorySteps).toBe(150);
+ expect(loaded.undoRamSteps).toBe(30);
+ expect(loaded.renderBackend).toBe('canvas2d');
+ expect(loaded.gpuPowerPreference).toBe('low-power');
+ expect(loaded.desktopGraphicsApi).toBe('vulkan');
+ expect(loaded.gpuTexturePoolPreset).toBe('ultra');
+ expect(loaded.viewportResolutionScale).toBe('1x');
+ expect(loaded.canvasFilteringQuality).toBe('pixelated');
+ expect(loaded.scratchDiskCompression).toBe('none');
+ expect(loaded.cpuWorkerThreads).toBe(8);
+ expect(loaded.preview3DMaxResolution).toBe(2560);
+ expect(loaded.preview3DAntialias).toBe(false);
+ });
+
+ it('computes Adobe-style memory limits and converts cleanly between % and MB', () => {
+ const limits16g = computeAdobeMemoryLimits(16384);
+ expect(limits16g.minMb).toBe(256);
+ expect(limits16g.idealMinMb).toBe(8192); // 50% of 16GB
+ expect(limits16g.idealMaxMb).toBe(11392); // floor(16384 * 0.7 / 128) * 128
+ expect(limits16g.maxMb).toBe(13824); // floor(16384 * 0.85 / 128) * 128
+
+ const mbAt60 = memoryPercentToMb(60, 16384);
+ expect(mbAt60 % 128).toBe(0);
+ expect(memoryMbToPercent(mbAt60, 16384)).toBe(60);
+
+ // 64GB workstation clamps safely at 32GB ceiling
+ const limits64g = computeAdobeMemoryLimits(65536);
+ expect(limits64g.maxMb).toBe(32768);
+ });
+
+ it('resolves viewport HiDPI resolution scaling modes accurately', () => {
+ expect(resolveEffectiveDpr(2.5, 'native')).toBe(2.5);
+ expect(resolveEffectiveDpr(2.5, 'capped-2x')).toBe(2);
+ expect(resolveEffectiveDpr(1.5, 'capped-2x')).toBe(1.5);
+ expect(resolveEffectiveDpr(2.0, '1x')).toBe(1);
+ expect(resolveEffectiveDpr(2.0, '0.75x')).toBe(0.75);
+ });
+
+ it('generates calibrated optimization presets for battery, balanced, maximum, and compatibility', () => {
+ const battery = buildPerformancePreset('battery', 16384);
+ expect(battery.gpuPowerPreference).toBe('low-power');
+ expect(battery.gpuTexturePoolPreset).toBe('low');
+ expect(battery.viewportResolutionScale).toBe('1x');
+ expect(battery.memoryAllocationPercent).toBe(40);
+
+ const max = buildPerformancePreset('maximum', 32768);
+ expect(max.renderBackend).toBe('webgl2');
+ expect(max.gpuPowerPreference).toBe('high-performance');
+ expect(max.gpuTexturePoolPreset).toBe('ultra');
+ expect(max.viewportResolutionScale).toBe('native');
+
+ const compat = buildPerformancePreset('compatibility', 8192);
+ expect(compat.renderBackend).toBe('canvas2d');
+ expect(compat.gpuBrushAcceleration).toBe(false);
+ expect(compat.layerStackCaching).toBe(false);
+ });
+
+ it('disables GPU brush dispatch when renderBackend is canvas2d or gpuBrushAcceleration is false', () => {
+ performanceManager.applySettings({
+ ...DEFAULT_APP_SETTINGS,
+ renderBackend: 'canvas2d',
+ gpuBrushAcceleration: true,
+ });
+ expect(canUseWebGlForBrush()).toBe(false);
+
+ performanceManager.applySettings({
+ ...DEFAULT_APP_SETTINGS,
+ renderBackend: 'auto',
+ gpuBrushAcceleration: false,
+ });
+ expect(canUseWebGlForBrush()).toBe(false);
+ });
+
+ it('ViewportCompositor skips WebGL2 init when renderBackend is canvas2d and reuses 2D ImageData with frustum culling', () => {
+ let webglRequested = false;
+ let createImageDataCalls = 0;
+ const drawImagePositions: Array<{ x: number; y: number }> = [];
+
+ const mock2DCtx = {
+ save: vi.fn(),
+ restore: vi.fn(),
+ clearRect: vi.fn(),
+ scale: vi.fn(),
+ translate: vi.fn(),
+ rotate: vi.fn(),
+ fillRect: vi.fn(),
+ drawImage: vi.fn((_img: unknown, x: number, y: number) => {
+ drawImagePositions.push({ x, y });
+ }),
+ putImageData: vi.fn(),
+ createImageData: vi.fn((w: number, h: number) => {
+ createImageDataCalls++;
+ return { width: w, height: h, data: new Uint8ClampedArray(w * h * 4) };
+ }),
+ imageSmoothingEnabled: true,
+ fillStyle: '',
+ globalAlpha: 1,
+ globalCompositeOperation: 'source-over',
+ };
+
+ const mockCanvas = {
+ width: 512,
+ height: 512,
+ getContext: (kind: string) => {
+ if (kind === 'webgl2') {
+ webglRequested = true;
+ return null;
+ }
+ return mock2DCtx;
+ },
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ } as unknown as HTMLCanvasElement;
+
+ const origDocument = (globalThis as any).document;
+ (globalThis as any).document = {
+ createElement: () => ({
+ width: TILE_SIZE,
+ height: TILE_SIZE,
+ getContext: () => mock2DCtx,
+ }),
+ };
+
+ try {
+ const compositor = new ViewportCompositor(mockCanvas, {
+ renderBackend: 'canvas2d',
+ gpuTexturePoolPreset: 'low',
+ filteringQuality: 'pixelated',
+ });
+
+ expect(webglRequested).toBe(false);
+ expect(compositor.getBackend()).toBe('canvas2d');
+ expect(compositor.getTelemetry().backend).toBe('canvas2d');
+ expect(compositor.getTelemetry().estimatedVramMb).toBe(0);
+
+ // Populate 4 tiles: (0,0) and (1,0) visible, (10,10) and (11,11) far off-screen
+ const grid = new SparseTileGrid();
+ const layerId = 'layer-1';
+ grid.setLayerFormat(layerId, 'color-32bit');
+ for (const [tx, ty] of [
+ [0, 0],
+ [1, 0],
+ [10, 10],
+ [11, 11],
+ ]) {
+ const tile = createTileBuffer(layerId, tx, ty, 'color-32bit', 0);
+ tile.data!.fill(255);
+ grid.setTile(layerId, tx, ty, tile);
+ }
+
+ const layers = [
+ {
+ id: layerId,
+ name: 'Layer 1',
+ type: 'raster' as const,
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal' as const,
+ locked: false,
+ parentId: null,
+ },
+ ];
+
+ // Render two consecutive frames focused on top-left corner (0..512, 0..512)
+ const dims = { width: 4096, height: 4096, dpi: 300 };
+ const transform = { pan: { x: 2048, y: 2048 }, zoom: 1, rotation: 0 };
+
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ });
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ });
+
+ // Reusable ImageData allocated ONCE total across all tiles & frames!
+ expect(createImageDataCalls).toBe(1);
+ // Pixelated filtering applied in 2D mode
+ expect(mock2DCtx.imageSmoothingEnabled).toBe(false);
+ // Off-screen tiles (10,10) and (11,11) were culled (never drawn at x >= 2560)
+ expect(drawImagePositions.length).toBeGreaterThan(0);
+ expect(drawImagePositions.every((p) => p.x < 1024 && p.y < 1024)).toBe(true);
+
+ compositor.dispose();
+ } finally {
+ (globalThis as any).document = origDocument;
+ }
+ });
+
+ it('DocumentStore and performanceManager purge tiles, undo steps, and GPU caches', async () => {
+ const store = new DocumentStore({ totalTileBudgetMb: 64, offloadInactiveUndoOnSwitch: true });
+ const s1 = store.getOrCreateSession('doc-a');
+ const s2 = store.getOrCreateSession('doc-b');
+
+ const t1 = createTileBuffer('l1', 0, 0, 'color-32bit', 0);
+ t1.data!.fill(128);
+ s1.tileGrid.setTile('l1', 0, 0, t1);
+
+ const t2 = createTileBuffer('l2', 0, 0, 'color-32bit', 0);
+ t2.data!.fill(200);
+ s2.tileGrid.setTile('l2', 0, 0, t2);
+
+ store.setActiveDocument('doc-b');
+ expect(store.getTotalActiveTileBytes()).toBeGreaterThan(0);
+
+ let gpuFlushed = false;
+ performanceManager.registerCompositorHooks({
+ getTelemetry: () => ({
+ backend: 'webgl2',
+ rendererName: 'Mock RTX',
+ arrayPoolUsed: 12,
+ arrayPoolCapacity: GPU_TEXTURE_POOL_CONFIGS.high.arrayLayers,
+ texture2DPoolUsed: 0,
+ estimatedVramMb: 128,
+ stackCacheHits: 42,
+ stackCacheRebuilds: 2,
+ }),
+ flushGpuCaches: () => {
+ gpuFlushed = true;
+ },
+ });
+ performanceManager.registerMemoryHooks({
+ getActiveTileBytes: () => store.getTotalActiveTileBytes(),
+ getTileBudgetBytes: () => store.getTileBudgetBytes(),
+ getUndoStats: () => store.getUndoMemoryStats(),
+ getActiveSessionIds: () => store.getActiveSessionIds(),
+ purgeTiles: () => store.purgeTileMemory(),
+ purgeUndo: () => store.purgeUndoMemory(),
+ });
+
+ const beforeTelemetry = await performanceManager.getMemoryTelemetry();
+ expect(beforeTelemetry.compositor.rendererName).toBe('Mock RTX');
+ expect(beforeTelemetry.tileBudgetMb).toBe(64);
+
+ const purgeRes = await performanceManager.purgeMemory('all');
+ expect(purgeRes.flushedGpuTextures).toBe(true);
+ expect(gpuFlushed).toBe(true);
+ // Inactive session doc-a had its tile evicted to scratch disk
+ expect(s1.tileGrid.getMemoryManager()!.getActiveMemoryBytes()).toBe(0);
+
+ performanceManager.registerCompositorHooks(null);
+ performanceManager.registerMemoryHooks(null);
+ await store.clearAllSessions();
+ });
+
+ it('renders PerformanceSettingsTab safely even with stale/partial pre-HMR settings in desktop and web modes', () => {
+ const staleLegacySettings = {
+ themePreset: 'modern',
+ modernAccent: 'purple',
+ tileMemoryBudgetMb: 1024,
+ } as unknown as AppSettings;
+
+ const htmlDesktop = renderToStaticMarkup(
+ React.createElement(PerformanceSettingsTab, {
+ settings: staleLegacySettings,
+ isDesktopTauri: true,
+ onUpdateSettings: () => {},
+ onShowToast: () => {},
+ })
+ );
+ expect(htmlDesktop).toContain('performance-settings-tab');
+ expect(htmlDesktop).toContain('Automatic Settings');
+ expect(htmlDesktop).toContain('Memory Usage (Max RAM)');
+ expect(htmlDesktop).toContain('Graphics &amp; Rendering');
+ expect(htmlDesktop).toContain('Advanced Settings');
+
+ const htmlWeb = renderToStaticMarkup(
+ React.createElement(PerformanceSettingsTab, {
+ settings: DEFAULT_APP_SETTINGS,
+ isDesktopTauri: false,
+ onUpdateSettings: () => {},
+ onShowToast: () => {},
+ })
+ );
+ expect(htmlWeb).toContain('performance-settings-tab');
+ expect(htmlWeb).toContain('Automatic Settings');
+ expect(htmlWeb).toContain('Free Memory');
+ });
+
+ it('auto-calibrates recommended settings for low-RAM, workstation, and software-only GPUs', () => {
+ // 4 GB laptop with integrated GPU
+ const lowRam = computeRecommendedSettings({
+ totalRamMb: 4096,
+ cpuLogicalCores: 4,
+ gpus: [{ id: 'g0', name: 'Intel UHD 620', vendor: 'Intel', vramMb: 128, kind: 'integrated', isPrimary: true }],
+ activeWebGl: {
+ available: true,
+ renderer: 'ANGLE (Intel UHD 620)',
+ vendor: 'Intel',
+ glVersion: 'WebGL 2.0',
+ maxTextureSize: 8192,
+ maxArrayLayers: 256,
+ },
+ });
+ expect(lowRam.settings.autoOptimizePerformance).toBe(true);
+ expect(lowRam.settings.gpuTexturePoolPreset).toBe('low');
+ expect(lowRam.settings.viewportResolutionScale).toBe('1x');
+ expect(lowRam.settings.tileMemoryBudgetMb).toBe(2048);
+
+ // 32 GB workstation with discrete RTX GPU
+ const workstation = computeRecommendedSettings({
+ totalRamMb: 32768,
+ cpuLogicalCores: 16,
+ gpus: [{ id: 'g0', name: 'NVIDIA GeForce RTX 4080', vendor: 'NVIDIA', vramMb: 16384, kind: 'discrete', isPrimary: true }],
+ activeWebGl: {
+ available: true,
+ renderer: 'ANGLE (NVIDIA GeForce RTX 4080)',
+ vendor: 'NVIDIA',
+ glVersion: 'WebGL 2.0',
+ maxTextureSize: 16384,
+ maxArrayLayers: 2048,
+ },
+ });
+ expect(workstation.settings.gpuTexturePoolPreset).toBe('ultra');
+ expect(workstation.settings.gpuPowerPreference).toBe('high-performance');
+ expect(workstation.settings.preview3DMaxResolution).toBe(2560);
+ expect(workstation.settings.undoRamSteps).toBe(25);
+
+ // Software-only / no hardware GPU
+ const softwareOnly = computeRecommendedSettings({
+ totalRamMb: 8192,
+ cpuLogicalCores: 4,
+ gpus: [{ id: 'g0', name: 'Microsoft Basic Render Driver', vendor: 'Microsoft', vramMb: 0, kind: 'software', isPrimary: true }],
+ activeWebGl: {
+ available: true,
+ renderer: 'Google SwiftShader',
+ vendor: 'Google',
+ glVersion: 'WebGL 2.0',
+ maxTextureSize: 4096,
+ maxArrayLayers: 256,
+ },
+ });
+ expect(softwareOnly.settings.renderBackend).toBe('canvas2d');
+ expect(softwareOnly.settings.gpuBrushAcceleration).toBe(false);
+ expect(softwareOnly.settings.layerStackCaching).toBe(false);
+ });
+});
diff --git a/src/utils/__tests__/recentDocumentsManager.test.ts b/src/utils/__tests__/recentDocumentsManager.test.ts
index b84ee27..741a53f 100644
--- a/src/utils/__tests__/recentDocumentsManager.test.ts
+++ b/src/utils/__tests__/recentDocumentsManager.test.ts
@@ -148,4 +148,26 @@ describe('recentDocumentsManager', () => {
expect(docs.find((d) => d.id === 'doc-saved-1')).toBeDefined();
expect(docs.length).toBe(1);
});
+
+ it('strips non-serializable file handles in localStorage fallback', async () => {
+ const fakeHandle = {
+ name: 'Panel.ink',
+ getFile: async () => new File([new Uint8Array([1, 2, 3])], 'Panel.ink'),
+ };
+ await saveRecentDocument({
+ id: 'doc-with-handle',
+ title: 'Panel.ink',
+ path: 'InkStudio\\Panel.ink',
+ size: 2048,
+ isStarred: false,
+ isSaved: true,
+ fileType: '.ink',
+ handle: fakeHandle,
+ });
+
+ const docs = await loadRecentDocuments();
+ const saved = docs.find((d) => d.id === 'doc-with-handle');
+ expect(saved).toBeDefined();
+ expect(saved?.handle).toBeUndefined();
+ });
});
diff --git a/src/utils/artworkTimeTracker.ts b/src/utils/artworkTimeTracker.ts
new file mode 100644
index 0000000..5c8b96e
--- /dev/null
+++ b/src/utils/artworkTimeTracker.ts
@@ -0,0 +1,697 @@
+export const BASE_IDLE_TIMEOUT_MS = 25_000; // Default threshold before cadence samples arrive
+export const MIN_ADAPTIVE_IDLE_MS = 15_000; // Fast sketching cadence -> pauses promptly (~15-18s)
+export const MAX_ADAPTIVE_IDLE_MS = 60_000; // Deliberate painting cadence -> allows up to 60s between strokes
+export const CADENCE_WINDOW_SIZE = 8; // Rolling window of recent inter-action intervals
+/**
+ * Maximum time supporting non-edit interactions (pan/zoom/color pick/shortcuts)
+ * may sustain an already-active session without a fresh canvas or layer edit.
+ */
+export const MAX_NON_EDIT_SUSTAIN_MS = 90_000;
+export const TICK_INTERVAL_MS = 1_000;
+/**
+ * Maximum allowable gap between two consecutive ticks before assuming OS sleep,
+ * tab throttling, or process suspension. Protects against adding hours when a
+ * laptop wakes from sleep.
+ */
+export const MAX_SLEEP_GAP_MS = 5_000;
+
+export type WorkTimeStatus = 'recording' | 'idle' | 'inactive';
+
+export interface DocumentWorkTimeEntry {
+ documentId: string;
+ accumulatedMs: number;
+ sessionMs: number;
+}
+
+export interface ArtworkTimeSnapshot {
+ documentId: string | null;
+ accumulatedMs: number;
+ sessionMs: number;
+ status: WorkTimeStatus;
+ effectiveIdleTimeoutMs: number;
+ windowFocused: boolean;
+}
+
+export interface ArtworkTimeTrackerOptions {
+ now?: () => number;
+ baseIdleTimeoutMs?: number;
+ minAdaptiveIdleMs?: number;
+ maxAdaptiveIdleMs?: number;
+ maxNonEditSustainMs?: number;
+ tickIntervalMs?: number;
+ maxSleepGapMs?: number;
+}
+
+/**
+ * Validates and normalizes persisted artwork work-time milliseconds.
+ * Returns a non-negative safe integer (0 for invalid/missing values).
+ */
+export function sanitizeWorkTimeMs(raw: unknown): number {
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0) {
+ return 0;
+ }
+ const maxReasonableMs = 100 * 365 * 24 * 60 * 60 * 1000;
+ return Math.min(maxReasonableMs, Math.round(raw));
+}
+
+/**
+ * Extracts `workTimeMs` from a serialized manifest or legacy payload, supporting
+ * both primary (`workTimeMs`) and fallback field names if present.
+ */
+export function extractWorkTimeMsFromManifest(raw: unknown): number | undefined {
+ if (!raw || typeof raw !== 'object') return undefined;
+ const rec = raw as Record<string, unknown>;
+ const candidate =
+ rec.workTimeMs !== undefined
+ ? rec.workTimeMs
+ : rec.artworkTimeMs !== undefined
+ ? rec.artworkTimeMs
+ : rec.elapsedTimeMs;
+ if (typeof candidate !== 'number' || !Number.isFinite(candidate) || candidate < 0) {
+ return undefined;
+ }
+ return sanitizeWorkTimeMs(candidate);
+}
+
+/**
+ * Splits milliseconds into exact non-negative `{ hours, minutes, seconds }`.
+ */
+export function splitWorkTimeMs(ms: number): { hours: number; minutes: number; seconds: number } {
+ const safeMs = sanitizeWorkTimeMs(ms);
+ const totalSeconds = Math.floor(safeMs / 1000);
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
+ const seconds = totalSeconds % 60;
+ return { hours, minutes, seconds };
+}
+
+/**
+ * Formats duration as fixed-width `HH:MM:SS` (e.g. `03:15:42` or `102:05:09`).
+ */
+export function formatWorkTimeClock(ms: number): string {
+ const { hours, minutes, seconds } = splitWorkTimeMs(ms);
+ const hh = String(hours).padStart(2, '0');
+ const mm = String(minutes).padStart(2, '0');
+ const ss = String(seconds).padStart(2, '0');
+ return `${hh}:${mm}:${ss}`;
+}
+
+/**
+ * Formats duration as human-readable hours & minutes (e.g. `3h 15m`, `42m`, `0m`).
+ */
+export function formatWorkTimeHoursMinutes(ms: number): string {
+ const { hours, minutes } = splitWorkTimeMs(ms);
+ if (hours > 0) {
+ return `${hours}h ${String(minutes).padStart(2, '0')}m`;
+ }
+ return `${minutes}m`;
+}
+
+/**
+ * Builds a minimal standards-compliant Adobe XMP XML packet embedding Ink Studio's
+ * tracked artwork work time for `.psd` / `.psb` round-trip persistence.
+ */
+export function buildInkStudioXmpMetadata(workTimeMs: number): string {
+ const safeMs = sanitizeWorkTimeMs(workTimeMs);
+ return (
+ `<?xpacket begin="\uFEFF" id="W5M0MpCehiHzreSzNTczkc9d"?>` +
+ `<x:xmpmeta xmlns:x="adobe:ns:meta/">` +
+ `<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">` +
+ `<rdf:Description rdf:about="" xmlns:inkstudio="http://inkstudio.app/ns/1.0/">` +
+ `<inkstudio:WorkTimeMs>${safeMs}</inkstudio:WorkTimeMs>` +
+ `</rdf:Description>` +
+ `</rdf:RDF>` +
+ `</x:xmpmeta>` +
+ `<?xpacket end="w"?>`
+ );
+}
+
+/**
+ * Parses `inkstudio:WorkTimeMs` out of an XMP metadata string (from PSD/PSB).
+ */
+export function extractWorkTimeMsFromXmp(xmp: string | undefined | null): number | undefined {
+ if (!xmp || typeof xmp !== 'string') return undefined;
+ const tagMatch = /<inkstudio:WorkTimeMs>\s*(\d+(?:\.\d+)?)\s*<\/inkstudio:WorkTimeMs>/i.exec(xmp);
+ if (tagMatch) {
+ return sanitizeWorkTimeMs(Number(tagMatch[1]));
+ }
+ const attrMatch = /inkstudio:WorkTimeMs="(\d+(?:\.\d+)?)"/i.exec(xmp);
+ if (attrMatch) {
+ return sanitizeWorkTimeMs(Number(attrMatch[1]));
+ }
+ return undefined;
+}
+
+/**
+ * Fast fallback scanner for `inkstudio:WorkTimeMs` directly inside a raw PSD/PSB ArrayBuffer
+ * (useful when Tauri's native Rust PSD loader parses pixels and doesn't return XMP).
+ */
+export function extractWorkTimeMsFromPsdBuffer(buffer: ArrayBuffer | Uint8Array): number | undefined {
+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
+ if (bytes.byteLength < 64) return undefined;
+ const needle = 'inkstudio:WorkTimeMs';
+ const needleBytes = new Uint8Array(needle.length);
+ for (let i = 0; i < needle.length; i++) {
+ needleBytes[i] = needle.charCodeAt(i);
+ }
+ const limit = bytes.byteLength - needleBytes.length;
+ for (let i = 0; i <= limit; i++) {
+ if (bytes[i] !== needleBytes[0]) continue;
+ let matched = true;
+ for (let j = 1; j < needleBytes.length; j++) {
+ if (bytes[i + j] !== needleBytes[j]) {
+ matched = false;
+ break;
+ }
+ }
+ if (matched) {
+ const start = Math.max(0, i - 4);
+ const end = Math.min(bytes.byteLength, i + 96);
+ const snippet = new TextDecoder('utf-8', { fatal: false }).decode(bytes.subarray(start, end));
+ const parsed = extractWorkTimeMsFromXmp(snippet);
+ if (parsed !== undefined) return parsed;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Smart, fully automatic per-document artwork time tracker.
+ *
+ * Safety & accuracy guarantees:
+ * 1. **Action-gated start**: Never counts on file open, cursor hover, or clicking UI
+ * tabs/menus. Counting begins only when the user takes a genuine artwork action
+ * (canvas draw/edit, tile mutation, or layer edit).
+ * 2. **Adaptive inactivity timeout**: Observes the artist's recent stroke/edit cadence
+ * and dynamically adapts the idle timeout between 15s (brisk sketching) and 60s
+ * (deliberate painting/shading).
+ * 3. **Supporting-interaction sustain cap**: Zooming, panning, color picking, and
+ * shortcuts sustain an already-active session while working, but never start an
+ * idle timer and stop extending if no genuine artwork edit occurs within 90s.
+ * 4. **Instant pause on context loss**: Immediately flushes and pauses on window blur,
+ * tab hide, Home screen navigation, or document tab switch.
+ * 5. **OS sleep / freeze protection**: Caps anomalous tick jumps (> 5s) so waking a
+ * sleeping laptop never inflates recorded work time.
+ */
+export class ArtworkTimeTracker {
+ private entries = new Map<string, DocumentWorkTimeEntry>();
+ private activeDocumentId: string | null = null;
+ private workspaceVisible = false;
+ private windowFocused = true;
+ private isDrawingStroke = false;
+ private status: WorkTimeStatus = 'inactive';
+
+ private lastArtworkActionAt: number | null = null;
+ private lastActivityAt: number | null = null;
+ private lastTickAt: number | null = null;
+ private cadenceGapsMs: number[] = [];
+ private effectiveIdleTimeoutMs: number;
+ private tickTimer: ReturnType<typeof setInterval> | null = null;
+
+ private readonly nowFn: () => number;
+ private readonly baseIdleTimeoutMs: number;
+ private readonly minAdaptiveIdleMs: number;
+ private readonly maxAdaptiveIdleMs: number;
+ private readonly maxNonEditSustainMs: number;
+ private readonly tickIntervalMs: number;
+ private readonly maxSleepGapMs: number;
+
+ private listeners = new Set<() => void>();
+ private version = 0;
+ private cachedSnapshotKey = '';
+ private cachedSnapshot: ArtworkTimeSnapshot | null = null;
+
+ constructor(options: ArtworkTimeTrackerOptions = {}) {
+ this.nowFn =
+ options.now ??
+ (() =>
+ typeof performance !== 'undefined' && typeof performance.now === 'function'
+ ? performance.now()
+ : Date.now());
+ this.baseIdleTimeoutMs = Math.max(5_000, Math.round(options.baseIdleTimeoutMs ?? BASE_IDLE_TIMEOUT_MS));
+ this.minAdaptiveIdleMs = Math.max(5_000, Math.round(options.minAdaptiveIdleMs ?? MIN_ADAPTIVE_IDLE_MS));
+ this.maxAdaptiveIdleMs = Math.max(
+ this.minAdaptiveIdleMs,
+ Math.round(options.maxAdaptiveIdleMs ?? MAX_ADAPTIVE_IDLE_MS)
+ );
+ this.maxNonEditSustainMs = Math.max(
+ this.maxAdaptiveIdleMs,
+ Math.round(options.maxNonEditSustainMs ?? MAX_NON_EDIT_SUSTAIN_MS)
+ );
+ this.effectiveIdleTimeoutMs = this.baseIdleTimeoutMs;
+ this.tickIntervalMs = Math.max(50, Math.round(options.tickIntervalMs ?? TICK_INTERVAL_MS));
+ this.maxSleepGapMs = Math.max(
+ this.tickIntervalMs * 2,
+ Math.round(options.maxSleepGapMs ?? MAX_SLEEP_GAP_MS)
+ );
+ }
+
+ private emit(): void {
+ this.version += 1;
+ for (const listener of this.listeners) {
+ listener();
+ }
+ }
+
+ private startInterval(): void {
+ if (this.tickTimer !== null) return;
+ this.tickTimer = setInterval(() => {
+ this.tick();
+ }, this.tickIntervalMs);
+ }
+
+ private stopInterval(): void {
+ if (this.tickTimer !== null) {
+ clearInterval(this.tickTimer);
+ this.tickTimer = null;
+ }
+ }
+
+ private ensureEntry(docId: string): DocumentWorkTimeEntry {
+ let entry = this.entries.get(docId);
+ if (!entry) {
+ entry = {
+ documentId: docId,
+ accumulatedMs: 0,
+ sessionMs: 0,
+ };
+ this.entries.set(docId, entry);
+ }
+ return entry;
+ }
+
+ private computeNonRecordingStatus(): WorkTimeStatus {
+ if (!this.activeDocumentId || !this.workspaceVisible) {
+ return 'inactive';
+ }
+ return 'idle';
+ }
+
+ private resetLiveSessionCounters(): void {
+ this.isDrawingStroke = false;
+ this.lastArtworkActionAt = null;
+ this.lastActivityAt = null;
+ this.lastTickAt = null;
+ this.cadenceGapsMs = [];
+ this.effectiveIdleTimeoutMs = this.baseIdleTimeoutMs;
+ }
+
+ private updateAdaptiveCadence(gapMs: number): void {
+ // Only learn from realistic active inter-action intervals (ignore rapid sub-300ms bursts & long AFK breaks)
+ if (gapMs < 300 || gapMs > this.maxAdaptiveIdleMs) {
+ return;
+ }
+ this.cadenceGapsMs.push(gapMs);
+ if (this.cadenceGapsMs.length > CADENCE_WINDOW_SIZE) {
+ this.cadenceGapsMs.shift();
+ }
+ if (this.cadenceGapsMs.length < 2) {
+ this.effectiveIdleTimeoutMs = this.baseIdleTimeoutMs;
+ return;
+ }
+ // Use 75th-percentile interval so occasional short pauses don't cause premature cutoffs
+ const sorted = [...this.cadenceGapsMs].sort((a, b) => a - b);
+ const p75Idx = Math.min(sorted.length - 1, Math.floor((sorted.length - 1) * 0.75));
+ const typicalGapMs = sorted[p75Idx];
+ const computed = Math.round(typicalGapMs * 2.5 + 12_000);
+ this.effectiveIdleTimeoutMs = Math.max(
+ this.minAdaptiveIdleMs,
+ Math.min(this.maxAdaptiveIdleMs, computed)
+ );
+ }
+
+ private computeIdleDeadline(now: number): number {
+ if (this.isDrawingStroke) return now;
+ const baseActivity = this.lastActivityAt ?? this.lastTickAt ?? now;
+ const activityDeadline = baseActivity + this.effectiveIdleTimeoutMs;
+ if (this.lastArtworkActionAt !== null) {
+ const hardSustainCap = this.lastArtworkActionAt + this.maxNonEditSustainMs;
+ return Math.min(activityDeadline, hardSustainCap);
+ }
+ return activityDeadline;
+ }
+
+ /**
+ * Advances accrued time for the active document up to `now`, enforcing the
+ * adaptive inactivity deadline, non-edit sustain cap, and OS sleep guard.
+ */
+ private advanceActiveClock(now: number): boolean {
+ if (this.status !== 'recording' || this.lastTickAt === null || !this.activeDocumentId) {
+ return false;
+ }
+
+ const entry = this.entries.get(this.activeDocumentId);
+ if (!entry || !this.workspaceVisible || !this.windowFocused) {
+ this.lastTickAt = null;
+ this.status = this.computeNonRecordingStatus();
+ this.stopInterval();
+ return true;
+ }
+
+ const dt = now - this.lastTickAt;
+ if (!Number.isFinite(dt) || dt <= 0) {
+ this.lastTickAt = now;
+ return false;
+ }
+
+ const idleDeadline = this.computeIdleDeadline(now);
+
+ // Sleep / hibernation / heavy throttling protection
+ if (dt > this.maxSleepGapMs) {
+ const cappedCredit = Math.min(
+ this.tickIntervalMs,
+ Math.max(0, idleDeadline - this.lastTickAt)
+ );
+ if (cappedCredit > 0) {
+ entry.accumulatedMs += cappedCredit;
+ entry.sessionMs += cappedCredit;
+ }
+ this.isDrawingStroke = false;
+ this.lastTickAt = null;
+ this.status = 'idle';
+ this.stopInterval();
+ return true;
+ }
+
+ const effectiveEnd = this.isDrawingStroke ? now : Math.min(now, idleDeadline);
+ const delta = Math.max(0, effectiveEnd - this.lastTickAt);
+ if (delta > 0) {
+ entry.accumulatedMs += delta;
+ entry.sessionMs += delta;
+ }
+
+ if (!this.isDrawingStroke && now >= idleDeadline) {
+ this.lastTickAt = null;
+ this.status = 'idle';
+ this.stopInterval();
+ return true;
+ }
+
+ this.lastTickAt = now;
+ return delta > 0;
+ }
+
+ /**
+ * Initializes (or restores from disk/recovery) a document's tracked time.
+ * Starts idle and will NOT count until the user takes an artwork action.
+ */
+ public initDocument(docId: string, initialWorkTimeMs: number = 0): void {
+ const safeMs = sanitizeWorkTimeMs(initialWorkTimeMs);
+ this.entries.set(docId, {
+ documentId: docId,
+ accumulatedMs: safeMs,
+ sessionMs: 0,
+ });
+ if (this.activeDocumentId === docId) {
+ this.resetLiveSessionCounters();
+ this.status = this.computeNonRecordingStatus();
+ this.stopInterval();
+ }
+ this.emit();
+ }
+
+ /**
+ * Switches active tracking context to `docId`. Flushes any prior active
+ * document immediately so tab switching never leaks time between artworks.
+ */
+ public setActiveDocument(docId: string | null, workspaceVisible?: boolean): void {
+ const nextVisible = workspaceVisible ?? this.workspaceVisible;
+ const isDocChange = this.activeDocumentId !== docId;
+ const isVisChange = this.workspaceVisible !== nextVisible;
+
+ if (!isDocChange && !isVisChange) return;
+
+ if (this.status === 'recording') {
+ this.advanceActiveClock(this.nowFn());
+ }
+
+ this.activeDocumentId = docId;
+ this.workspaceVisible = nextVisible;
+ if (docId) {
+ this.ensureEntry(docId);
+ }
+
+ if (isDocChange || !nextVisible) {
+ this.resetLiveSessionCounters();
+ this.status = this.computeNonRecordingStatus();
+ this.stopInterval();
+ }
+
+ this.emit();
+ }
+
+ /**
+ * Updates whether the workspace canvas is currently active/visible (false on
+ * Home screen or during blocking save/load overlays).
+ */
+ public setWorkspaceVisible(visible: boolean): void {
+ if (this.workspaceVisible === visible) return;
+ if (!visible && this.status === 'recording') {
+ this.advanceActiveClock(this.nowFn());
+ this.isDrawingStroke = false;
+ this.lastTickAt = null;
+ this.lastActivityAt = null;
+ this.stopInterval();
+ }
+ this.workspaceVisible = visible;
+ if (!visible || this.status === 'inactive') {
+ this.status = this.computeNonRecordingStatus();
+ }
+ this.emit();
+ }
+
+ /**
+ * Updates window focus & document visibility state.
+ * Losing focus/visibility immediately flushes and pauses tracking.
+ * Regaining focus stays idle until the user takes a genuine artwork action.
+ */
+ public setWindowFocused(focused: boolean): void {
+ if (this.windowFocused === focused) return;
+ if (!focused) {
+ if (this.status === 'recording') {
+ this.advanceActiveClock(this.nowFn());
+ }
+ this.windowFocused = false;
+ this.isDrawingStroke = false;
+ this.lastTickAt = null;
+ this.lastActivityAt = null;
+ this.status = this.computeNonRecordingStatus();
+ this.stopInterval();
+ this.emit();
+ return;
+ }
+
+ this.windowFocused = true;
+ this.emit();
+ }
+
+ /**
+ * Marks whether a continuous brush/stylus stroke is currently down on canvas.
+ * While a stroke is held down, the idle timeout will not interrupt counting.
+ */
+ public setDrawingActive(active: boolean): void {
+ if (active) {
+ this.isDrawingStroke = true;
+ this.recordArtworkAction();
+ } else if (this.isDrawingStroke) {
+ this.isDrawingStroke = false;
+ this.recordArtworkAction();
+ }
+ }
+
+ /**
+ * Records a genuine artwork action (drawing on canvas, tile/pixel mutation,
+ * layer/mask/filter edit). Starts counting from idle or extends active counting,
+ * and updates the adaptive cadence model.
+ */
+ public recordArtworkAction(targetDocId?: string): void {
+ const docId = targetDocId ?? this.activeDocumentId;
+ if (!docId || docId !== this.activeDocumentId) return;
+ if (!this.workspaceVisible || !this.windowFocused) return;
+
+ this.ensureEntry(docId);
+
+ const now = this.nowFn();
+ const prevStatus = this.status;
+
+ if (this.status === 'recording') {
+ this.advanceActiveClock(now);
+ }
+
+ if (this.lastArtworkActionAt !== null) {
+ this.updateAdaptiveCadence(now - this.lastArtworkActionAt);
+ }
+
+ this.lastArtworkActionAt = now;
+ this.lastActivityAt = now;
+ this.lastTickAt = now;
+ this.status = 'recording';
+ this.startInterval();
+
+ if (prevStatus !== 'recording') {
+ this.emit();
+ }
+ }
+
+ /**
+ * Alias for `recordArtworkAction` for callers recording direct drawing actions.
+ */
+ public recordActivity(targetDocId?: string): void {
+ this.recordArtworkAction(targetDocId);
+ }
+
+ /**
+ * Records a supporting workspace interaction (canvas zoom/pan, keyboard shortcut,
+ * picking a color/brush/tool).
+ *
+ * Safety rule: NEVER starts counting when the tracker is idle, and only extends
+ * an active session up to `maxNonEditSustainMs` since the last genuine artwork edit.
+ */
+ public recordSupportingActivity(targetDocId?: string): void {
+ const docId = targetDocId ?? this.activeDocumentId;
+ if (!docId || docId !== this.activeDocumentId) return;
+ if (!this.workspaceVisible || !this.windowFocused) return;
+ if (this.status !== 'recording' || this.lastArtworkActionAt === null) {
+ return;
+ }
+
+ const now = this.nowFn();
+ this.advanceActiveClock(now);
+
+ // If advanceActiveClock timed out to idle or hard sustain cap passed, do not wake
+ if (this.status !== 'recording') {
+ return;
+ }
+ if (now - this.lastArtworkActionAt >= this.maxNonEditSustainMs) {
+ this.lastTickAt = null;
+ this.status = 'idle';
+ this.stopInterval();
+ this.emit();
+ return;
+ }
+
+ this.lastActivityAt = now;
+ }
+
+ /**
+ * Periodic heartbeat (or manual step in tests) that commits active elapsed time
+ * and transitions to `idle` once inactivity exceeds the adaptive threshold.
+ */
+ public tick(): void {
+ if (this.status !== 'recording') {
+ this.stopInterval();
+ return;
+ }
+ const changed = this.advanceActiveClock(this.nowFn());
+ if (changed) {
+ this.emit();
+ }
+ }
+
+ /**
+ * Immediately flushes any in-flight active milliseconds so reads (e.g. before
+ * saving to `.ink` / `.psd` or crash-recovery checkpointing) are exact.
+ */
+ public flush(docId?: string | null): void {
+ if (docId && docId !== this.activeDocumentId) return;
+ if (this.status !== 'recording') return;
+ const changed = this.advanceActiveClock(this.nowFn());
+ if (changed) {
+ this.emit();
+ }
+ }
+
+ /**
+ * Returns exact accumulated work time in milliseconds for a document.
+ */
+ public getWorkTimeMs(docId: string | null | undefined): number {
+ if (!docId) return 0;
+ if (docId === this.activeDocumentId && this.status === 'recording') {
+ this.advanceActiveClock(this.nowFn());
+ }
+ const entry = this.entries.get(docId);
+ return entry ? Math.round(entry.accumulatedMs) : 0;
+ }
+
+ public getSessionTimeMs(docId: string | null | undefined): number {
+ if (!docId) return 0;
+ if (docId === this.activeDocumentId && this.status === 'recording') {
+ this.advanceActiveClock(this.nowFn());
+ }
+ const entry = this.entries.get(docId);
+ return entry ? Math.round(entry.sessionMs) : 0;
+ }
+
+ public getEffectiveIdleTimeoutMs(): number {
+ return this.effectiveIdleTimeoutMs;
+ }
+
+ /**
+ * Removes tracking state when a document tab is closed.
+ */
+ public removeDocument(docId: string): void {
+ if (this.activeDocumentId === docId) {
+ this.activeDocumentId = null;
+ this.resetLiveSessionCounters();
+ this.status = 'inactive';
+ this.stopInterval();
+ }
+ this.entries.delete(docId);
+ this.emit();
+ }
+
+ /**
+ * Resets all tracker state (intended for tests and clean teardown).
+ */
+ public resetAll(): void {
+ this.stopInterval();
+ this.entries.clear();
+ this.activeDocumentId = null;
+ this.workspaceVisible = false;
+ this.windowFocused = true;
+ this.resetLiveSessionCounters();
+ this.status = 'inactive';
+ this.emit();
+ }
+
+ /**
+ * Returns a referentially-stable snapshot for React's `useSyncExternalStore`.
+ */
+ public getSnapshot(docId?: string | null): ArtworkTimeSnapshot {
+ const targetId = docId !== undefined ? docId : this.activeDocumentId;
+ const key = `${this.version}:${targetId ?? ''}`;
+ if (this.cachedSnapshot && this.cachedSnapshotKey === key) {
+ return this.cachedSnapshot;
+ }
+
+ const entry = targetId ? this.entries.get(targetId) : undefined;
+ const isActiveTarget = Boolean(targetId && targetId === this.activeDocumentId);
+ const status: WorkTimeStatus = !targetId
+ ? 'inactive'
+ : isActiveTarget
+ ? this.status
+ : 'idle';
+
+ const snap: ArtworkTimeSnapshot = {
+ documentId: targetId ?? null,
+ accumulatedMs: entry ? Math.round(entry.accumulatedMs) : 0,
+ sessionMs: entry ? Math.round(entry.sessionMs) : 0,
+ status,
+ effectiveIdleTimeoutMs: this.effectiveIdleTimeoutMs,
+ windowFocused: this.windowFocused,
+ };
+
+ this.cachedSnapshotKey = key;
+ this.cachedSnapshot = snap;
+ return snap;
+ }
+
+ public subscribe = (listener: () => void): (() => void) => {
+ this.listeners.add(listener);
+ return () => {
+ this.listeners.delete(listener);
+ };
+ };
+}
+
+export const artworkTimeTracker = new ArtworkTimeTracker();
diff --git a/src/utils/compositor.ts b/src/utils/compositor.ts
index 40897f6..6f7989c 100644
--- a/src/utils/compositor.ts
+++ b/src/utils/compositor.ts
@@ -9,6 +9,17 @@
*/
import { CanvasDimensions, LayerItem } from '../types/editor';
+import type {
+ CanvasFilteringQuality,
+ GpuPowerPreference,
+ GpuTexturePoolPreset,
+ RenderBackend,
+} from '../types/settings';
+import {
+ CompositorTelemetry,
+ GPU_TEXTURE_POOL_CONFIGS,
+ performanceManager,
+} from './performanceManager';
import { SparseTileGrid, TILE_SIZE, globalTileGrid } from './tileEngine';
import { calculateVisibleDocumentBounds } from './compositor/bounds';
import { disposeFboSurface, disposePingPongTarget } from './compositor/fboManager';
@@ -85,10 +96,26 @@ export {
export { calculateVisibleDocumentBounds } from './compositor/bounds';
+export interface ViewportCompositorInitOptions {
+ preserveDrawingBuffer?: boolean;
+ renderBackend?: RenderBackend;
+ powerPreference?: GpuPowerPreference;
+ gpuTexturePoolPreset?: GpuTexturePoolPreset;
+ filteringQuality?: CanvasFilteringQuality;
+}
+
function createInitialCompositorState(
canvas: HTMLCanvasElement,
- preserveDrawingBuffer: boolean
+ options?: ViewportCompositorInitOptions
): CompositorState {
+ const perf = performanceManager.getConfig();
+ const renderBackend: RenderBackend = options?.renderBackend ?? perf.renderBackend;
+ const powerPreference: GpuPowerPreference = options?.powerPreference ?? perf.gpuPowerPreference;
+ const poolPreset: GpuTexturePoolPreset = options?.gpuTexturePoolPreset ?? perf.gpuTexturePoolPreset;
+ const poolSpec = GPU_TEXTURE_POOL_CONFIGS[poolPreset] ?? GPU_TEXTURE_POOL_CONFIGS.high;
+ const filteringQuality: CanvasFilteringQuality =
+ options?.filteringQuality ?? perf.canvasFilteringQuality;
+
return {
canvas,
gl: null,
@@ -108,7 +135,9 @@ function createInitialCompositorState(
aInstDataLoc: -1,
instancedVao: null,
instanceBuffer: null,
- instanceFloatScratch: new Float32Array(DEFAULT_ARRAY_POOL_LAYERS * 3),
+ instanceFloatScratch: new Float32Array(
+ Math.max(DEFAULT_ARRAY_POOL_LAYERS, poolSpec.arrayLayers) * 3
+ ),
tileArrayTexture: null,
arrayPoolCapacity: 0,
arrayPoolFilterTier: -1,
@@ -118,7 +147,7 @@ function createInitialCompositorState(
arrayAccessCounter: 0,
arrayBatchCounter: 0,
uploadPremulScratch: new Uint8Array(TILE_SIZE * TILE_SIZE * 4),
- preserveDrawingBuffer,
+ preserveDrawingBuffer: Boolean(options?.preserveDrawingBuffer),
viewportDraftProgram: null,
viewportDraftLocs: null,
uViewportDraftTileTexLoc: null,
@@ -217,7 +246,17 @@ function createInitialCompositorState(
texturePool: [],
activePoolByKey: new Map(),
fallbackTileCanvas: null,
+ fallbackTileImageData: null,
+ fallbackIsoCanvas: null,
lastRenderedGrid: null,
+ renderBackend,
+ powerPreference,
+ requestedArrayPoolLayers: poolSpec.arrayLayers,
+ maxTexturePoolSize: poolSpec.maxTexture2D,
+ filteringQuality,
+ activeRendererName:
+ renderBackend === 'canvas2d' ? 'Canvas 2D (CPU Software)' : 'WebGL2 GPU',
+ layerVisScratch: new Map(),
};
}
@@ -227,8 +266,8 @@ function createInitialCompositorState(
export class ViewportCompositor {
private state: CompositorState;
- constructor(canvas: HTMLCanvasElement, options?: { preserveDrawingBuffer?: boolean }) {
- this.state = createInitialCompositorState(canvas, Boolean(options?.preserveDrawingBuffer));
+ constructor(canvas: HTMLCanvasElement, options?: ViewportCompositorInitOptions) {
+ this.state = createInitialCompositorState(canvas, options);
if (typeof canvas.addEventListener === 'function') {
this.state.onContextLostHandler = (e: Event) => {
e.preventDefault();
@@ -249,6 +288,62 @@ export class ViewportCompositor {
return !this.state.contextLost && this.state.gl !== null && this.state.program !== null;
}
+ public getBackend(): 'webgl2' | 'canvas2d' {
+ return this.isReady() ? 'webgl2' : 'canvas2d';
+ }
+
+ public getRendererName(): string {
+ return this.state.activeRendererName;
+ }
+
+ public setFilteringQuality(quality: CanvasFilteringQuality): void {
+ if (this.state.filteringQuality === quality) return;
+ this.state.filteringQuality = quality;
+ this.state.arrayPoolFilterTier = -1;
+ for (const slot of this.state.texturePool) {
+ slot.filterTier = -1;
+ }
+ }
+
+ public getTelemetry(): CompositorTelemetry {
+ const backend = this.getBackend();
+ const arrayUsed = this.state.arrayPoolByKey.size;
+ const tex2DUsed = this.state.texturePool.length;
+ const tileBytes = TILE_SIZE * TILE_SIZE * 4;
+ // Array texture reserves full capacity slices upfront when allocated on GPU
+ const arrayBytes = this.state.tileArrayTexture
+ ? this.state.arrayPoolCapacity * tileBytes
+ : 0;
+ const tex2DBytes = tex2DUsed * tileBytes;
+ const fboPixels =
+ (this.state.scenePingPong ? 2 : 0) +
+ (this.state.belowActiveCacheFbo ? 1 : 0) +
+ (this.state.aboveActiveCacheFbo ? 1 : 0);
+ const fboBytes = fboPixels * this.state.canvas.width * this.state.canvas.height * 4;
+ const estimatedVramMb =
+ backend === 'webgl2'
+ ? Math.round(((arrayBytes + tex2DBytes + fboBytes) / (1024 * 1024)) * 10) / 10
+ : 0;
+
+ return {
+ backend,
+ rendererName: this.state.activeRendererName,
+ arrayPoolUsed: arrayUsed,
+ arrayPoolCapacity: this.state.arrayPoolCapacity,
+ texture2DPoolUsed: tex2DUsed,
+ estimatedVramMb,
+ stackCacheHits: this.state.stackCacheStats.cacheHits,
+ stackCacheRebuilds:
+ this.state.stackCacheStats.belowRebuilds + this.state.stackCacheStats.aboveRebuilds,
+ };
+ }
+
+ public flushGpuCaches(): void {
+ invalidateTileTextures(this.state);
+ invalidateMaskTexture(this.state);
+ this.state.stackCache.invalidateAll();
+ }
+
public getCanvas(): HTMLCanvasElement {
return this.state.canvas;
}
@@ -445,8 +540,17 @@ export class ViewportCompositor {
}
s.stackCache.invalidateAll();
if (s.fallbackTileCanvas) {
+ s.fallbackTileCanvas.width = 0;
+ s.fallbackTileCanvas.height = 0;
s.fallbackTileCanvas = null;
}
+ s.fallbackTileImageData = null;
+ if (s.fallbackIsoCanvas) {
+ s.fallbackIsoCanvas.width = 0;
+ s.fallbackIsoCanvas.height = 0;
+ s.fallbackIsoCanvas = null;
+ }
+ s.layerVisScratch.clear();
if (typeof s.canvas.removeEventListener === 'function') {
if (s.onContextLostHandler) {
s.canvas.removeEventListener('webglcontextlost', s.onContextLostHandler);
diff --git a/src/utils/compositor/fallback2d.ts b/src/utils/compositor/fallback2d.ts
index 34b02be..6dfa3b9 100644
--- a/src/utils/compositor/fallback2d.ts
+++ b/src/utils/compositor/fallback2d.ts
@@ -1,17 +1,85 @@
import { CanvasDimensions, LayerItem, isFolderLikeLayer } from '../../types/editor';
import { getCanvasCompositeOperation } from '../canvasUtils';
import { applyMultiFrameClip, renderFrameBorder } from '../frameEngine';
-import { SparseTileGrid, TILE_SIZE } from '../tileEngine';
+import { SparseTileGrid, TILE_SIZE, TileBuffer } from '../tileEngine';
import { applyAdjustment } from '../tonalEngine';
+import { calculateVisibleDocumentBounds } from './bounds';
import { buildLayerTree, groupTreeNodesForCompositing } from './layerTree';
import { hasActiveLayerStyles } from './shaders/effectShaders';
import {
CompositorOptions,
CompositorState,
+ DocumentBounds,
LayerTreeNode,
ViewportTransform,
} from './types';
+function collectVisible2DTiles(
+ grid: SparseTileGrid,
+ layerId: string,
+ zoom: number,
+ frustum?: DocumentBounds | null
+): { tiles: TileBuffer[]; lodTileDocSize: number } {
+ const targetLod =
+ !frustum
+ ? 0
+ : zoom <= 0.125
+ ? 3
+ : zoom <= 0.25
+ ? 2
+ : zoom <= 0.5
+ ? 1
+ : 0;
+ const lodScale = 1 << targetLod;
+ const lodTileDocSize = TILE_SIZE * lodScale;
+
+ if (!frustum) {
+ return { tiles: grid.getLayerTiles(layerId, 0), lodTileDocSize: TILE_SIZE };
+ }
+
+ const hasLayerTiles =
+ typeof grid.hasLayerTiles === 'function' ? grid.hasLayerTiles(layerId) : true;
+ if (!hasLayerTiles) {
+ return { tiles: [], lodTileDocSize };
+ }
+
+ const hasOccCheck = typeof grid.hasPopulatedLodTile === 'function';
+ const startTileX = Math.floor(frustum.minX / lodTileDocSize);
+ const endTileX = Math.floor(frustum.maxX / lodTileDocSize);
+ const startTileY = Math.floor(frustum.minY / lodTileDocSize);
+ const endTileY = Math.floor(frustum.maxY / lodTileDocSize);
+
+ const visibleTiles: TileBuffer[] = [];
+ for (let ty = startTileY; ty <= endTileY; ty++) {
+ for (let tx = startTileX; tx <= endTileX; tx++) {
+ if (targetLod > 0 && hasOccCheck && !grid.hasPopulatedLodTile(layerId, tx, ty, targetLod)) {
+ continue;
+ }
+ let tile = grid.getTile(layerId, tx, ty, targetLod);
+ if (
+ targetLod > 0 &&
+ (!tile || tile.data === null || grid.isLodTileDirty(layerId, tx, ty, targetLod))
+ ) {
+ tile = grid.generateLodTile(layerId, tx, ty, targetLod);
+ }
+ if (tile) {
+ visibleTiles.push(tile);
+ }
+ }
+ }
+ return { tiles: visibleTiles, lodTileDocSize };
+}
+
+function getReusableTileImageData(
+ state: CompositorState,
+ tileCtx: CanvasRenderingContext2D
+): ImageData {
+ if (!state.fallbackTileImageData) {
+ state.fallbackTileImageData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
+ }
+ return state.fallbackTileImageData;
+}
+
/**
* Helper to render a single layer onto a 2D canvas context.
*/
@@ -21,25 +89,32 @@ export function render2DSingleLayer(
layer: LayerItem,
grid: SparseTileGrid,
tileCtx: CanvasRenderingContext2D | null | undefined,
- opacityMultiplier: number = 1.0
+ opacityMultiplier: number = 1.0,
+ frustum?: DocumentBounds | null
): void {
targetCtx.save();
targetCtx.globalAlpha = Math.max(0, Math.min(1, layer.opacity * opacityMultiplier));
targetCtx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
- const tiles = grid.getLayerTiles(layer.id);
+ const { tiles, lodTileDocSize } = collectVisible2DTiles(
+ grid,
+ layer.id,
+ state.currentZoom,
+ frustum
+ );
const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
const maskCtx = hasMask && layer.maskCanvas ? layer.maskCanvas.getContext('2d', { willReadFrequently: true }) : null;
- // Helper to render tiles into target context
+ // Helper to render tiles into target context (reuses single ImageData buffer — zero per-tile GC)
const drawTiles = (ctx: CanvasRenderingContext2D) => {
+ if (!tileCtx || !state.fallbackTileCanvas) return;
+ const imgData = getReusableTileImageData(state, tileCtx);
+ const scaleRatio = lodTileDocSize / TILE_SIZE;
for (const tile of tiles) {
- if (!tileCtx || !state.fallbackTileCanvas) continue;
const rgba = grid.getTileAsRGBA(tile);
- const imgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
imgData.data.set(rgba);
- if (hasMask && maskCtx) {
+ if (hasMask && maskCtx && scaleRatio === 1) {
const maskImgData = maskCtx.getImageData(tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE, TILE_SIZE, TILE_SIZE);
const md = maskImgData.data;
const d = imgData.data;
@@ -51,7 +126,17 @@ export function render2DSingleLayer(
}
tileCtx.putImageData(imgData, 0, 0);
- ctx.drawImage(state.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
+ if (scaleRatio === 1) {
+ ctx.drawImage(state.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
+ } else {
+ ctx.drawImage(
+ state.fallbackTileCanvas,
+ tile.tileX * lodTileDocSize,
+ tile.tileY * lodTileDocSize,
+ lodTileDocSize,
+ lodTileDocSize
+ );
+ }
}
};
@@ -102,11 +187,20 @@ export function render2DSingleLayer(
typeof document !== 'undefined' &&
targetCtx.canvas
) {
- const iso = document.createElement('canvas');
- iso.width = targetCtx.canvas.width;
- iso.height = targetCtx.canvas.height;
+ if (!state.fallbackIsoCanvas) {
+ state.fallbackIsoCanvas = document.createElement('canvas');
+ }
+ const iso = state.fallbackIsoCanvas;
+ if (iso.width !== targetCtx.canvas.width || iso.height !== targetCtx.canvas.height) {
+ iso.width = targetCtx.canvas.width;
+ iso.height = targetCtx.canvas.height;
+ }
const isoCtx = iso.getContext('2d');
if (isoCtx) {
+ if (typeof isoCtx.setTransform === 'function') {
+ isoCtx.setTransform(1, 0, 0, 1, 0, 0);
+ }
+ isoCtx.clearRect(0, 0, iso.width, iso.height);
if (typeof targetCtx.getTransform === 'function' && typeof isoCtx.setTransform === 'function') {
isoCtx.setTransform(targetCtx.getTransform());
}
@@ -179,7 +273,8 @@ export function render2DNodeList(
dimensions: CanvasDimensions,
grid: SparseTileGrid,
tileCtx: CanvasRenderingContext2D | null | undefined,
- opacityMultiplier: number = 1.0
+ opacityMultiplier: number = 1.0,
+ frustum?: DocumentBounds | null
): void {
const renderOrder = nodes.slice().reverse();
const groups = groupTreeNodesForCompositing(renderOrder);
@@ -295,7 +390,7 @@ export function render2DNodeList(
);
if (activeClipped.length === 0) {
- render2DSingleLayer(state, targetCtx, baseLayer, grid, tileCtx, opacityMultiplier);
+ render2DSingleLayer(state, targetCtx, baseLayer, grid, tileCtx, opacityMultiplier, frustum);
} else {
let groupCanvas: HTMLCanvasElement | null = null;
if (typeof document !== 'undefined') {
@@ -305,11 +400,11 @@ export function render2DNodeList(
}
const gCtx = groupCanvas?.getContext('2d');
if (!gCtx || !groupCanvas) {
- render2DSingleLayer(state, targetCtx, baseLayer, grid, tileCtx, opacityMultiplier);
+ render2DSingleLayer(state, targetCtx, baseLayer, grid, tileCtx, opacityMultiplier, frustum);
continue;
}
- render2DSingleLayer(state, gCtx, baseLayer, grid, tileCtx, 1.0);
+ render2DSingleLayer(state, gCtx, baseLayer, grid, tileCtx, 1.0, null);
for (const clippedNode of activeClipped) {
const clipped = clippedNode.layer;
@@ -318,13 +413,14 @@ export function render2DNodeList(
gCtx.globalCompositeOperation = 'source-atop';
const tiles = grid.getLayerTiles(clipped.id);
- for (const tile of tiles) {
- if (!tileCtx || !state.fallbackTileCanvas) continue;
- const rgba = grid.getTileAsRGBA(tile);
- const imgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
- imgData.data.set(rgba);
- tileCtx.putImageData(imgData, 0, 0);
- gCtx.drawImage(state.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
+ if (tileCtx && state.fallbackTileCanvas) {
+ const imgData = getReusableTileImageData(state, tileCtx);
+ for (const tile of tiles) {
+ const rgba = grid.getTileAsRGBA(tile);
+ imgData.data.set(rgba);
+ tileCtx.putImageData(imgData, 0, 0);
+ gCtx.drawImage(state.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
+ }
}
gCtx.restore();
}
@@ -339,7 +435,8 @@ export function render2DNodeList(
}
/**
- * 2D Canvas Fallback Pass: Blits tiles when WebGL2 context is unavailable.
+ * 2D Canvas Fallback Pass: Blits visible tiles using frustum culling and adaptive LOD
+ * when WebGL2 is unavailable or Canvas 2D software mode is selected.
*/
export function render2DFallback(
state: CompositorState,
@@ -356,9 +453,34 @@ export function render2DFallback(
const viewportH = state.canvas.height;
const dpr = _options.devicePixelRatio ?? (typeof window !== 'undefined' ? window.devicePixelRatio : 1) ?? 1;
+ // Frustum Culling & Memory Manager Sync (keeps RAM eviction accurate even in CPU 2D mode)
+ const frustum = calculateVisibleDocumentBounds(
+ viewportW / Math.max(0.01, dpr),
+ viewportH / Math.max(0.01, dpr),
+ transform,
+ dimensions.width,
+ dimensions.height
+ );
+ const activeLayerId = _options.activeLayerId ?? _options.activeDraftLayerId ?? null;
+ const layerVis = state.layerVisScratch;
+ layerVis.clear();
+ for (let i = 0; i < layers.length; i++) {
+ layerVis.set(layers[i].id, layers[i].visible);
+ }
+ grid.getMemoryManager()?.updateViewport(frustum, activeLayerId, layerVis);
+
ctx.save();
ctx.clearRect(0, 0, viewportW, viewportH);
+ // Respect texture filtering quality preference in 2D mode
+ const shouldSmooth =
+ state.filteringQuality === 'smooth'
+ ? true
+ : state.filteringQuality === 'pixelated'
+ ? false
+ : transform.zoom < 2.0;
+ ctx.imageSmoothingEnabled = shouldSmooth;
+
ctx.scale(dpr, dpr);
ctx.translate(transform.pan.x, transform.pan.y);
ctx.rotate((transform.rotation * Math.PI) / 180);
@@ -368,12 +490,14 @@ export function render2DFallback(
);
ctx.translate(-dimensions.width / 2, -dimensions.height / 2);
- if (_options.showCheckerboard) {
- ctx.fillStyle = '#1e1e1e';
- } else {
- ctx.fillStyle = '#ffffff';
+ if (!_options.transparentBackground) {
+ if (_options.showCheckerboard) {
+ ctx.fillStyle = '#1e1e1e';
+ } else {
+ ctx.fillStyle = '#ffffff';
+ }
+ ctx.fillRect(0, 0, dimensions.width, dimensions.height);
}
- ctx.fillRect(0, 0, dimensions.width, dimensions.height);
if (!state.fallbackTileCanvas && typeof document !== 'undefined') {
state.fallbackTileCanvas = document.createElement('canvas');
@@ -383,7 +507,7 @@ export function render2DFallback(
const tileCtx = state.fallbackTileCanvas?.getContext('2d', { willReadFrequently: true });
const tree = buildLayerTree(layers);
- render2DNodeList(state, ctx, tree, dimensions, grid, tileCtx, 1.0);
+ render2DNodeList(state, ctx, tree, dimensions, grid, tileCtx, 1.0, frustum);
ctx.restore();
}
diff --git a/src/utils/compositor/glInit.ts b/src/utils/compositor/glInit.ts
index b856004..c331876 100644
--- a/src/utils/compositor/glInit.ts
+++ b/src/utils/compositor/glInit.ts
@@ -122,9 +122,10 @@ export function initTileArrayPool(state: CompositorState, gl: WebGL2RenderingCon
return;
}
+ const desiredLayers = state.requestedArrayPoolLayers || DEFAULT_ARRAY_POOL_LAYERS;
const maxLayersParam =
- Number(gl.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS)) || DEFAULT_ARRAY_POOL_LAYERS;
- const capacity = Math.max(1, Math.min(DEFAULT_ARRAY_POOL_LAYERS, maxLayersParam));
+ Number(gl.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS)) || desiredLayers;
+ const capacity = Math.max(1, Math.min(desiredLayers, maxLayersParam));
const arrTex = gl.createTexture();
const instBuf = gl.createBuffer();
@@ -247,6 +248,10 @@ export function resetGLStateOnContextLost(state: CompositorState): void {
}
export function initGL(state: CompositorState): boolean {
+ if (state.renderBackend === 'canvas2d') {
+ state.activeRendererName = 'Canvas 2D (CPU Software)';
+ return false;
+ }
if (state.gl && state.program) return true;
try {
@@ -257,12 +262,28 @@ export function initGL(state: CompositorState): boolean {
depth: false,
stencil: true,
preserveDrawingBuffer: state.preserveDrawingBuffer,
- powerPreference: 'high-performance',
+ powerPreference: state.powerPreference || 'high-performance',
});
- if (!gl) return false;
+ if (!gl) {
+ state.activeRendererName = 'Canvas 2D Fallback';
+ return false;
+ }
state.gl = gl;
+ // Detect active GPU renderer string once on context creation
+ let rendererName = 'WebGL2 GPU';
+ if (typeof gl.getExtension === 'function') {
+ const debugExt = gl.getExtension('WEBGL_debug_renderer_info');
+ if (debugExt) {
+ const rawRenderer = gl.getParameter(debugExt.UNMASKED_RENDERER_WEBGL);
+ if (typeof rawRenderer === 'string' && rawRenderer.trim()) {
+ rendererName = rawRenderer.trim();
+ }
+ }
+ }
+ state.activeRendererName = rendererName;
+
// Compile vertex shader
const vs = compileShader(gl, gl.VERTEX_SHADER, COMPOSITOR_VERTEX_SHADER);
if (!vs) return false;
diff --git a/src/utils/compositor/renderFrame.ts b/src/utils/compositor/renderFrame.ts
index 2b2a9b7..3e7aa17 100644
--- a/src/utils/compositor/renderFrame.ts
+++ b/src/utils/compositor/renderFrame.ts
@@ -6,6 +6,7 @@ import { render2DFallback } from './fallback2d';
import {
copyFboSurface,
createFboSurface,
+ disposeFboSurface,
ensureFboSurfaceSize,
ensurePingPongTarget,
} from './fboManager';
@@ -74,11 +75,12 @@ export function renderFrame(
dimensions.height
);
- // Dynamic Frustum Culling & Memory Budget Sync
+ // Dynamic Frustum Culling & Memory Budget Sync (reuse persistent Map — zero per-frame allocation)
const activeLayerId = _options.activeLayerId ?? _options.activeDraftLayerId ?? null;
- const layerVis = new Map<string, boolean>();
- for (const l of layers) {
- layerVis.set(l.id, l.visible);
+ const layerVis = state.layerVisScratch;
+ layerVis.clear();
+ for (let i = 0; i < layers.length; i++) {
+ layerVis.set(layers[i].id, layers[i].visible);
}
grid.getMemoryManager()?.updateViewport(frustum, activeLayerId, layerVis);
@@ -89,7 +91,18 @@ export function renderFrame(
const bypassStackCache = Boolean(_options.bypassStackCache);
let belowCacheReady = false;
let aboveCacheReady = false;
- if (scenePP && !bypassStackCache) {
+ if (bypassStackCache) {
+ if (state.belowActiveCacheFbo) {
+ disposeFboSurface(gl, state.belowActiveCacheFbo);
+ state.belowActiveCacheFbo = null;
+ state.stackCache.invalidateAll();
+ }
+ if (state.aboveActiveCacheFbo) {
+ disposeFboSurface(gl, state.aboveActiveCacheFbo);
+ state.aboveActiveCacheFbo = null;
+ state.stackCache.invalidateAll();
+ }
+ } else if (scenePP) {
if (!state.belowActiveCacheFbo) {
state.belowActiveCacheFbo = createFboSurface(gl, false);
}
@@ -395,7 +408,8 @@ export function renderFrame(
}
// Clean up stale textures if fallback pool exceeded limit
- if (state.texturePool.length > MAX_TEXTURE_POOL_SIZE) {
+ const maxPool = state.maxTexturePoolSize || MAX_TEXTURE_POOL_SIZE;
+ if (state.texturePool.length > maxPool) {
evictStaleTextures(state);
}
}
diff --git a/src/utils/compositor/tileDraw.ts b/src/utils/compositor/tileDraw.ts
index 35d4d77..eff67c1 100644
--- a/src/utils/compositor/tileDraw.ts
+++ b/src/utils/compositor/tileDraw.ts
@@ -85,7 +85,16 @@ export function drawVisibleTiles(
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D_ARRAY, state.tileArrayTexture);
- const desiredTier = state.currentZoom < 0.99 ? 0 : state.currentZoom < 2.0 ? 1 : 2;
+ const desiredTier =
+ state.filteringQuality === 'smooth'
+ ? 1
+ : state.filteringQuality === 'pixelated'
+ ? 2
+ : state.currentZoom < 0.99
+ ? 0
+ : state.currentZoom < 2.0
+ ? 1
+ : 2;
if (state.arrayPoolFilterTier !== desiredTier) {
const filter = desiredTier <= 1 ? gl.LINEAR : gl.NEAREST;
gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, filter);
@@ -251,7 +260,15 @@ export function renderActiveDraftForLayer(
needsMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR
);
}
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, state.currentZoom >= 2.0 ? gl.NEAREST : gl.LINEAR);
+ const draftMagFilter =
+ state.filteringQuality === 'smooth'
+ ? gl.LINEAR
+ : state.filteringQuality === 'pixelated'
+ ? gl.NEAREST
+ : state.currentZoom >= 2.0
+ ? gl.NEAREST
+ : gl.LINEAR;
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, draftMagFilter);
let effectiveDraftLayer: LayerItem =
state.currentOptions?.activeDraftMonochrome && layer.expressionColor !== 'monochrome'
diff --git a/src/utils/compositor/tileTexturePool.ts b/src/utils/compositor/tileTexturePool.ts
index b6c28ff..6978704 100644
--- a/src/utils/compositor/tileTexturePool.ts
+++ b/src/utils/compositor/tileTexturePool.ts
@@ -144,7 +144,8 @@ export function getTileTexture(
state.activePoolByKey.delete(key);
state.activePoolByKey.set(key, slot);
} else {
- if (state.texturePool.length < MAX_TEXTURE_POOL_SIZE) {
+ const maxPoolSize = state.maxTexturePoolSize || MAX_TEXTURE_POOL_SIZE;
+ if (state.texturePool.length < maxPoolSize) {
const tex = gl.createTexture();
if (!tex) return null;
slot = {
@@ -177,7 +178,16 @@ export function getTileTexture(
}
slot.lastUsed = accessTick;
- const desiredTier = state.currentZoom < 0.99 ? 0 : state.currentZoom < 2.0 ? 1 : 2;
+ const desiredTier =
+ state.filteringQuality === 'smooth'
+ ? 1
+ : state.filteringQuality === 'pixelated'
+ ? 2
+ : state.currentZoom < 0.99
+ ? 0
+ : state.currentZoom < 2.0
+ ? 1
+ : 2;
// Re-upload if version changed (direct GPU unpack premultiplication, zero JS pixel loop)
if (slot.version !== tile.version) {
@@ -289,9 +299,10 @@ export function getMaskTexture(state: CompositorState, layer: LayerItem): WebGLT
* Evict least recently used tile textures when texture pool exceeds threshold.
*/
export function evictStaleTextures(state: CompositorState): void {
- if (!state.gl || state.texturePool.length <= MAX_TEXTURE_POOL_SIZE) return;
+ const maxPoolSize = state.maxTexturePoolSize || MAX_TEXTURE_POOL_SIZE;
+ if (!state.gl || state.texturePool.length <= maxPoolSize) return;
state.texturePool.sort((a, b) => a.lastUsed - b.lastUsed);
- while (state.texturePool.length > MAX_TEXTURE_POOL_SIZE) {
+ while (state.texturePool.length > maxPoolSize) {
const slot = state.texturePool.shift();
if (slot) {
if (slot.currentKey) state.activePoolByKey.delete(slot.currentKey);
diff --git a/src/utils/compositor/types.ts b/src/utils/compositor/types.ts
index 25420d5..bc908b3 100644
--- a/src/utils/compositor/types.ts
+++ b/src/utils/compositor/types.ts
@@ -5,6 +5,11 @@ import {
CanvasColorMode,
SoftProofSettings,
} from '../../types/editor';
+import type {
+ CanvasFilteringQuality,
+ GpuPowerPreference,
+ RenderBackend,
+} from '../../types/settings';
import { SparseTileGrid } from '../tileEngine';
export const DEFAULT_ARRAY_POOL_LAYERS = 512;
@@ -394,5 +399,16 @@ export interface CompositorState {
texturePool: Texture2DPoolSlot[];
activePoolByKey: Map<string, Texture2DPoolSlot>;
fallbackTileCanvas: HTMLCanvasElement | null;
+ fallbackTileImageData: ImageData | null;
+ fallbackIsoCanvas: HTMLCanvasElement | null;
lastRenderedGrid: SparseTileGrid | null;
+
+ // Performance & Renderer Configuration
+ renderBackend: RenderBackend;
+ powerPreference: GpuPowerPreference;
+ requestedArrayPoolLayers: number;
+ maxTexturePoolSize: number;
+ filteringQuality: CanvasFilteringQuality;
+ activeRendererName: string;
+ layerVisScratch: Map<string, boolean>;
}
diff --git a/src/utils/documentStore.ts b/src/utils/documentStore.ts
index 0bfad0f..904bdf2 100644
--- a/src/utils/documentStore.ts
+++ b/src/utils/documentStore.ts
@@ -209,6 +209,68 @@ export class DocumentStore {
void this.enforceSharedUndoBudget();
}
+ public setOffloadInactiveUndoOnSwitch(enabled: boolean): void {
+ this.offloadInactiveUndoOnSwitch = Boolean(enabled);
+ }
+
+ public getOffloadInactiveUndoOnSwitch(): boolean {
+ return this.offloadInactiveUndoOnSwitch;
+ }
+
+ public getUndoMemoryStats(): {
+ ramSteps: number;
+ diskSteps: number;
+ compressedRamBytes: number;
+ } {
+ let ramSteps = 0;
+ let diskSteps = 0;
+ let compressedRamBytes = 0;
+ for (const session of this.sessions.values()) {
+ if (session.isDisposed()) continue;
+ ramSteps += session.undoCache.getRamStepCount();
+ diskSteps += session.undoCache.getDiskCachedCount();
+ compressedRamBytes += session.undoCache.getCompressedRamBytes();
+ }
+ return { ramSteps, diskSteps, compressedRamBytes };
+ }
+
+ public getActiveSessionIds(): string[] {
+ return this.getAllSessions().map((s) => s.documentId);
+ }
+
+ /**
+ * Reclaims RAM immediately by dropping cached mipmap LODs across all sessions
+ * and offloading inactive document tiles to scratch disk.
+ */
+ public async purgeTileMemory(): Promise<number> {
+ let freed = 0;
+ for (const session of this.getAllSessions()) {
+ const mm = session.tileGrid.getMemoryManager();
+ if (!mm) continue;
+ if (!session.isActive) {
+ freed += await mm.evictAllToDisk();
+ } else {
+ // Drop regenerable LOD > 0 mipmaps & evict hidden/off-frustum tiles down to 50% of active bytes
+ const activeBytes = mm.getActiveMemoryBytes();
+ if (activeBytes > 0) {
+ freed += await mm.evictBytesToDisk(Math.floor(activeBytes * 0.5));
+ }
+ }
+ }
+ return freed;
+ }
+
+ /**
+ * Offloads in-RAM undo tile deltas to scratch disk / compressed storage across all sessions.
+ */
+ public async purgeUndoMemory(): Promise<number> {
+ let offloaded = 0;
+ for (const session of this.getAllSessions()) {
+ offloaded += await session.undoCache.offloadAllToDisk(session.history);
+ }
+ return offloaded;
+ }
+
public getTotalActiveTileBytes(): number {
let total = 0;
for (const session of this.sessions.values()) {
diff --git a/src/utils/imageLoader.ts b/src/utils/imageLoader.ts
index ccfd38b..8ab14c5 100644
--- a/src/utils/imageLoader.ts
+++ b/src/utils/imageLoader.ts
@@ -148,6 +148,7 @@ export async function openFile(file: File): Promise<LoadedDocument> {
perspectiveRuler: project.perspectiveRuler ?? null,
animationTimeline: project.animationTimeline ?? null,
timelapse: project.timelapse ?? null,
+ workTimeMs: project.workTimeMs,
previewDataUrl: project.previewDataUrl,
};
}
diff --git a/src/utils/legacySoraMigrator.ts b/src/utils/legacySoraMigrator.ts
index 19af20f..e399929 100644
--- a/src/utils/legacySoraMigrator.ts
+++ b/src/utils/legacySoraMigrator.ts
@@ -16,6 +16,7 @@ import {
sanitizeJsonLayer,
} from './saveManager/types';
import { extractZipPreview, parseInkZipBytes } from './saveManager/inkParse';
+import { extractWorkTimeMsFromManifest } from './artworkTimeTracker';
/**
* Read-only migrator for legacy `.sora` project files (v1 JSON and v2 binary/wrapped containers).
@@ -33,6 +34,7 @@ export interface LegacySoraV1Project {
layers: LayerItem[];
canvases: Record<string, string>;
masks: Record<string, string>;
+ workTimeMs?: number;
}
export type MigratedSoraProject =
@@ -109,6 +111,7 @@ export function parseLegacySoraV1Json(jsonText: string): LegacySoraV1Project {
layers,
canvases: parsed.canvases && typeof parsed.canvases === 'object' ? parsed.canvases : {},
masks: parsed.masks && typeof parsed.masks === 'object' ? parsed.masks : {},
+ workTimeMs: extractWorkTimeMsFromManifest(parsed),
};
}
@@ -200,6 +203,7 @@ export async function migrateLegacySoraFile(file: File): Promise<LoadedDocument>
perspectiveRuler: migrated.perspectiveRuler ?? null,
animationTimeline: migrated.animationTimeline ?? null,
timelapse: migrated.timelapse ?? null,
+ workTimeMs: migrated.workTimeMs,
previewDataUrl: migrated.previewDataUrl,
};
}
@@ -299,5 +303,6 @@ export async function migrateLegacySoraFile(file: File): Promise<LoadedDocument>
colorMode,
layers,
tileGrid: grid,
+ workTimeMs: migrated.workTimeMs,
};
}
diff --git a/src/utils/nativeBackend.ts b/src/utils/nativeBackend.ts
index 1ea15c8..4b5bbbf 100644
--- a/src/utils/nativeBackend.ts
+++ b/src/utils/nativeBackend.ts
@@ -8,6 +8,7 @@ import { createCanvasThumbnail } from './canvasUtils';
import { lz4DecompressBlock } from './lz4';
import { BYTES_32BIT, SparseTileGrid } from './tileEngine';
import { isTauriEnvironment } from './tileEngine/scratchDriver';
+import { performanceManager } from './performanceManager';
import type { LiquifyMode } from './liquifyEngine';
type TauriInvoke = typeof import('@tauri-apps/api/core').invoke;
@@ -15,7 +16,7 @@ type TauriInvoke = typeof import('@tauri-apps/api/core').invoke;
let cachedInvokePromise: Promise<TauriInvoke> | null = null;
export function isNativeRustAvailable(): boolean {
- return isTauriEnvironment();
+ return isTauriEnvironment() && performanceManager.getConfig().useNativeRustAcceleration;
}
function getInvoke(): Promise<TauriInvoke> {
diff --git a/src/utils/performanceManager.ts b/src/utils/performanceManager.ts
new file mode 100644
index 0000000..e56113a
--- /dev/null
+++ b/src/utils/performanceManager.ts
@@ -0,0 +1,942 @@
+/**
+ * Central Runtime Performance, Hardware Telemetry & Optimization Manager
+ *
+ * Bridges AppSettings (RAM allocation, GPU renderer & power preference, VRAM cache pool,
+ * HiDPI scaling, CPU worker thread limits, and Scratch Disk settings) to:
+ * - ViewportCompositor (WebGL2 / Canvas2D)
+ * - WebGlBrushEngine & BrushEngine
+ * - DocumentStore (Tile RAM & Undo RAM budgets)
+ * - Rust Tauri desktop backend (hardware telemetry, Rayon worker pool, custom scratch disk, WebView2 GPU flags)
+ */
+
+import {
+ AppSettings,
+ CanvasFilteringQuality,
+ DEFAULT_APP_SETTINGS,
+ DesktopGraphicsApi,
+ GpuPowerPreference,
+ GpuTexturePoolPreset,
+ PerformancePresetId,
+ Preview3DMaxResolution,
+ RenderBackend,
+ ScratchDiskCompression,
+ ViewportResolutionScale,
+} from '../types/settings';
+import { isTauriEnvironment } from './tileEngine/scratchDriver';
+
+export interface GpuAdapterInfo {
+ id: string;
+ name: string;
+ vendor: string;
+ vramMb: number;
+ kind: 'discrete' | 'integrated' | 'software' | 'unknown';
+ isPrimary: boolean;
+}
+
+export interface ActiveWebGlInfo {
+ available: boolean;
+ renderer: string;
+ vendor: string;
+ glVersion: string;
+ maxTextureSize: number;
+ maxArrayLayers: number;
+}
+
+export interface StartupPerformanceConfig {
+ gpuPowerPreference: GpuPowerPreference;
+ desktopGraphicsApi: DesktopGraphicsApi;
+ scratchDiskPath: string;
+ scratchDiskCompression: ScratchDiskCompression;
+ cpuWorkerThreads: number;
+}
+
+export interface SystemHardwareInfo {
+ totalRamMb: number;
+ availableRamMb: number;
+ cpuLogicalCores: number;
+ osPlatform: string;
+ isDesktop: boolean;
+ gpus: GpuAdapterInfo[];
+ activeWebGl: ActiveWebGlInfo;
+ scratchDiskPath: string;
+ scratchDiskFreeMb: number;
+ scratchDiskTotalMb: number;
+ scratchDiskUsedBytes: number;
+ undoCacheUsedBytes: number;
+ activeCpuWorkerThreads: number;
+ startupConfig: StartupPerformanceConfig;
+}
+
+export interface GpuTexturePoolSpec {
+ arrayLayers: number;
+ maxTexture2D: number;
+ estimatedVramMb: number;
+ label: string;
+}
+
+export const GPU_TEXTURE_POOL_CONFIGS: Record<GpuTexturePoolPreset, GpuTexturePoolSpec> = {
+ low: {
+ arrayLayers: 128,
+ maxTexture2D: 512,
+ estimatedVramMb: 32,
+ label: 'Low (32 MB)',
+ },
+ balanced: {
+ arrayLayers: 256,
+ maxTexture2D: 1024,
+ estimatedVramMb: 64,
+ label: 'Balanced (64 MB)',
+ },
+ high: {
+ arrayLayers: 512,
+ maxTexture2D: 2048,
+ estimatedVramMb: 128,
+ label: 'High (128 MB)',
+ },
+ ultra: {
+ arrayLayers: 1024,
+ maxTexture2D: 4096,
+ estimatedVramMb: 256,
+ label: 'Ultra (256 MB)',
+ },
+};
+
+export interface RuntimePerformanceConfig {
+ autoOptimizePerformance: boolean;
+ tileMemoryBudgetMb: number;
+ memoryAllocationPercent: number;
+ maxHistorySteps: number;
+ undoRamSteps: number;
+ offloadInactiveTabs: boolean;
+ renderBackend: RenderBackend;
+ gpuPowerPreference: GpuPowerPreference;
+ desktopGraphicsApi: DesktopGraphicsApi;
+ gpuBrushAcceleration: boolean;
+ gpuTexturePoolPreset: GpuTexturePoolPreset;
+ layerStackCaching: boolean;
+ viewportResolutionScale: ViewportResolutionScale;
+ canvasFilteringQuality: CanvasFilteringQuality;
+ scratchDiskPath: string;
+ scratchDiskCompression: ScratchDiskCompression;
+ cpuWorkerThreads: number;
+ useNativeRustAcceleration: boolean;
+ preview3DMaxResolution: Preview3DMaxResolution;
+ preview3DAntialias: boolean;
+}
+
+export interface CompositorTelemetry {
+ backend: 'webgl2' | 'canvas2d';
+ rendererName: string;
+ arrayPoolUsed: number;
+ arrayPoolCapacity: number;
+ texture2DPoolUsed: number;
+ estimatedVramMb: number;
+ stackCacheHits: number;
+ stackCacheRebuilds: number;
+}
+
+export interface LiveMemoryTelemetry {
+ activeTileMb: number;
+ tileBudgetMb: number;
+ tilePercent: number;
+ ramUndoSteps: number;
+ diskUndoSteps: number;
+ compressedRamUndoMb: number;
+ scratchDiskUsedMb: number;
+ undoDiskUsedMb: number;
+ jsHeapUsedMb: number | null;
+ jsHeapLimitMb: number | null;
+ compositor: CompositorTelemetry;
+}
+
+export type PurgeScope = 'tiles' | 'undo' | 'gpu' | 'scratch' | 'all';
+
+export interface PurgeResult {
+ freedTileMb: number;
+ offloadedUndoSteps: number;
+ flushedGpuTextures: boolean;
+ freedScratchDiskMb: number;
+}
+
+export interface AdobeMemoryLimits {
+ totalRamMb: number;
+ minMb: number;
+ maxMb: number;
+ idealMinMb: number;
+ idealMaxMb: number;
+ idealMinPercent: number;
+ idealMaxPercent: number;
+}
+
+export function extractPerformanceConfig(settings: AppSettings): RuntimePerformanceConfig {
+ return {
+ autoOptimizePerformance:
+ settings.autoOptimizePerformance ?? DEFAULT_APP_SETTINGS.autoOptimizePerformance,
+ tileMemoryBudgetMb: settings.tileMemoryBudgetMb || DEFAULT_APP_SETTINGS.tileMemoryBudgetMb,
+ memoryAllocationPercent:
+ settings.memoryAllocationPercent ?? DEFAULT_APP_SETTINGS.memoryAllocationPercent,
+ maxHistorySteps: settings.maxHistorySteps ?? DEFAULT_APP_SETTINGS.maxHistorySteps,
+ undoRamSteps: settings.undoRamSteps ?? DEFAULT_APP_SETTINGS.undoRamSteps,
+ offloadInactiveTabs: settings.offloadInactiveTabs ?? DEFAULT_APP_SETTINGS.offloadInactiveTabs,
+ renderBackend: settings.renderBackend ?? DEFAULT_APP_SETTINGS.renderBackend,
+ gpuPowerPreference: settings.gpuPowerPreference ?? DEFAULT_APP_SETTINGS.gpuPowerPreference,
+ desktopGraphicsApi: settings.desktopGraphicsApi ?? DEFAULT_APP_SETTINGS.desktopGraphicsApi,
+ gpuBrushAcceleration:
+ settings.gpuBrushAcceleration ?? DEFAULT_APP_SETTINGS.gpuBrushAcceleration,
+ gpuTexturePoolPreset:
+ settings.gpuTexturePoolPreset ?? DEFAULT_APP_SETTINGS.gpuTexturePoolPreset,
+ layerStackCaching: settings.layerStackCaching ?? DEFAULT_APP_SETTINGS.layerStackCaching,
+ viewportResolutionScale:
+ settings.viewportResolutionScale ?? DEFAULT_APP_SETTINGS.viewportResolutionScale,
+ canvasFilteringQuality:
+ settings.canvasFilteringQuality ?? DEFAULT_APP_SETTINGS.canvasFilteringQuality,
+ scratchDiskPath: settings.scratchDiskPath ?? DEFAULT_APP_SETTINGS.scratchDiskPath,
+ scratchDiskCompression:
+ settings.scratchDiskCompression ?? DEFAULT_APP_SETTINGS.scratchDiskCompression,
+ cpuWorkerThreads: settings.cpuWorkerThreads ?? DEFAULT_APP_SETTINGS.cpuWorkerThreads,
+ useNativeRustAcceleration:
+ settings.useNativeRustAcceleration ?? DEFAULT_APP_SETTINGS.useNativeRustAcceleration,
+ preview3DMaxResolution:
+ settings.preview3DMaxResolution ?? DEFAULT_APP_SETTINGS.preview3DMaxResolution,
+ preview3DAntialias: settings.preview3DAntialias ?? DEFAULT_APP_SETTINGS.preview3DAntialias,
+ };
+}
+
+/**
+ * Computes Adobe Photoshop-style RAM allocation bounds based on detected system memory.
+ */
+export function computeAdobeMemoryLimits(totalRamMb: number): AdobeMemoryLimits {
+ const safeTotal = Math.max(2048, Math.round(totalRamMb || 8192));
+ const minMb = 256;
+ const maxMb = Math.min(32768, Math.max(1024, Math.floor((safeTotal * 0.85) / 128) * 128));
+ const idealMinMb = Math.max(minMb, Math.floor((safeTotal * 0.5) / 128) * 128);
+ const idealMaxMb = Math.min(maxMb, Math.max(idealMinMb + 128, Math.floor((safeTotal * 0.7) / 128) * 128));
+ return {
+ totalRamMb: safeTotal,
+ minMb,
+ maxMb,
+ idealMinMb,
+ idealMaxMb,
+ idealMinPercent: 50,
+ idealMaxPercent: 70,
+ };
+}
+
+export function memoryPercentToMb(percent: number, totalRamMb: number): number {
+ const limits = computeAdobeMemoryLimits(totalRamMb);
+ const clampedPct = Math.max(20, Math.min(85, percent));
+ const raw = Math.round(((limits.totalRamMb * clampedPct) / 100) / 128) * 128;
+ return Math.max(limits.minMb, Math.min(limits.maxMb, raw));
+}
+
+export function memoryMbToPercent(mb: number, totalRamMb: number): number {
+ const safeTotal = Math.max(2048, totalRamMb || 8192);
+ return Math.max(20, Math.min(85, Math.round((mb / safeTotal) * 100)));
+}
+
+/**
+ * Computes effective viewport devicePixelRatio from the user's HiDPI scaling setting.
+ */
+export function resolveEffectiveDpr(
+ rawDpr: number,
+ scale: ViewportResolutionScale = 'capped-2x'
+): number {
+ const safeRaw = Number.isFinite(rawDpr) && rawDpr > 0 ? rawDpr : 1;
+ switch (scale) {
+ case 'native':
+ return safeRaw;
+ case 'capped-2x':
+ return Math.min(safeRaw, 2);
+ case '1x':
+ return 1;
+ case '0.75x':
+ return 0.75;
+ default:
+ return Math.min(safeRaw, 2);
+ }
+}
+
+export interface RecommendedPerformanceResult {
+ settings: Partial<AppSettings>;
+ profileLabel: string;
+ summary: string;
+}
+
+function isSoftwareRendererString(name: string): boolean {
+ const lower = (name || '').toLowerCase();
+ return (
+ lower.includes('swiftshader') ||
+ lower.includes('llvmpipe') ||
+ lower.includes('microsoft basic') ||
+ lower.includes('software') ||
+ lower.includes('warp')
+ );
+}
+
+/**
+ * Automatically calculates optimal Ink Studio performance settings from detected hardware
+ * (System RAM, GPU class/VRAM, WebGL2 availability, and CPU cores) so users never have to tune manually.
+ */
+export function computeRecommendedSettings(
+ hw: Pick<SystemHardwareInfo, 'totalRamMb' | 'cpuLogicalCores' | 'gpus' | 'activeWebGl'>
+): RecommendedPerformanceResult {
+ const totalRamMb = Math.max(2048, Math.round(hw.totalRamMb || 8192));
+ const gpus = Array.isArray(hw.gpus) ? hw.gpus : [];
+ const hasDiscreteGpu = gpus.some((g) => g.kind === 'discrete');
+ const maxDiscreteVramMb = gpus
+ .filter((g) => g.kind === 'discrete')
+ .reduce((max, g) => Math.max(max, g.vramMb || 0), 0);
+
+ const webglAvailable = Boolean(hw.activeWebGl?.available);
+ const webglIsSoftware =
+ !webglAvailable || isSoftwareRendererString(hw.activeWebGl?.renderer || '');
+ const onlySoftwareGpu =
+ webglIsSoftware && (gpus.length === 0 || gpus.every((g) => g.kind === 'software'));
+
+ // Software-only / no hardware GPU fallback
+ if (onlySoftwareGpu) {
+ const percent = totalRamMb <= 4096 ? 45 : 55;
+ const budgetMb = memoryPercentToMb(percent, totalRamMb);
+ return {
+ profileLabel: 'Auto (CPU Safe)',
+ summary: `${Math.round(budgetMb / 102.4) / 10 >= 1 ? `${(budgetMb / 1024).toFixed(1)} GB` : `${budgetMb} MB`} RAM · Canvas 2D CPU · 1× Scale`,
+ settings: {
+ autoOptimizePerformance: true,
+ memoryAllocationPercent: percent,
+ tileMemoryBudgetMb: budgetMb,
+ undoRamSteps: totalRamMb <= 4096 ? 8 : 12,
+ offloadInactiveTabs: true,
+ renderBackend: 'canvas2d',
+ gpuPowerPreference: 'default',
+ desktopGraphicsApi: 'auto',
+ gpuBrushAcceleration: false,
+ gpuTexturePoolPreset: 'low',
+ layerStackCaching: false,
+ viewportResolutionScale: '1x',
+ canvasFilteringQuality: 'auto',
+ scratchDiskCompression: 'lz4',
+ cpuWorkerThreads: 0,
+ useNativeRustAcceleration: true,
+ preview3DMaxResolution: 1024,
+ preview3DAntialias: false,
+ },
+ };
+ }
+
+ // Tiered hardware calibration based on system RAM & GPU class
+ let percent = 60;
+ let undoRamSteps = 15;
+ let gpuTexturePoolPreset: GpuTexturePoolPreset = 'balanced';
+ let viewportResolutionScale: ViewportResolutionScale = 'capped-2x';
+ let preview3DMaxResolution: Preview3DMaxResolution = 1920;
+ let preview3DAntialias = true;
+ let profileLabel = 'Auto (Balanced)';
+
+ if (totalRamMb <= 4096) {
+ percent = 50;
+ undoRamSteps = 8;
+ gpuTexturePoolPreset = 'low';
+ viewportResolutionScale = '1x';
+ preview3DMaxResolution = 1024;
+ preview3DAntialias = false;
+ profileLabel = 'Auto (Compact RAM)';
+ } else if (totalRamMb <= 8192) {
+ percent = 55;
+ undoRamSteps = 12;
+ gpuTexturePoolPreset = hasDiscreteGpu ? 'high' : 'balanced';
+ viewportResolutionScale = 'capped-2x';
+ preview3DMaxResolution = 1920;
+ preview3DAntialias = true;
+ profileLabel = 'Auto (Standard)';
+ } else if (totalRamMb >= 24576 && (hasDiscreteGpu || (hw.activeWebGl?.maxArrayLayers ?? 0) >= 1024)) {
+ percent = 65;
+ undoRamSteps = 25;
+ gpuTexturePoolPreset =
+ hasDiscreteGpu && (maxDiscreteVramMb === 0 || maxDiscreteVramMb >= 4096) ? 'ultra' : 'high';
+ viewportResolutionScale = 'capped-2x';
+ preview3DMaxResolution = 2560;
+ preview3DAntialias = true;
+ profileLabel = 'Auto (Workstation)';
+ } else {
+ // 16 GB class
+ percent = 60;
+ undoRamSteps = 18;
+ gpuTexturePoolPreset = hasDiscreteGpu ? 'high' : 'balanced';
+ viewportResolutionScale = 'capped-2x';
+ preview3DMaxResolution = 1920;
+ preview3DAntialias = true;
+ profileLabel = hasDiscreteGpu ? 'Auto (High GPU)' : 'Auto (Balanced)';
+ }
+
+ const budgetMb = memoryPercentToMb(percent, totalRamMb);
+ const ramLabel =
+ budgetMb >= 1024
+ ? `${(budgetMb / 1024).toFixed(budgetMb % 1024 === 0 ? 0 : 1)} GB`
+ : `${budgetMb} MB`;
+ const gpuLabel = hasDiscreteGpu ? 'Dedicated GPU' : 'WebGL2 GPU';
+ const poolLabel = GPU_TEXTURE_POOL_CONFIGS[gpuTexturePoolPreset].label;
+
+ return {
+ profileLabel,
+ summary: `${ramLabel} RAM · ${gpuLabel} · ${poolLabel} Cache`,
+ settings: {
+ autoOptimizePerformance: true,
+ memoryAllocationPercent: percent,
+ tileMemoryBudgetMb: budgetMb,
+ undoRamSteps,
+ offloadInactiveTabs: true,
+ renderBackend: 'auto',
+ gpuPowerPreference: hasDiscreteGpu ? 'high-performance' : 'default',
+ desktopGraphicsApi: 'auto',
+ gpuBrushAcceleration: true,
+ gpuTexturePoolPreset,
+ layerStackCaching: true,
+ viewportResolutionScale,
+ canvasFilteringQuality: 'auto',
+ scratchDiskCompression: 'lz4',
+ cpuWorkerThreads: 0,
+ useNativeRustAcceleration: true,
+ preview3DMaxResolution,
+ preview3DAntialias,
+ },
+ };
+}
+
+/**
+ * Generates an optimized bundle of performance settings calibrated to the host machine's RAM.
+ */
+export function buildPerformancePreset(
+ preset: PerformancePresetId,
+ totalRamMb: number = 8192
+): Partial<AppSettings> {
+ switch (preset) {
+ case 'battery': {
+ const percent = 40;
+ return {
+ autoOptimizePerformance: false,
+ memoryAllocationPercent: percent,
+ tileMemoryBudgetMb: memoryPercentToMb(percent, totalRamMb),
+ undoRamSteps: 8,
+ offloadInactiveTabs: true,
+ renderBackend: 'auto',
+ gpuPowerPreference: 'low-power',
+ gpuBrushAcceleration: true,
+ gpuTexturePoolPreset: 'low',
+ layerStackCaching: true,
+ viewportResolutionScale: '1x',
+ canvasFilteringQuality: 'auto',
+ scratchDiskCompression: 'lz4',
+ preview3DMaxResolution: 1024,
+ preview3DAntialias: false,
+ };
+ }
+ case 'maximum': {
+ const percent = 70;
+ return {
+ autoOptimizePerformance: false,
+ memoryAllocationPercent: percent,
+ tileMemoryBudgetMb: memoryPercentToMb(percent, totalRamMb),
+ undoRamSteps: 25,
+ offloadInactiveTabs: true,
+ renderBackend: 'webgl2',
+ gpuPowerPreference: 'high-performance',
+ gpuBrushAcceleration: true,
+ gpuTexturePoolPreset: totalRamMb >= 16384 ? 'ultra' : 'high',
+ layerStackCaching: true,
+ viewportResolutionScale: 'native',
+ canvasFilteringQuality: 'auto',
+ scratchDiskCompression: 'lz4',
+ cpuWorkerThreads: 0,
+ useNativeRustAcceleration: true,
+ preview3DMaxResolution: 2560,
+ preview3DAntialias: true,
+ };
+ }
+ case 'compatibility': {
+ const percent = 50;
+ return {
+ autoOptimizePerformance: false,
+ memoryAllocationPercent: percent,
+ tileMemoryBudgetMb: memoryPercentToMb(percent, totalRamMb),
+ undoRamSteps: 10,
+ offloadInactiveTabs: true,
+ renderBackend: 'canvas2d',
+ gpuPowerPreference: 'default',
+ gpuBrushAcceleration: false,
+ gpuTexturePoolPreset: 'low',
+ layerStackCaching: false,
+ viewportResolutionScale: '1x',
+ canvasFilteringQuality: 'auto',
+ scratchDiskCompression: 'lz4',
+ preview3DMaxResolution: 1024,
+ preview3DAntialias: false,
+ };
+ }
+ case 'balanced':
+ default: {
+ const percent = 60;
+ return {
+ autoOptimizePerformance: false,
+ memoryAllocationPercent: percent,
+ tileMemoryBudgetMb: memoryPercentToMb(percent, totalRamMb),
+ undoRamSteps: 15,
+ offloadInactiveTabs: true,
+ renderBackend: 'auto',
+ gpuPowerPreference: 'high-performance',
+ gpuBrushAcceleration: true,
+ gpuTexturePoolPreset: 'balanced',
+ layerStackCaching: true,
+ viewportResolutionScale: 'capped-2x',
+ canvasFilteringQuality: 'auto',
+ scratchDiskCompression: 'lz4',
+ cpuWorkerThreads: 0,
+ useNativeRustAcceleration: true,
+ preview3DMaxResolution: 1920,
+ preview3DAntialias: true,
+ };
+ }
+ }
+}
+
+export function probeWebGlRenderer(
+ powerPreference: GpuPowerPreference = 'high-performance'
+): ActiveWebGlInfo {
+ if (typeof document === 'undefined') {
+ return {
+ available: false,
+ renderer: 'CPU Software (Headless)',
+ vendor: 'Standard',
+ glVersion: 'None',
+ maxTextureSize: 0,
+ maxArrayLayers: 0,
+ };
+ }
+ try {
+ const canvas = document.createElement('canvas');
+ canvas.width = 1;
+ canvas.height = 1;
+ const gl = canvas.getContext('webgl2', {
+ powerPreference,
+ alpha: true,
+ antialias: false,
+ depth: false,
+ stencil: false,
+ }) as WebGL2RenderingContext | null;
+ if (!gl) {
+ return {
+ available: false,
+ renderer: 'Canvas 2D (WebGL2 Unavailable)',
+ vendor: 'Standard',
+ glVersion: 'None',
+ maxTextureSize: 0,
+ maxArrayLayers: 0,
+ };
+ }
+
+ let renderer = 'WebGL2 Hardware GPU';
+ let vendor = 'Generic';
+ if (typeof gl.getExtension === 'function') {
+ const debugExt = gl.getExtension('WEBGL_debug_renderer_info');
+ if (debugExt) {
+ renderer = String(gl.getParameter(debugExt.UNMASKED_RENDERER_WEBGL) || renderer);
+ vendor = String(gl.getParameter(debugExt.UNMASKED_VENDOR_WEBGL) || vendor);
+ }
+ }
+ const glVersion = String(gl.getParameter(gl.VERSION) || 'WebGL 2.0');
+ const maxTextureSize = Number(gl.getParameter(gl.MAX_TEXTURE_SIZE)) || 4096;
+ const maxArrayLayers = Number(gl.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS)) || 256;
+
+ // Immediately free probe WebGL context so we don't leak context slots
+ const loseExt = gl.getExtension?.('WEBGL_lose_context');
+ loseExt?.loseContext?.();
+ canvas.width = 0;
+ canvas.height = 0;
+
+ return {
+ available: true,
+ renderer,
+ vendor,
+ glVersion,
+ maxTextureSize,
+ maxArrayLayers,
+ };
+ } catch {
+ return {
+ available: false,
+ renderer: 'Canvas 2D Fallback',
+ vendor: 'Standard',
+ glVersion: 'None',
+ maxTextureSize: 0,
+ maxArrayLayers: 0,
+ };
+ }
+}
+
+export interface RegisteredCompositorHooks {
+ getTelemetry: () => CompositorTelemetry;
+ flushGpuCaches: () => void;
+}
+
+export interface RegisteredMemoryHooks {
+ getActiveTileBytes: () => number;
+ getTileBudgetBytes: () => number;
+ getUndoStats: () => { ramSteps: number; diskSteps: number; compressedRamBytes: number };
+ getActiveSessionIds: () => string[];
+ purgeTiles: () => Promise<number>;
+ purgeUndo: () => Promise<number>;
+ flushBrushGpuCaches?: () => void;
+}
+
+type PerfListener = (config: RuntimePerformanceConfig) => void;
+
+class PerformanceManager {
+ private config: RuntimePerformanceConfig = extractPerformanceConfig(DEFAULT_APP_SETTINGS);
+ private listeners: Set<PerfListener> = new Set();
+ private cachedHardwareInfo: SystemHardwareInfo | null = null;
+ private compositorHooks: RegisteredCompositorHooks | null = null;
+ private memoryHooks: RegisteredMemoryHooks | null = null;
+ private invokePromise: Promise<typeof import('@tauri-apps/api/core').invoke> | null = null;
+ private lastAppliedStartupConfig: StartupPerformanceConfig | null = null;
+
+ private getInvoke(): Promise<typeof import('@tauri-apps/api/core').invoke> {
+ if (!this.invokePromise) {
+ this.invokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);
+ }
+ return this.invokePromise;
+ }
+
+ public getConfig(): RuntimePerformanceConfig {
+ return this.config;
+ }
+
+ public subscribe(listener: PerfListener): () => void {
+ this.listeners.add(listener);
+ return () => {
+ this.listeners.delete(listener);
+ };
+ }
+
+ public applySettings(settings: AppSettings): RuntimePerformanceConfig {
+ const next = extractPerformanceConfig(settings);
+ this.config = next;
+ for (const listener of Array.from(this.listeners)) {
+ try {
+ listener(next);
+ } catch (err) {
+ console.warn('[PerformanceManager] listener error:', err);
+ }
+ }
+ return next;
+ }
+
+ public registerCompositorHooks(hooks: RegisteredCompositorHooks | null): void {
+ this.compositorHooks = hooks;
+ }
+
+ public registerMemoryHooks(hooks: RegisteredMemoryHooks | null): void {
+ this.memoryHooks = hooks;
+ }
+
+ public needsRestartForDesktopGpuFlags(settings: AppSettings): boolean {
+ if (!isTauriEnvironment() || !this.lastAppliedStartupConfig) return false;
+ return (
+ this.lastAppliedStartupConfig.gpuPowerPreference !== settings.gpuPowerPreference ||
+ this.lastAppliedStartupConfig.desktopGraphicsApi !== settings.desktopGraphicsApi
+ );
+ }
+
+ public async detectHardwareInfo(forceRefresh = false): Promise<SystemHardwareInfo> {
+ if (this.cachedHardwareInfo && !forceRefresh) {
+ return this.cachedHardwareInfo;
+ }
+
+ const activeWebGl = probeWebGlRenderer(this.config.gpuPowerPreference);
+
+ if (isTauriEnvironment()) {
+ try {
+ const invoke = await this.getInvoke();
+ const native = await invoke<{
+ totalRamMb: number;
+ availableRamMb: number;
+ cpuLogicalCores: number;
+ osPlatform: string;
+ gpus: GpuAdapterInfo[];
+ scratchDiskPath: string;
+ scratchDiskFreeMb: number;
+ scratchDiskTotalMb: number;
+ scratchDiskUsedBytes: number;
+ undoCacheUsedBytes: number;
+ activeCpuWorkerThreads: number;
+ startupConfig: StartupPerformanceConfig;
+ }>('get_system_hardware_info');
+
+ if (!this.lastAppliedStartupConfig && native.startupConfig) {
+ this.lastAppliedStartupConfig = { ...native.startupConfig };
+ }
+
+ const gpus: GpuAdapterInfo[] =
+ native.gpus && native.gpus.length > 0
+ ? native.gpus
+ : activeWebGl.available
+ ? [
+ {
+ id: 'webgl-active',
+ name: activeWebGl.renderer,
+ vendor: activeWebGl.vendor,
+ vramMb: 0,
+ kind: 'unknown',
+ isPrimary: true,
+ },
+ ]
+ : [];
+
+ const info: SystemHardwareInfo = {
+ totalRamMb: native.totalRamMb || 8192,
+ availableRamMb: native.availableRamMb || 4096,
+ cpuLogicalCores: native.cpuLogicalCores || 4,
+ osPlatform: native.osPlatform || 'desktop',
+ isDesktop: true,
+ gpus,
+ activeWebGl,
+ scratchDiskPath: native.scratchDiskPath || '',
+ scratchDiskFreeMb: native.scratchDiskFreeMb || 0,
+ scratchDiskTotalMb: native.scratchDiskTotalMb || 0,
+ scratchDiskUsedBytes: native.scratchDiskUsedBytes || 0,
+ undoCacheUsedBytes: native.undoCacheUsedBytes || 0,
+ activeCpuWorkerThreads: native.activeCpuWorkerThreads || 0,
+ startupConfig: native.startupConfig || {
+ gpuPowerPreference: this.config.gpuPowerPreference,
+ desktopGraphicsApi: this.config.desktopGraphicsApi,
+ scratchDiskPath: this.config.scratchDiskPath,
+ scratchDiskCompression: this.config.scratchDiskCompression,
+ cpuWorkerThreads: this.config.cpuWorkerThreads,
+ },
+ };
+ this.cachedHardwareInfo = info;
+ return info;
+ } catch (err) {
+ console.warn('[PerformanceManager] Failed to query native hardware info:', err);
+ }
+ }
+
+ // Web / Browser fallback telemetry
+ const nav = typeof navigator !== 'undefined' ? (navigator as Navigator & { deviceMemory?: number }) : null;
+ const deviceMemGb = typeof nav?.deviceMemory === 'number' && nav.deviceMemory > 0 ? nav.deviceMemory : 8;
+ const totalRamMb = Math.round(deviceMemGb * 1024);
+ const cores = typeof nav?.hardwareConcurrency === 'number' && nav.hardwareConcurrency > 0 ? nav.hardwareConcurrency : 4;
+
+ const webGpus: GpuAdapterInfo[] = activeWebGl.available
+ ? [
+ {
+ id: 'webgl-primary',
+ name: activeWebGl.renderer,
+ vendor: activeWebGl.vendor,
+ vramMb: 0,
+ kind: 'unknown',
+ isPrimary: true,
+ },
+ ]
+ : [];
+
+ const webInfo: SystemHardwareInfo = {
+ totalRamMb,
+ availableRamMb: Math.round(totalRamMb * 0.65),
+ cpuLogicalCores: cores,
+ osPlatform: 'web',
+ isDesktop: false,
+ gpus: webGpus,
+ activeWebGl,
+ scratchDiskPath: 'Browser In-Memory (IndexedDB / LZ4)',
+ scratchDiskFreeMb: 0,
+ scratchDiskTotalMb: 0,
+ scratchDiskUsedBytes: 0,
+ undoCacheUsedBytes: 0,
+ activeCpuWorkerThreads: 0,
+ startupConfig: {
+ gpuPowerPreference: this.config.gpuPowerPreference,
+ desktopGraphicsApi: this.config.desktopGraphicsApi,
+ scratchDiskPath: '',
+ scratchDiskCompression: this.config.scratchDiskCompression,
+ cpuWorkerThreads: this.config.cpuWorkerThreads,
+ },
+ };
+ this.cachedHardwareInfo = webInfo;
+ return webInfo;
+ }
+
+ public async syncDesktopBackendConfig(
+ settings: AppSettings
+ ): Promise<{ ok: boolean; info?: SystemHardwareInfo; error?: string }> {
+ if (!isTauriEnvironment()) {
+ return { ok: true };
+ }
+ try {
+ const invoke = await this.getInvoke();
+ const payload: StartupPerformanceConfig = {
+ gpuPowerPreference: settings.gpuPowerPreference,
+ desktopGraphicsApi: settings.desktopGraphicsApi,
+ scratchDiskPath: settings.scratchDiskPath || '',
+ scratchDiskCompression: settings.scratchDiskCompression,
+ cpuWorkerThreads: settings.cpuWorkerThreads,
+ };
+ const native = await invoke<{
+ totalRamMb: number;
+ availableRamMb: number;
+ cpuLogicalCores: number;
+ osPlatform: string;
+ gpus: GpuAdapterInfo[];
+ scratchDiskPath: string;
+ scratchDiskFreeMb: number;
+ scratchDiskTotalMb: number;
+ scratchDiskUsedBytes: number;
+ undoCacheUsedBytes: number;
+ activeCpuWorkerThreads: number;
+ startupConfig: StartupPerformanceConfig;
+ }>('apply_performance_config', { config: payload });
+
+ const activeWebGl = this.cachedHardwareInfo?.activeWebGl ?? probeWebGlRenderer(settings.gpuPowerPreference);
+ const info: SystemHardwareInfo = {
+ ...native,
+ isDesktop: true,
+ activeWebGl,
+ };
+ this.cachedHardwareInfo = info;
+ return { ok: true, info };
+ } catch (err) {
+ return {
+ ok: false,
+ error: err instanceof Error ? err.message : String(err),
+ };
+ }
+ }
+
+ public async getMemoryTelemetry(): Promise<LiveMemoryTelemetry> {
+ const activeTileBytes = this.memoryHooks?.getActiveTileBytes() ?? 0;
+ const tileBudgetBytes =
+ this.memoryHooks?.getTileBudgetBytes() ?? this.config.tileMemoryBudgetMb * 1024 * 1024;
+ const undoStats = this.memoryHooks?.getUndoStats() ?? {
+ ramSteps: 0,
+ diskSteps: 0,
+ compressedRamBytes: 0,
+ };
+
+ let scratchDiskUsedBytes = this.cachedHardwareInfo?.scratchDiskUsedBytes ?? 0;
+ let undoDiskUsedBytes = this.cachedHardwareInfo?.undoCacheUsedBytes ?? 0;
+
+ if (isTauriEnvironment()) {
+ try {
+ const invoke = await this.getInvoke();
+ const usage = await invoke<{
+ scratchDiskUsedBytes: number;
+ undoCacheUsedBytes: number;
+ scratchDiskFreeMb: number;
+ scratchDiskTotalMb: number;
+ scratchDiskPath: string;
+ }>('get_scratch_disk_usage');
+ scratchDiskUsedBytes = usage.scratchDiskUsedBytes;
+ undoDiskUsedBytes = usage.undoCacheUsedBytes;
+ if (this.cachedHardwareInfo) {
+ this.cachedHardwareInfo = {
+ ...this.cachedHardwareInfo,
+ scratchDiskPath: usage.scratchDiskPath,
+ scratchDiskFreeMb: usage.scratchDiskFreeMb,
+ scratchDiskTotalMb: usage.scratchDiskTotalMb,
+ scratchDiskUsedBytes: usage.scratchDiskUsedBytes,
+ undoCacheUsedBytes: usage.undoCacheUsedBytes,
+ };
+ }
+ } catch {
+ // Ignore transient telemetry errors
+ }
+ }
+
+ const perfMem =
+ typeof performance !== 'undefined'
+ ? (performance as Performance & {
+ memory?: { usedJSHeapSize: number; jsHeapSizeLimit: number };
+ }).memory
+ : undefined;
+
+ const poolPreset = this.config.gpuTexturePoolPreset;
+ const poolSpec =
+ (poolPreset && GPU_TEXTURE_POOL_CONFIGS[poolPreset]) || GPU_TEXTURE_POOL_CONFIGS.high;
+
+ const compositor: CompositorTelemetry = this.compositorHooks?.getTelemetry() ?? {
+ backend: this.config.renderBackend === 'canvas2d' ? 'canvas2d' : 'webgl2',
+ rendererName:
+ this.config.renderBackend === 'canvas2d'
+ ? 'Canvas 2D (CPU)'
+ : this.cachedHardwareInfo?.activeWebGl?.renderer || 'WebGL2',
+ arrayPoolUsed: 0,
+ arrayPoolCapacity: poolSpec.arrayLayers,
+ texture2DPoolUsed: 0,
+ estimatedVramMb: 0,
+ stackCacheHits: 0,
+ stackCacheRebuilds: 0,
+ };
+
+ const activeTileMb = Math.round((activeTileBytes / (1024 * 1024)) * 10) / 10;
+ const tileBudgetMb = Math.max(1, Math.round(tileBudgetBytes / (1024 * 1024)));
+
+ return {
+ activeTileMb,
+ tileBudgetMb,
+ tilePercent: Math.min(100, Math.round((activeTileMb / tileBudgetMb) * 100)),
+ ramUndoSteps: undoStats.ramSteps,
+ diskUndoSteps: undoStats.diskSteps,
+ compressedRamUndoMb: Math.round((undoStats.compressedRamBytes / (1024 * 1024)) * 10) / 10,
+ scratchDiskUsedMb: Math.round((scratchDiskUsedBytes / (1024 * 1024)) * 10) / 10,
+ undoDiskUsedMb: Math.round((undoDiskUsedBytes / (1024 * 1024)) * 10) / 10,
+ jsHeapUsedMb: perfMem ? Math.round((perfMem.usedJSHeapSize / (1024 * 1024)) * 10) / 10 : null,
+ jsHeapLimitMb: perfMem ? Math.round((perfMem.jsHeapSizeLimit / (1024 * 1024)) * 10) / 10 : null,
+ compositor,
+ };
+ }
+
+ public async purgeMemory(scope: PurgeScope = 'all'): Promise<PurgeResult> {
+ let freedTileBytes = 0;
+ let offloadedUndoSteps = 0;
+ let flushedGpuTextures = false;
+ let freedScratchBytes = 0;
+
+ if ((scope === 'tiles' || scope === 'all') && this.memoryHooks) {
+ freedTileBytes = await this.memoryHooks.purgeTiles();
+ }
+
+ if ((scope === 'undo' || scope === 'all') && this.memoryHooks) {
+ offloadedUndoSteps = await this.memoryHooks.purgeUndo();
+ }
+
+ if (scope === 'gpu' || scope === 'all') {
+ if (this.compositorHooks) {
+ this.compositorHooks.flushGpuCaches();
+ flushedGpuTextures = true;
+ }
+ if (this.memoryHooks?.flushBrushGpuCaches) {
+ this.memoryHooks.flushBrushGpuCaches();
+ flushedGpuTextures = true;
+ }
+ }
+
+ if ((scope === 'scratch' || scope === 'all') && isTauriEnvironment()) {
+ try {
+ const invoke = await this.getInvoke();
+ const activeSessionIds = this.memoryHooks?.getActiveSessionIds() ?? [];
+ freedScratchBytes = await invoke<number>('purge_unused_scratch_files', {
+ activeSessionIds,
+ });
+ } catch (err) {
+ console.warn('[PerformanceManager] Failed to purge unused scratch files:', err);
+ }
+ }
+
+ return {
+ freedTileMb: Math.round((freedTileBytes / (1024 * 1024)) * 10) / 10,
+ offloadedUndoSteps,
+ flushedGpuTextures,
+ freedScratchDiskMb: Math.round((freedScratchBytes / (1024 * 1024)) * 10) / 10,
+ };
+ }
+}
+
+export const performanceManager = new PerformanceManager();
diff --git a/src/utils/psdParser.ts b/src/utils/psdParser.ts
index 06c48d9..f1b5153 100644
--- a/src/utils/psdParser.ts
+++ b/src/utils/psdParser.ts
@@ -3,6 +3,7 @@ import { BlendMode, CanvasColorMode, LayerItem, LoadedDocument } from '../types/
import { createCanvasThumbnail } from './canvasUtils';
import { isNativeRustAvailable, parsePsdNative } from './nativeBackend';
import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';
+import { extractWorkTimeMsFromPsdBuffer, extractWorkTimeMsFromXmp } from './artworkTimeTracker';
initializeCanvas(
(w, h) => {
@@ -247,7 +248,12 @@ export async function parsePsdFile(
targetGrid?: SparseTileGrid
): Promise<LoadedDocument> {
if (isNativeRustAvailable()) {
- return await parsePsdNative(buffer, fileName, targetGrid);
+ const nativeDoc = await parsePsdNative(buffer, fileName, targetGrid);
+ const nativeWorkTimeMs = extractWorkTimeMsFromPsdBuffer(buffer);
+ if (nativeWorkTimeMs !== undefined) {
+ return { ...nativeDoc, workTimeMs: nativeWorkTimeMs };
+ }
+ return nativeDoc;
}
const psd = readPsd(buffer, {
@@ -416,11 +422,14 @@ export async function parsePsdFile(
});
}
+ const workTimeMs = extractWorkTimeMsFromXmp(psd.imageResources?.xmpMetadata);
+
return {
name: fileName.replace(/\.[^/.]+$/, ''),
dimensions: { width, height, dpi },
colorMode,
layers,
tileGrid,
+ ...(workTimeMs !== undefined ? { workTimeMs } : {}),
};
}
diff --git a/src/utils/recentDocumentsManager.ts b/src/utils/recentDocumentsManager.ts
index bf2e39b..5ee20ad 100644
--- a/src/utils/recentDocumentsManager.ts
+++ b/src/utils/recentDocumentsManager.ts
@@ -5,6 +5,14 @@ import {
safeLocalStorageSetItem,
} from './safeStorage';
+export interface FileSystemFileHandleLike {
+ name: string;
+ getFile: () => Promise<File>;
+ createWritable?: () => Promise<FileSystemWritableFileStream>;
+ queryPermission?: (opts?: { mode?: 'read' | 'readwrite' }) => Promise<'granted' | 'denied' | 'prompt'>;
+ requestPermission?: (opts?: { mode?: 'read' | 'readwrite' }) => Promise<'granted' | 'denied' | 'prompt'>;
+}
+
export interface RecentDocument {
id: string;
title: string;
@@ -15,6 +23,7 @@ export interface RecentDocument {
isStarred: boolean;
fileType?: string;
isSaved?: boolean;
+ handle?: FileSystemFileHandleLike;
}
const DB_NAME = 'InkStudioRecentDocsDB';
@@ -39,11 +48,12 @@ export function isActualSavedDocument(doc: RecentDocument): boolean {
}
/**
- * Strips heavy coverUrl thumbnails so localStorage only ever stores lightweight metadata/IDs.
+ * Strips heavy coverUrl thumbnails and non-JSON-serializable handles so localStorage
+ * only ever stores lightweight metadata/IDs.
*/
-function stripRecentDocThumbnail(doc: RecentDocument): RecentDocument {
- if (!doc.coverUrl) return doc;
- const { coverUrl: _omit, ...lightweight } = doc;
+function stripForLocalStorage(doc: RecentDocument): RecentDocument {
+ if (!doc.coverUrl && !doc.handle) return doc;
+ const { coverUrl: _omitCover, handle: _omitHandle, ...lightweight } = doc;
return lightweight;
}
@@ -74,7 +84,7 @@ function openDB(): Promise<IDBDatabase> {
}
function writeFallbackDocs(docs: RecentDocument[]): void {
- const stripped = docs.filter(isActualSavedDocument).map(stripRecentDocThumbnail);
+ const stripped = docs.filter(isActualSavedDocument).map(stripForLocalStorage);
safeLocalStorageSetItem(RECENT_DOCS_LS_KEY, JSON.stringify(stripped), 'recent documents');
}
@@ -94,7 +104,7 @@ function getRawFallbackDocs(): RecentDocument[] {
}
function getFallbackDocs(): RecentDocument[] {
- return getRawFallbackDocs().map(stripRecentDocThumbnail);
+ return getRawFallbackDocs().map(stripForLocalStorage);
}
export async function loadRecentDocuments(): Promise<RecentDocument[]> {
@@ -170,10 +180,26 @@ export async function saveRecentDocument(
tx.onerror = () => reject(tx.error);
});
} catch (err) {
+ if (fullDoc.handle) {
+ const { handle: _omitHandle, ...withoutHandle } = fullDoc;
+ try {
+ const db = await openDB();
+ await new Promise<void>((resolve, reject) => {
+ const tx = db.transaction(STORE_NAME, 'readwrite');
+ const req = tx.objectStore(STORE_NAME).put(withoutHandle);
+ req.onerror = () => reject(req.error);
+ tx.oncomplete = () => resolve();
+ tx.onerror = () => reject(tx.error);
+ });
+ return;
+ } catch {
+ // Fall through to localStorage fallback
+ }
+ }
handleIndexedDbError(err, 'recent document thumbnail');
- // Fallback to localStorage without heavy thumbnail payloads
+ // Fallback to localStorage without heavy thumbnail payloads or file handles
const current = getFallbackDocs().filter((d) => d.id !== fullDoc.id);
- writeFallbackDocs([stripRecentDocThumbnail(fullDoc), ...current]);
+ writeFallbackDocs([stripForLocalStorage(fullDoc), ...current]);
}
}
diff --git a/src/utils/saveManager/fileActions.ts b/src/utils/saveManager/fileActions.ts
index 946a9dc..b84b6f6 100644
--- a/src/utils/saveManager/fileActions.ts
+++ b/src/utils/saveManager/fileActions.ts
@@ -2,6 +2,7 @@ import { buildLayerTree } from '../compositor';
import { recoveryService } from '../../services/recoveryService';
import { releaseTemporaryCanvas } from '../tileEngine';
import { documentStore } from '../documentStore';
+import { buildInkStudioXmpMetadata, sanitizeWorkTimeMs } from '../artworkTimeTracker';
import {
ExportImageOptions,
ExportImageResult,
@@ -106,6 +107,7 @@ export async function serializeDocument(
);
const dpi = data.dimensions.dpi || 300;
+ const workTimeMs = sanitizeWorkTimeMs(data.workTimeMs);
const { writePsd } = await import('ag-psd');
const psdBuffer = writePsd(
{
@@ -121,6 +123,7 @@ export async function serializeDocument(
verticalResolutionUnit: 'PPI',
heightUnit: 'Inches',
},
+ ...(workTimeMs > 0 ? { xmpMetadata: buildInkStudioXmpMetadata(workTimeMs) } : {}),
},
},
{
diff --git a/src/utils/saveManager/gpuComposite.ts b/src/utils/saveManager/gpuComposite.ts
index 259a0fc..619f363 100644
--- a/src/utils/saveManager/gpuComposite.ts
+++ b/src/utils/saveManager/gpuComposite.ts
@@ -1,5 +1,6 @@
import type { CanvasColorMode, CanvasDimensions, LayerItem } from '../../types/editor';
import { ViewportCompositor, ViewportTransform } from '../compositor';
+import { performanceManager } from '../performanceManager';
import { SparseTileGrid, releaseTemporaryCanvas } from '../tileEngine';
import {
CompositeCanvasOptions,
@@ -22,7 +23,12 @@ function tryCompositeCanvasGpuSync(
tileGrid?: SparseTileGrid,
options?: CompositeCanvasOptions
): HTMLCanvasElement | null {
- if (typeof document === 'undefined' || dimensions.width <= 0 || dimensions.height <= 0) {
+ if (
+ typeof document === 'undefined' ||
+ dimensions.width <= 0 ||
+ dimensions.height <= 0 ||
+ performanceManager.getConfig().renderBackend === 'canvas2d'
+ ) {
return null;
}
@@ -133,7 +139,12 @@ export async function compositeCanvasAsync(
): Promise<{ canvas: HTMLCanvasElement; usedGpu: boolean }> {
await hydratePagedTilesForLayers(tileGrid, layers, true);
- if (typeof document !== 'undefined' && dimensions.width > 0 && dimensions.height > 0) {
+ if (
+ typeof document !== 'undefined' &&
+ dimensions.width > 0 &&
+ dimensions.height > 0 &&
+ performanceManager.getConfig().renderBackend !== 'canvas2d'
+ ) {
const requestedTileSize = options?.tileSize ?? INK_DEFAULT_TILE_EXPORT_SIZE;
const probeCanvas = document.createElement('canvas');
probeCanvas.width = Math.min(requestedTileSize, dimensions.width);
diff --git a/src/utils/saveManager/inkParse.ts b/src/utils/saveManager/inkParse.ts
index 252deed..4dd4f33 100644
--- a/src/utils/saveManager/inkParse.ts
+++ b/src/utils/saveManager/inkParse.ts
@@ -1,6 +1,7 @@
import { unzipSync } from 'fflate';
import { CanvasColorMode, LayerItem, hasTileBackedLayer } from '../../types/editor';
import { SparseTileGrid, TileBuffer, TileFormat } from '../tileEngine';
+import { extractWorkTimeMsFromManifest } from '../artworkTimeTracker';
import {
CHUNK_YIELD_INTERVAL,
MAX_DOCUMENT_DIM,
@@ -236,6 +237,7 @@ export async function parseInkZipBytes(
perspectiveRuler: parsedManifest.perspectiveRuler ?? null,
animationTimeline: parsedManifest.animationTimeline ?? null,
timelapse: parsedManifest.timelapse ?? null,
+ workTimeMs: extractWorkTimeMsFromManifest(parsedManifest),
previewBytes,
previewDataUrl,
};
diff --git a/src/utils/saveManager/inkSerialize.ts b/src/utils/saveManager/inkSerialize.ts
index 6fb1cb9..cd10bd0 100644
--- a/src/utils/saveManager/inkSerialize.ts
+++ b/src/utils/saveManager/inkSerialize.ts
@@ -8,6 +8,7 @@ import {
getTileByteSize,
} from '../tileEngine';
import { documentStore } from '../documentStore';
+import { sanitizeWorkTimeMs } from '../artworkTimeTracker';
import {
CHUNK_YIELD_INTERVAL,
InkProjectManifest,
@@ -157,6 +158,7 @@ export async function serializeInkProject(
perspectiveRuler: data.perspectiveRuler ?? null,
animationTimeline: data.animationTimeline ?? null,
timelapse: data.timelapse ?? null,
+ workTimeMs: sanitizeWorkTimeMs(data.workTimeMs),
preview: preview ? { path: 'preview.png', width: preview.width, height: preview.height } : null,
savedAt: Date.now(),
};
diff --git a/src/utils/saveManager/types.ts b/src/utils/saveManager/types.ts
index 6d46419..8178d87 100644
--- a/src/utils/saveManager/types.ts
+++ b/src/utils/saveManager/types.ts
@@ -39,6 +39,7 @@ export interface SaveDocumentData {
perspectiveRuler?: PerspectiveRuler | null;
animationTimeline?: AnimationTimeline | null;
timelapse?: InkTimelapseMetadata | null;
+ workTimeMs?: number;
onProgress?: (progress: SaveProgress) => void;
compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
}
@@ -58,6 +59,7 @@ export interface InkProjectManifest {
perspectiveRuler?: PerspectiveRuler | null;
animationTimeline?: AnimationTimeline | null;
timelapse?: InkTimelapseMetadata | null;
+ workTimeMs?: number;
preview: { path: string; width: number; height: number } | null;
savedAt: number;
}
@@ -75,6 +77,7 @@ export interface ParsedInkProject {
perspectiveRuler?: PerspectiveRuler | null;
animationTimeline?: AnimationTimeline | null;
timelapse?: InkTimelapseMetadata | null;
+ workTimeMs?: number;
previewBytes?: Uint8Array | null;
previewDataUrl?: string;
}
diff --git a/src/utils/undoCache.ts b/src/utils/undoCache.ts
index d8a0f83..e15daa0 100644
--- a/src/utils/undoCache.ts
+++ b/src/utils/undoCache.ts
@@ -113,6 +113,14 @@ export class UndoCacheManager {
return this.compressedRamCache.size;
}
+ public getCompressedRamBytes(): number {
+ let total = 0;
+ for (const buf of this.compressedRamCache.values()) {
+ total += buf.byteLength;
+ }
+ return total;
+ }
+
public isOffloaded(itemId: string): boolean {
return this.diskCachedIds.has(itemId) || this.compressedRamCache.has(itemId);
}
diff --git a/src/utils/workspacePresets.ts b/src/utils/workspacePresets.ts
index 1734e24..1d10ae3 100644
--- a/src/utils/workspacePresets.ts
+++ b/src/utils/workspacePresets.ts
@@ -82,7 +82,7 @@ export const DEFAULT_ILLUSTRATION_LAYOUT: WorkspaceLayout = {
groups: [
{
id: 'grp-navigator-subview',
- panelIds: ['navigator', 'sub-view'],
+ panelIds: ['navigator', 'sub-view', 'info'],
activePanelId: 'navigator',
heightRatio: 0.26,
},
@@ -178,7 +178,7 @@ export const MANGA_STUDIO_LAYOUT: WorkspaceLayout = {
groups: [
{
id: 'grp-manga-nav-subview',
- panelIds: ['navigator', 'sub-view'],
+ panelIds: ['navigator', 'sub-view', 'info'],
activePanelId: 'navigator',
heightRatio: 0.26,
},
@@ -236,7 +236,7 @@ export const MINIMALIST_TABLET_LAYOUT: WorkspaceLayout = {
groups: [
{
id: 'grp-tablet-layers',
- panelIds: ['navigator', 'sub-view', 'layers', 'history', 'auto-actions', 'quick-access'],
+ panelIds: ['navigator', 'sub-view', 'info', 'layers', 'history', 'auto-actions', 'quick-access'],
activePanelId: 'layers',
heightRatio: 1,
},
@@ -718,6 +718,28 @@ function sanitizeCommandBarIds(raw: unknown): CommandActionId[] {
return out;
}
+const AUTO_MIGRATED_PANELS: DockPanelId[] = ['info'];
+
+function attachMigratedPanelToLayout(
+ layout: WorkspaceLayout,
+ panelId: DockPanelId
+): WorkspaceLayout {
+ if (findPanelLocation(layout, panelId)) return layout;
+ const anchor =
+ findPanelLocation(layout, 'navigator') ?? findPanelLocation(layout, 'sub-view');
+ if (anchor) {
+ const next = cloneLayout(layout);
+ const cols = anchor.side === 'left' ? next.leftDocks : next.rightDocks;
+ const col = cols.find((c) => c.id === anchor.colId);
+ const grp = col?.groups.find((g) => g.id === anchor.groupId);
+ if (grp && !grp.panelIds.includes(panelId)) {
+ grp.panelIds.push(panelId);
+ return next;
+ }
+ }
+ return togglePanelInLayout(layout, panelId);
+}
+
export function createDefaultPersistedWorkspace(): PersistedWorkspaceState {
return {
version: 1,
@@ -730,6 +752,7 @@ export function createDefaultPersistedWorkspace(): PersistedWorkspaceState {
showStatusBar: true,
showDocumentTabs: true,
showCommandBar: true,
+ migratedPanels: [...AUTO_MIGRATED_PANELS],
};
}
@@ -752,8 +775,26 @@ export function loadWorkspaceState(): PersistedWorkspaceState {
? (parsed.activePreset as WorkspacePresetId)
: 'default-illustration';
- const layout = sanitizeLayout(parsed.layout) ?? fallback.layout;
- const savedCustomLayout = sanitizeLayout(parsed.savedCustomLayout);
+ const existingMigrated = new Set<DockPanelId>(
+ Array.isArray(parsed.migratedPanels)
+ ? parsed.migratedPanels.filter(
+ (id): id is DockPanelId => typeof id === 'string' && VALID_PANEL_SET.has(id)
+ )
+ : []
+ );
+
+ let layout = sanitizeLayout(parsed.layout) ?? fallback.layout;
+ let savedCustomLayout = sanitizeLayout(parsed.savedCustomLayout);
+ for (const panelId of AUTO_MIGRATED_PANELS) {
+ if (!existingMigrated.has(panelId)) {
+ layout = attachMigratedPanelToLayout(layout, panelId);
+ if (savedCustomLayout) {
+ savedCustomLayout = attachMigratedPanelToLayout(savedCustomLayout, panelId);
+ }
+ existingMigrated.add(panelId);
+ }
+ }
+
const quickAccessItems = sanitizeQuickAccessItems(parsed.quickAccessItems);
const quickAccessViewMode: QuickAccessViewMode =
parsed.quickAccessViewMode === 'list' ? 'list' : 'grid';
@@ -770,6 +811,7 @@ export function loadWorkspaceState(): PersistedWorkspaceState {
showStatusBar: typeof parsed.showStatusBar === 'boolean' ? parsed.showStatusBar : true,
showDocumentTabs: typeof parsed.showDocumentTabs === 'boolean' ? parsed.showDocumentTabs : true,
showCommandBar: typeof parsed.showCommandBar === 'boolean' ? parsed.showCommandBar : true,
+ migratedPanels: Array.from(existingMigrated),
};
} catch {
return fallback;