From 73e15193decc79776e37eba8ca835c6c2ca047e3 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 07:11:53 +0000 Subject: [PATCH] =?UTF-8?q?Assets:=20saved=20brushes=20as=20tiles;=20savin?= =?UTF-8?q?g=20the=20current=20brush=20moves=20to=20Properties=20=E2=80=BA?= =?UTF-8?q?=20Brush=20=E2=80=BA=20Preset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/brush_preset_save.rs | 34 ++++++++++++++ crates/ui-egui/src/dock.rs | 4 ++ crates/ui-egui/src/i18n/ar.rs | 2 - crates/ui-egui/src/i18n/de.rs | 2 - crates/ui-egui/src/i18n/es.rs | 2 - crates/ui-egui/src/i18n/fr.rs | 2 - crates/ui-egui/src/i18n/it.rs | 2 - crates/ui-egui/src/i18n/ja.rs | 2 - crates/ui-egui/src/i18n/ko.rs | 2 - crates/ui-egui/src/i18n/pt_br.rs | 2 - crates/ui-egui/src/i18n/zh_hans.rs | 2 - crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/shelf.rs | 62 +++++-------------------- crates/ui-egui/src/shelf_entry.rs | 24 ++++++++-- crates/ui-egui/src/shelf_preview.rs | 28 +++++++++++ crates/ui-egui/src/thumbs.rs | 5 ++ 16 files changed, 105 insertions(+), 72 deletions(-) create mode 100644 crates/ui-egui/src/brush_preset_save.rs diff --git a/crates/ui-egui/src/brush_preset_save.rs b/crates/ui-egui/src/brush_preset_save.rs new file mode 100644 index 00000000..7bc0faaa --- /dev/null +++ b/crates/ui-egui/src/brush_preset_save.rs @@ -0,0 +1,34 @@ +//! Saving the current brush as a preset (Properties › Brush › Preset); presets show on the shelf's Brushes tab + +use egui::Ui; +use serde_json::json; +use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; + +use crate::TextureCraftApp; +use crate::i18n::tr; + +/// The preset name field's width in points +const NAME_WIDTH: f32 = 110.0; + +/// A name field and a button that saves the current brush under that name +pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) { + let dir = crate::user_dir("brushes"); + ui.horizontal(|ui| { + let name_id = ui.make_persistent_id("brush_preset_name"); + let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default(); + ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(NAME_WIDTH)); + + let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim()); + if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { + let path = dir.join(format!("{file}.{BRUSH_EXT}")); + // A folder that can't be made fails the save, which reports it + let _ = std::fs::create_dir_all(&dir); + if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { + new_name.clear(); + app.brushes = None; + } + } + + ui.data_mut(|data| data.insert_temp(name_id, new_name)); + }); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 53932f4e..61d39ced 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1583,6 +1583,10 @@ fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { } *brush = brush.sanitized(); + + // Presets are files, which the browser doesn't have + #[cfg(not(target_arch = "wasm32"))] + section(ui, "sec_brush_preset", tr("Preset"), false, |ui| crate::brush_preset_save::row(app, ui)); } /// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 95373f3d..68e95d5c 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -919,8 +919,6 @@ pub const TABLE: &[(&str, &str)] = &[ "استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص", ), ("Brushes", "الفرش"), - ("My brushes", "فرشي"), - ("Use this brush (keeps its size)", "استخدام هذه الفرشاة (مع الحفاظ على حجمها)"), ("Brush name", "اسم الفرشاة"), ("Save current brush", "حفظ الفرشاة الحالية"), ("Start window", "نافذة البدء"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 0f7e7c35..e0f15ab8 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -959,8 +959,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", ), ("Brushes", "Pinsel"), - ("My brushes", "Meine Pinsel"), - ("Use this brush (keeps its size)", "Diesen Pinsel verwenden (Größe bleibt)"), ("Brush name", "Pinselname"), ("Save current brush", "Aktuellen Pinsel speichern"), ("Start window", "Startfenster"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b5361801..2bd6fc75 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -947,8 +947,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", ), ("Brushes", "Pinceles"), - ("My brushes", "Mis pinceles"), - ("Use this brush (keeps its size)", "Usar este pincel (conserva su tamaño)"), ("Brush name", "Nombre del pincel"), ("Save current brush", "Guardar el pincel actual"), ("Start window", "Ventana de inicio"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 00b8c2af..73c6b199 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -968,8 +968,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", ), ("Brushes", "Pinceaux"), - ("My brushes", "Mes pinceaux"), - ("Use this brush (keeps its size)", "Utiliser ce pinceau (garde sa taille)"), ("Brush name", "Nom du pinceau"), ("Save current brush", "Enregistrer le pinceau actuel"), ("Start window", "Fenêtre de démarrage"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index e067cf67..d785fb4a 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -953,8 +953,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", ), ("Brushes", "Pennelli"), - ("My brushes", "I miei pennelli"), - ("Use this brush (keeps its size)", "Usa questo pennello (mantiene la dimensione)"), ("Brush name", "Nome del pennello"), ("Save current brush", "Salva il pennello attuale"), ("Start window", "Finestra iniziale"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 0e60e132..c437a9a5 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -941,8 +941,6 @@ pub const TABLE: &[(&str, &str)] = &[ "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", ), ("Brushes", "ブラシ一覧"), - ("My brushes", "マイブラシ"), - ("Use this brush (keeps its size)", "このブラシを使用(サイズはそのまま)"), ("Brush name", "ブラシ名"), ("Save current brush", "現在のブラシを保存"), ("Start window", "スタートウィンドウ"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 7f80b6be..df46e2f1 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -929,8 +929,6 @@ pub const TABLE: &[(&str, &str)] = &[ "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", ), ("Brushes", "브러시 목록"), - ("My brushes", "내 브러시"), - ("Use this brush (keeps its size)", "이 브러시 사용 (크기 유지)"), ("Brush name", "브러시 이름"), ("Save current brush", "현재 브러시 저장"), ("Start window", "시작 창"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index e5b023af..87b0fc93 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -944,8 +944,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", ), ("Brushes", "Pincéis"), - ("My brushes", "Meus pincéis"), - ("Use this brush (keeps its size)", "Usar este pincel (mantém o tamanho)"), ("Brush name", "Nome do pincel"), ("Save current brush", "Salvar o pincel atual"), ("Start window", "Janela inicial"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index ef4209e4..3f1e89f7 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -884,8 +884,6 @@ pub const TABLE: &[(&str, &str)] = &[ "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", ), ("Brushes", "笔刷库"), - ("My brushes", "我的笔刷"), - ("Use this brush (keeps its size)", "使用此笔刷(保留大小)"), ("Brush name", "笔刷名称"), ("Save current brush", "保存当前笔刷"), ("Start window", "启动窗口"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c47ddd4f..cbfc80a8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,6 +10,8 @@ mod bake_job; pub mod bake_mode; mod bake_scene; +#[cfg(not(target_arch = "wasm32"))] +mod brush_preset_save; mod color_selection_editor; pub mod control; mod decal_drop; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 0ff1cc6a..2e8f6a82 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -249,6 +249,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let filter = app.ui.shelf_filter.to_lowercase(); let shown_tab = TABS[tab].0; + scan_brushes(app); // Searching shows matches from every tab in one grid let mut entries: Vec = ShelfEntry::all(app).into_iter().filter(|entry| (searching || entry.tab() == shown_tab) && entry.matches(&filter)).collect(); @@ -267,9 +268,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { if searching || shown_tab == Tab::Smart { library(app, ui, &filter); } - if searching || shown_tab == Tab::Brushes { - my_brushes(app, ui, &filter); - } }); drag_preview(&ctx); } @@ -364,60 +362,24 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { #[cfg(target_arch = "wasm32")] fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} -/// The user's saved brush presets (desktop brushes folder) and saving the current brush there. +/// Read the user's saved brush presets (desktop brushes folder) unless they are already listed #[cfg(not(target_arch = "wasm32"))] -fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { +fn scan_brushes(app: &mut TextureCraftApp) { use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; - let dir = crate::user_dir("brushes"); - if app.brushes.is_none() { - let mut files: Vec = std::fs::read_dir(&dir) - .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == BRUSH_EXT)).collect()) - .unwrap_or_default(); - files.sort(); - app.brushes = Some(files); - } - let files = app.brushes.clone().unwrap_or_default(); - let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("brush").to_string(); - let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect(); - if !filter.is_empty() && shown.is_empty() { + + if app.brushes.is_some() { return; } - ui.horizontal(|ui| { - header(ui, tr("My brushes")); - if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() { - app.brushes = None; - } - }); - for f in shown { - if ui - .add(egui::Button::selectable(false, format!("{} {}", ic::PAINT_BRUSH_BROAD, name(f)))) - .on_hover_text(tr("Use this brush (keeps its size)")) - .clicked() - { - app.run("brush.preset.load", json!({"path": f.display().to_string()})); - } - } - ui.horizontal(|ui| { - let id = ui.make_persistent_id("brush_preset_name"); - let mut new_name: String = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); - ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(110.0)); - let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim()); - if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { - let path = dir.join(format!("{file}.{BRUSH_EXT}")); - // A folder that can't be made fails the save, which reports it. - let _ = std::fs::create_dir_all(&dir); - if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { - new_name.clear(); - app.brushes = None; - } - } - ui.data_mut(|d| d.insert_temp(id, new_name)); - }); - ui.add_space(6.0); + + let mut files: Vec = std::fs::read_dir(crate::user_dir("brushes")) + .map(|dir| dir.flatten().map(|entry| entry.path()).filter(|path| path.extension().is_some_and(|extension| extension == BRUSH_EXT)).collect()) + .unwrap_or_default(); + files.sort(); + app.brushes = Some(files); } #[cfg(target_arch = "wasm32")] -fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} +fn scan_brushes(_: &mut TextureCraftApp) {} /// The Textures tab's import button, and a hint while the project has no images fn import_images(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, empty: bool) { diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index c44ecb1c..a8d4cacc 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -1,5 +1,7 @@ //! One asset on the shelf: its name, the tab it belongs to, and how it previews, drags and applies +use std::path::PathBuf; + use serde_json::json; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::core::project::ENVIRONMENTS; @@ -14,6 +16,9 @@ use crate::i18n::tr; use crate::shelf::{Asset, Tab, apply}; use crate::shelf_preview::ShelfPreview; +/// The name of a saved brush whose file name isn't text +const SAVED_BRUSH_NAME: &str = "brush"; + /// A shelf tile's asset #[derive(Clone)] pub(crate) enum ShelfEntry { @@ -21,6 +26,8 @@ pub(crate) enum ShelfEntry { SmartMask(&'static SmartMask), Filter(&'static FilterDef), Brush(&'static BrushPreset), + /// A brush preset file the user saved + SavedBrush(PathBuf), Alpha(&'static LibraryAlpha), Procedural(ProceduralKind), /// A built-in lighting environment, by name @@ -30,7 +37,7 @@ pub(crate) enum ShelfEntry { } impl ShelfEntry { - /// Every built-in asset and the project's images + /// Every built-in asset, the user's saved brushes and the project's images pub(crate) fn all(app: &TextureCraftApp) -> Vec { let built_in = MATERIALS .iter() @@ -41,7 +48,8 @@ impl ShelfEntry { .chain(alphas::library().iter().map(ShelfEntry::Alpha)) .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)) .chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment)); - built_in.chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() + let saved = app.brushes.iter().flatten().cloned().map(ShelfEntry::SavedBrush); + built_in.chain(saved).chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() } /// The tab that lists the asset @@ -51,7 +59,7 @@ impl ShelfEntry { ShelfEntry::Material(_) => Tab::Materials, ShelfEntry::SmartMask(_) => Tab::Masks, ShelfEntry::Filter(_) => Tab::Filters, - ShelfEntry::Brush(_) => Tab::Brushes, + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) => Tab::Brushes, ShelfEntry::Alpha(_) => Tab::Alphas, ShelfEntry::Procedural(_) => Tab::Procedurals, ShelfEntry::Environment(_) => Tab::Environments, @@ -66,6 +74,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => format!("mask:{}", mask.id), ShelfEntry::Filter(filter) => format!("filter:{}", filter.id), ShelfEntry::Brush(preset) => format!("brush:{}", preset.id), + ShelfEntry::SavedBrush(path) => format!("saved-brush:{}", path.display()), ShelfEntry::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfEntry::Procedural(kind) => format!("procedural:{kind:?}"), ShelfEntry::Environment(name) => format!("environment:{name}"), @@ -77,6 +86,7 @@ impl ShelfEntry { pub(crate) fn label(&self) -> &str { match self { ShelfEntry::Material(material) => material.label, + ShelfEntry::SavedBrush(path) => path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_BRUSH_NAME), ShelfEntry::SmartMask(mask) => mask.label, ShelfEntry::Filter(filter) => tr(filter.label), ShelfEntry::Brush(preset) => preset.label, @@ -91,6 +101,7 @@ impl ShelfEntry { pub(crate) fn matches(&self, filter: &str) -> bool { let texts: &[&str] = match self { ShelfEntry::Material(material) => &[material.label, material.category, material.id], + ShelfEntry::SavedBrush(_) => &[self.label()], ShelfEntry::SmartMask(mask) => &[mask.label, mask.id], ShelfEntry::Filter(filter) => &[filter.label, filter.group, filter.id, tr(filter.label), tr(filter.group)], ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id], @@ -109,6 +120,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id), ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id), ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), + ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path), ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name), @@ -126,6 +138,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id), ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id), ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset), + ShelfEntry::SavedBrush(path) => ShelfPreview::SavedBrush(path.clone()), ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), ShelfEntry::Environment(name) => ShelfPreview::Environment(name), @@ -141,7 +154,7 @@ impl ShelfEntry { ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)), ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)), ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())), - ShelfEntry::Brush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None, + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None, } } @@ -163,6 +176,9 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => { app.run("brush.preset.apply", json!({"preset": preset.id})); } + ShelfEntry::SavedBrush(path) => { + app.run("brush.preset.load", json!({"path": path.display().to_string()})); + } ShelfEntry::Procedural(kind) => { app.run("layer.add.fill", json!({"name": kind.label()})); app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": kind.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index c4b4ae36..076ea14f 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -1,5 +1,6 @@ //! Shelf assets and their preview renderers +use std::path::PathBuf; use std::sync::Arc; use egui::ColorImage; @@ -13,6 +14,10 @@ use texturecraft_engine::preview; use crate::preview_image::{alpha_image, environment_image, image_preview, procedural_image, sphere_image, stroke_preview}; +/// Larger brush preset files aren't read (the `brush.preset.load` command's limit) +#[cfg(not(target_arch = "wasm32"))] +const MAX_SAVED_BRUSH_BYTES: u64 = 1 << 20; + /// The asset a shelf tile previews pub enum ShelfPreview { /// A built-in plain material on a sphere @@ -29,6 +34,8 @@ pub enum ShelfPreview { Alpha(&'static LibraryAlpha), /// A brush preset's stroke along an S curve Brush(&'static BrushPreset), + /// A brush preset file the user saved, its stroke along an S curve + SavedBrush(PathBuf), /// An image resource by name Image(String, Arc), /// A built-in lighting environment's panorama @@ -54,6 +61,7 @@ impl ShelfPreview { ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), + ShelfPreview::SavedBrush(path) => format!("saved-brush:{}", path.display()), ShelfPreview::Image(name, _) => format!("image:{name}"), ShelfPreview::Environment(name) => format!("environment:{name}"), } @@ -69,12 +77,32 @@ impl ShelfPreview { ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), + ShelfPreview::SavedBrush(path) => Some(stroke_preview(&saved_brush(path)?, size)), ShelfPreview::Image(_, image) => Some(image_preview(image, size)), ShelfPreview::Environment(name) => Some(environment_image(name, size)), } } } +/// A saved brush preset's settings; None when the file can't be read (or in the browser, which has no files) +#[cfg(not(target_arch = "wasm32"))] +fn saved_brush(path: &std::path::Path) -> Option { + use std::io::Read as _; + + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|file| file.take(MAX_SAVED_BRUSH_BYTES + 1).read_to_end(&mut bytes)).ok()?; + if bytes.len() as u64 > MAX_SAVED_BRUSH_BYTES { + return None; + } + + serde_json::from_slice::(&bytes).ok().map(|settings| settings.sanitized()) +} + +#[cfg(target_arch = "wasm32")] +fn saved_brush(_: &std::path::Path) -> Option { + None +} + #[cfg(test)] mod tests { use texturecraft_engine::filter_lib::FILTERS; diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 3aa97413..a6bd93cb 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -217,6 +217,11 @@ impl Thumbs { self.shelf(ctx, ShelfPreview::Environment(name), SWATCH_PX) } + /// A saved brush preset's stroke along an S curve; None while it renders, empty when the file is unreadable + pub fn saved_brush(&mut self, ctx: &egui::Context, path: &std::path::Path) -> Option { + self.shelf(ctx, ShelfPreview::SavedBrush(path.to_path_buf()), SWATCH_PX) + } + /// A brush preset's stroke along an S curve pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX)