Merge pull request #844 from Rebornim/feat/assets-pass-2

Assets panel pass 2: a right-click menu on every asset, favorites, a drag ghost that says where it can drop, automatic updates and a second Assets panel
This commit is contained in:
Chris Hassebrook authored and GitHub committed 2026-11-27 22:54:04 -05:00
commit 216b199c5d
41 files changed
+2718 -110

No files matched your search

+42
View File
@@ -739,6 +739,15 @@ impl Source {
}
}
/// [`Source::images`], to rename them
pub fn images_mut(&mut self) -> Vec<&mut String> {
match self {
Source::Image { name, .. } => vec![name],
Source::Procedural { pattern, .. } => pattern.tile.iter_mut().flat_map(|tile| tile.images_mut()).collect(),
Source::Uniform(_) | Source::Anchor { .. } => Vec::new(),
}
}
/// The gradient map stops of a procedural or anchor source (empty: none).
pub fn ramp(&self) -> &[[f32; 3]] {
match self {
@@ -844,6 +853,12 @@ pub struct LinkPreset {
}
impl Fill {
/// The image resource names the fill holds, to rename them: its sources' and, when linked, its package and cooked outputs
pub fn images_mut(&mut self) -> impl Iterator<Item = &mut String> {
let link = self.link.iter_mut().map(|link| &mut **link).flat_map(|link| std::iter::once(&mut link.package).chain(link.outputs.values_mut()));
self.sources.values_mut().flat_map(Source::images_mut).chain(link)
}
/// Value used for `c` when the fill has no source for it: the channel default.
pub fn source(&self, c: Channel) -> Source {
self.sources.get(&c).cloned().unwrap_or_else(|| Source::uniform_of(c))
@@ -1287,6 +1302,17 @@ impl Generator {
self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro)
}
/// [`Generator::sources`], to rename the images they read
pub fn sources_mut(&mut self) -> impl Iterator<Item = &mut Source> {
let grayscale = match self.controls.as_deref_mut() {
Some(KindControls::Grayscale(grayscale)) if self.kind == GeneratorKind::GrayscaleConversion => grayscale.source.as_mut(),
_ => None,
};
let micro = self.micro.iter_mut().flat_map(|micro| micro.sources_mut()).chain(grayscale);
let texture = self.texture.as_mut().and_then(|texture| texture.source.as_mut());
self.inputs.values_mut().chain(texture).chain(self.grunge.as_mut()).chain(micro)
}
/// The micro details as saved, when the generator computes with them: with a slot switched on, except a micro detail saved before Micro Details on a generator still on the earlier model, which [`Generator::earlier_micro`] reads (bring them into range before use: saved files are not trusted)
pub fn micro_in_use(&self) -> Option<&MicroDetails> {
self.micro.as_deref().filter(|micro| micro.in_use(self.kind) && !(micro.earlier && self.on_earlier_model()))
@@ -2348,6 +2374,17 @@ impl EffectKind {
sources.into_iter().flat_map(Source::images).chain(id_map)
}
/// [`EffectKind::images_read`], to rename them
pub fn images_mut(&mut self) -> Vec<&mut String> {
match self {
EffectKind::Fill { source, .. } => source.images_mut(),
EffectKind::Material(fill) => fill.images_mut().collect(),
EffectKind::Generator(generator) => generator.sources_mut().flat_map(Source::images_mut).collect(),
EffectKind::ColorSelection(selection) => selection.id_map.iter_mut().collect(),
_ => Vec::new(),
}
}
/// Reads a channel of the layer or of the stack below it (a compare mask's layer sides)
pub fn reads_stack(&self) -> bool {
matches!(self, EffectKind::Compare { left, right, .. } if left.reads_stack() || right.reads_stack())
@@ -2410,6 +2447,11 @@ impl Effect {
self.kind.images_read().chain(self.inputs.values().flat_map(Source::images))
}
/// [`Effect::images_read`], to rename them
pub fn images_mut(&mut self) -> impl Iterator<Item = &mut String> {
self.kind.images_mut().into_iter().chain(self.inputs.values_mut().flat_map(Source::images_mut))
}
/// Whether a source of the effect, or one of its image inputs, reads anchor point `anchor` (any anchor point when None)
pub fn reads(&self, anchor: Option<LayerId>) -> bool {
self.kind.reads(anchor) || self.inputs.values().any(|source| source.reads_anchor(anchor))
+5
View File
@@ -119,6 +119,11 @@ impl MicroDetails {
self.height_source.iter().chain(self.normal_source.as_ref())
}
/// [`MicroDetails::sources`], to rename the images they read
pub fn sources_mut(&mut self) -> impl Iterator<Item = &mut Source> {
self.height_source.iter_mut().chain(self.normal_source.as_mut())
}
/// Every value brought into its range, non-finite ones to the defaults of `kind`
pub fn clamped(self, kind: GeneratorKind) -> MicroDetails {
let Some(defaults) = MicroDetails::defaults(kind) else { return self };
+5
View File
@@ -202,6 +202,11 @@ impl TileGenerator {
pub fn images(&self) -> impl Iterator<Item = &str> {
self.inputs.iter().chain(&self.background_image).map(String::as_str)
}
/// [`TileGenerator::images`], to rename them
pub fn images_mut(&mut self) -> impl Iterator<Item = &mut String> {
self.inputs.iter_mut().chain(&mut self.background_image)
}
}
impl Default for TileGenerator {
+54
View File
@@ -146,6 +146,15 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("brush.preset.delete", "Delete a brush preset", [], None, "{name} — one of the user's presets (built-ins are read-only)", always, delete),
cmd!("brush.preset.save", "Save brush preset", [], None, "{path} — the current brush as a .tcbrush file", always, save),
cmd!("brush.preset.load", "Load brush preset", [], None, "{path} — a .tcbrush file's stroke on the brush, keeping the size", always, load),
cmd!(
"brush.preset.export",
"Export brush preset",
[],
None,
"{name, path} — one of the user's presets as a .tcbrush file, as its library folder holds it",
always,
export
),
]
}
@@ -325,6 +334,26 @@ fn load(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("brush.preset.load", "file paths are not available in the browser"))
}
/// Writes user preset `name` to `path` as the library folder holds it
#[cfg(not(target_arch = "wasm32"))]
fn export(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "brush.preset.export";
let name = name_param(params, "name", CMD)?;
let path = strp(params, "path").ok_or_else(|| bad(CMD, "`path` is required"))?;
let preset = session.brush_presets.find(&name).and_then(|index| session.brush_presets.list.get(index));
let preset = preset.ok_or_else(|| bad(CMD, format!("no user brush preset `{name}`")))?;
let bytes = serde_json::to_vec_pretty(preset).map_err(|error| bad(CMD, error.to_string()))?;
std::fs::write(path, bytes).map_err(|error| bad(CMD, format!("cannot write {path}: {error}")))?;
Ok(json!({ "path": path }))
}
#[cfg(target_arch = "wasm32")]
fn export(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("brush.preset.export", "file paths are not available in the browser"))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -406,6 +435,31 @@ mod tests {
assert_eq!(names(&test_session), ["a/b"]);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_exported_preset_loads_as_the_same_brush() {
let dir = std::env::temp_dir().join(format!("tc-brush-export-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut test_session = session();
run(&mut test_session, "tool.brush", json!({"size": 41, "hardness": 70})).unwrap();
run(&mut test_session, "brush.preset.store", json!({"name": "Ink pen"})).unwrap();
run(&mut test_session, "tool.brush", json!({"size": 5})).unwrap();
let path = dir.join("shared.tcbrush");
run(&mut test_session, "brush.preset.export", json!({"name": "ink pen", "path": path.to_str().unwrap()})).unwrap();
let mut fresh = session();
assert!(fresh.load_brush_presets(dir.clone()).is_empty());
assert_eq!(names(&fresh), ["Ink pen"], "the file carries the preset's name");
assert_eq!(fresh.brush_presets.list[0].brush, test_session.brush_presets.list[0].brush, "the stored brush, not the current one");
assert!(
run(&mut test_session, "brush.preset.export", json!({"name": "Airbrush", "path": path.to_str().unwrap()})).is_err(),
"built-ins are not exported"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn presets_persist_in_the_folder() {
@@ -45,6 +45,12 @@ impl UserBrushes {
self.dir.as_ref().map(|directory| directory.join(format!("{}.{BRUSH_EXT}", sanitize_file_stem(name.trim()))))
}
/// The file user preset `name` is mirrored to (None: no such preset, or the presets live in memory only)
pub fn file_for(&self, name: &str) -> Option<std::path::PathBuf> {
let preset = self.list.get(self.find(name)?)?;
preset.file.clone().or_else(|| self.file_of(&preset.name))
}
/// The file a preset named `name` that was never written would have.
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn file_of(&self, name: &str) -> Option<std::path::PathBuf> {
+15
View File
@@ -385,6 +385,21 @@ pub(crate) fn path_images(kind: &EffectKind) -> Vec<String> {
shapes.iter().filter_map(|shape| read_paint(shape).ok()?.mask_image).collect()
}
/// Points the stored paths of `kind` that paint with image resource `from` (as mask image or brush alpha) at `to`
pub(crate) fn rename_path_images(kind: &mut EffectKind, from: &str, to: &str) {
let EffectKind::Path(shapes) = kind else { return };
for shape in shapes {
for pointer in ["/mask_image", "/brush/alpha_image"] {
if let Some(image) = shape.paint.pointer_mut(pointer)
&& image.as_str() == Some(from)
{
*image = serde_json::Value::String(to.to_string());
}
}
}
}
/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`])
fn state_of(shape: &PathShape) -> PathState {
let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect();
+242 -7
View File
@@ -24,6 +24,16 @@ pub fn specs() -> Vec<CommandSpec> {
),
cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))),
cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove),
cmd!("resource.export", "Export resource", [], None, "{name, path} — the resource's file as it was imported", always, export),
cmd!(
"resource.rename",
"Rename resource",
[],
None,
"{name, to} — everything that uses the image follows it; `to` keeps the old extension when it has none",
always,
rename
),
cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused),
cmd!(
"layer.add.image",
@@ -292,23 +302,134 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// Drop resources unused by layers, mesh maps, paint tools or the environment (one undo step)
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
let mut used = Vec::new();
for set in &s.doc.project.texture_sets {
for root in &set.stack {
crate::material_lib::images_used(&s.doc.project, *root, &mut used, 0);
/// Writes resource `name`'s bytes, as imported, to `path`
#[cfg(not(target_arch = "wasm32"))]
fn export(s: &mut Session, p: &Value) -> Result<Value> {
let command = "resource.export";
let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?;
let path = strp(p, "path").ok_or_else(|| bad(command, "`path` is required"))?;
let bytes = s.doc.resources.get(name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?;
std::fs::write(path, bytes.as_slice()).map_err(|error| bad(command, format!("cannot write {path}: {error}")))?;
Ok(json!({ "path": path }))
}
#[cfg(target_arch = "wasm32")]
fn export(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("resource.export", "file paths are not available in the browser"))
}
/// Renames image resource `name` to `to` and every reference to it, in one undo step
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
let command = "resource.rename";
let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?.to_string();
let to = strp(p, "to").ok_or_else(|| bad(command, "`to` is required"))?.trim();
if !s.doc.resources.contains_key(&name) {
return Err(bad(command, format!("no resource `{name}`")));
}
let mut to = sanitize_resource_name(to);
if std::path::Path::new(&to).extension().is_none()
&& let Some(extension) = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str())
{
// The stem gives way, so a long name keeps its extension
let stem_room = MAX_RESOURCE_NAME_LEN.saturating_sub(extension.len() + 1);
to.truncate(stem_room);
to = format!("{to}.{extension}");
}
if to == name {
return Ok(json!({ "name": name }));
}
if s.doc.resources.contains_key(&to) || crate::fill_alpha::library_alpha_of(&to).is_some() {
return Err(bad(command, format!("a resource named `{to}` exists already")));
}
s.edit("Rename resource", |s| {
let bytes = s.doc.resources.remove(&name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?;
s.doc.resources.insert(to.clone(), bytes);
// The Resources Updater keeps following the file the image came from
if let Some(source) = s.doc.project.resource_sources.remove(&name) {
s.doc.project.resource_sources.insert(to.clone(), source);
}
rename_references(&mut s.doc.project, &name, &to);
// Refuse rather than leave a reference this rename does not know about pointing at nothing
if project_images(&s.doc.project).contains(&name) {
return Err(bad(command, format!("`{name}` is used somewhere it can't be renamed")));
}
Ok(())
})?;
for tool_image in s.tool_images_mut().filter(|tool_image| **tool_image == name) {
tool_image.clone_from(&to);
}
// The decoded pixels are the same: they move instead of decoding again
if let Some(image) = s.images.remove(&name) {
s.images.insert(to.clone(), image);
}
if s.library_alphas.remove(&name) {
s.library_alphas.insert(to.clone());
}
s.path_cache = None;
s.sync_images();
Ok(json!({ "name": to }))
}
/// Points every layer, effect, stored path and the environment that read image resource `from` at `to`
fn rename_references(project: &mut texturecraft_core::Project, from: &str, to: &str) {
for layer in project.layers.values_mut() {
let fill_images: Vec<&mut String> = match &mut layer.kind {
LayerKind::Fill(fill) => fill.images_mut().collect(),
_ => Vec::new(),
};
let effects = layer.mask.iter_mut().flat_map(|mask| mask.effects.iter_mut()).chain(&mut layer.content_effects);
let mut images = fill_images;
for effect in effects {
crate::path_tool::rename_path_images(&mut effect.kind, from, to);
images.extend(effect.images_mut());
}
for image in images.into_iter().filter(|image| *image == from) {
*image = to.to_string();
}
}
if project.display.environment_resource() == Some(from) {
project.display.environment = format!("{}{to}", texturecraft_core::project::ENV_RESOURCE_PREFIX);
}
}
/// Every image resource a layer, mask effect, stored path or the environment of `project` uses
fn project_images(project: &texturecraft_core::Project) -> Vec<String> {
let mut used = Vec::new();
for set in &project.texture_sets {
for root in &set.stack {
crate::material_lib::images_used(project, *root, &mut used, 0);
}
}
used.extend(project.display.environment_resource().map(str::to_string));
used
}
/// [`project_images`] and the images the brush alpha, the projection stencil and the mask brush use
fn images_in_use(s: &Session) -> Vec<String> {
let mut used = project_images(&s.doc.project);
used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone()));
used.extend(s.tool.brush.alpha_image.clone());
used.extend(s.tool.mask_image.clone());
used.extend(s.doc.project.display.environment_resource().map(str::to_string));
used.extend(s.doc.project.resource_sources.iter().filter_map(|(name, source)| {
let slot = source.mesh_map?;
s.doc.baked.get(&slot.texture_set).is_some_and(|baked| baked.maps.contains_key(&slot.map)).then(|| name.clone())
}));
used
}
/// Drop resources unused by layers, mesh maps, paint tools or the environment (one undo step)
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
let used = images_in_use(s);
let unused: Vec<String> = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect();
if !unused.is_empty() {
s.edit("Remove unused resources", |s| {
@@ -368,6 +489,120 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
mod tests {
use super::*;
#[test]
fn export_writes_the_imported_bytes() {
let mut session = crate::sample_session(128, 32).unwrap();
let bytes = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
let name = session.import_resource_bytes("icon.png", bytes.clone()).unwrap();
let path = std::env::temp_dir().join(format!("texturecraft-export-resource-{}.png", std::process::id()));
crate::commands::execute(&mut session, "resource.export", &json!({"name": name, "path": path.to_str().unwrap()})).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), bytes, "the file is the resource as imported");
std::fs::remove_file(path).unwrap();
}
#[test]
fn a_renamed_image_stays_in_use_everywhere_it_was() {
let mut session = crate::sample_session(128, 32).unwrap();
let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
let name = session.import_resource_bytes("photo.png", png).unwrap();
crate::execute(&mut session, "layer.add.image", &json!({"name": name})).unwrap();
session.tool.brush.alpha_image = Some(name.clone());
let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string();
assert_ne!(renamed, name);
assert!(renamed.ends_with(".png"), "the extension stays: {renamed}");
let used = images_in_use(&session);
assert!(used.contains(&renamed) && !used.contains(&name), "every use follows the rename: {used:?}");
assert!(session.images.contains_key(&renamed) && !session.images.contains_key(&name));
session.undo().unwrap();
assert!(project_images(&session.doc.project).contains(&name), "undo brings the old name back");
assert!(session.images.contains_key(&name));
assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&name), "the brush alpha follows the undo");
session.redo().unwrap();
assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&renamed), "the brush alpha follows the redo");
}
#[test]
fn a_renamed_image_keeps_following_its_file() {
let path = std::env::temp_dir().join(format!("texturecraft-rename-source-{}.png", std::process::id()));
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.25].into_iter()).unwrap()).unwrap();
let mut session = crate::sample_session(128, 32).unwrap();
let name = crate::execute(&mut session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string();
let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string();
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.75].into_iter()).unwrap()).unwrap();
// An equal-size file counts as changed once its time moved, as a later save's does
let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap();
let updated = crate::execute(&mut session, "resource.update", &json!({"names": [renamed]})).unwrap();
std::fs::remove_file(&path).unwrap();
assert_eq!(updated["updated"], json!([renamed]), "the renamed image reads its changed file again: {updated}");
}
#[test]
fn renaming_a_linked_materials_package_moves_a_material_effects_link_with_it() {
use std::collections::BTreeMap;
use texturecraft_core::{Effect, EffectKind, MaterialLink};
let mut session = crate::sample_session(128, 32).unwrap();
let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
let package = session.import_resource_bytes("package.png", png).unwrap();
crate::execute(&mut session, "layer.add.image", &json!({"name": package})).unwrap();
let layer_id = session.selected_layer().unwrap();
let link = MaterialLink {
name: "linked".into(),
package: package.clone(),
graph: String::new(),
params: Vec::new(),
presets: Vec::new(),
inputs: Vec::new(),
size: 1,
resolution: None,
mapping: BTreeMap::new(),
outputs: BTreeMap::from([("basecolor".to_string(), package.clone())]),
};
let effect_id = session.doc.project.alloc_id();
let material = Effect::new(effect_id, EffectKind::Material(Fill { link: Some(Box::new(link)), ..Fill::default() }));
session.doc.project.layers.get_mut(&layer_id).unwrap().content_effects.push(material);
let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": package, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string();
let effect = &session.doc.project.layers[&layer_id].content_effects[0];
let EffectKind::Material(fill) = &effect.kind else { panic!("the effect stays a material") };
let link = fill.link.as_ref().unwrap();
assert_ne!(renamed, package);
assert_eq!(link.package, renamed, "the link's package follows the rename");
assert_eq!(link.outputs.values().collect::<Vec<_>>(), [&renamed], "the link's cooked outputs follow the rename");
}
#[test]
fn renaming_an_image_a_generator_reads_as_its_grunge_moves_the_grunge_with_it() {
use texturecraft_core::{Effect, EffectKind, Generator, GeneratorKind};
let mut session = crate::sample_session(128, 32).unwrap();
let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
let grunge = session.import_resource_bytes("grunge.png", png).unwrap();
crate::execute(&mut session, "layer.add.image", &json!({"name": grunge})).unwrap();
let layer_id = session.selected_layer().unwrap();
let generator = Generator { grunge: Some(Source::image(grunge.clone())), ..Generator::new(GeneratorKind::EdgeWear) };
let effect_id = session.doc.project.alloc_id();
session.doc.project.layers.get_mut(&layer_id).unwrap().content_effects.push(Effect::new(effect_id, EffectKind::Generator(generator)));
let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": grunge, "to": "worn"})).unwrap()["name"].as_str().unwrap().to_string();
let EffectKind::Generator(generator) = &session.doc.project.layers[&layer_id].content_effects[0].kind else { panic!("the effect stays a generator") };
assert_ne!(renamed, grunge);
assert_eq!(generator.grunge, Some(Source::image(renamed)), "the generator's grunge follows the rename");
}
#[test]
fn file_reads_obey_the_remaining_byte_budget() {
let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id()));
+34
View File
@@ -1029,6 +1029,8 @@ impl Session {
}
fn after_history(&mut self, other: &Document) {
self.follow_renamed_resources(other);
// Pending operations may still hold layer IDs from the discarded snapshot
self.doc.project.next_id = self.doc.project.next_id.max(other.project.next_id);
self.mark_modified();
@@ -1051,6 +1053,38 @@ impl Session {
}
}
/// The image names the tools and the 2D view read, which a resource rename follows
pub(crate) fn tool_images_mut(&mut self) -> impl Iterator<Item = &mut String> {
[
self.tool.stencil.as_mut().map(|stencil| &mut stencil.image),
self.tool.brush.alpha_image.as_mut(),
self.tool.mask_image.as_mut(),
self.view_image.as_mut(),
]
.into_iter()
.flatten()
}
/// Points tool images at a resource's name on this side of an undone or redone rename
fn follow_renamed_resources(&mut self, other: &Document) {
let names: Vec<String> = self.tool_images_mut().map(|name| name.clone()).collect();
let renames: Vec<(String, String)> = names
.into_iter()
.filter(|name| !self.doc.resources.contains_key(name))
.filter_map(|name| {
let bytes = other.resources.get(&name)?;
let to = self.doc.resources.iter().find(|(_, here)| Arc::ptr_eq(here, bytes)).map(|(here, _)| here.clone())?;
Some((name, to))
})
.collect();
for (name, to) in renames {
for tool_image in self.tool_images_mut().filter(|tool_image| **tool_image == name) {
tool_image.clone_from(&to);
}
}
}
// -----------------------------------------------------------------------------------------
// Compositing
+10 -3
View File
@@ -194,6 +194,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
let material = response.dnd_hover_payload::<ShelfDrag>().is_some_and(|drag| drag.asset.is_material());
if response.dnd_hover_payload::<u64>().is_some() || material {
ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(DROP_STROKE, tokens.accent));
crate::shelf_drag_ghost::accept(ui.ctx());
}
});
select_all_layers(app, ui);
@@ -793,6 +794,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
}
if row.drag_started() && !renaming {
row.dnd_set_drag_payload(layer.id.0);
crate::shelf_drag_ghost::start_layer(ui.ctx(), &layer.name);
}
// A folder midpoint accepts child drops; a smart mask replaces the current mask
@@ -807,6 +809,11 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
let moving = row.dnd_hover_payload::<u64>().is_some_and(|dragged| !in_drag(app, *dragged));
let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent);
let shelf_material = shelf.as_ref().is_some_and(Asset::is_material);
let shelf_mask = matches!(shelf, Some(Asset::SmartMask(_) | Asset::SavedMask(_)));
let shelf_filter = matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group();
if moving || shelf_material || shelf_mask || shelf_filter {
crate::shelf_drag_ghost::accept(&row.ctx);
}
if moving || shelf_material {
if inside {
painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside);
@@ -815,9 +822,9 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
} else {
painter.line_segment([rect.left_top(), rect.right_top()], drop_stroke);
}
} else if matches!(shelf, Some(Asset::SmartMask(_) | Asset::SavedMask(_))) {
} else if shelf_mask {
painter.rect_stroke(mask_rect.expand(HIGHLIGHT_OUTSET), THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Outside);
} else if matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group() {
} else if shelf_filter {
painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside);
}
if let Some(dragged) = dnd_release::<u64>(&row)
@@ -1826,7 +1833,7 @@ pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option<String> {
return None;
}
ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, Tokens::get(ui.ctx()).accent), egui::StrokeKind::Inside);
crate::shelf_drag_ghost::outline_target(ui, resp.rect);
match dnd_release::<ShelfDrag>(resp).map(|d| d.asset.clone()) {
Some(Asset::Texture(name)) => Some(name),
_ => None,
+13 -6
View File
@@ -28,6 +28,8 @@ use crate::theme::Tokens;
pub enum Panel {
Viewport,
Assets,
/// A second Assets panel with its own search, type and folder (the Assets panel's folder button)
AssetsSecond,
// Saved layouts name the bake panels by their earlier names
#[serde(rename = "BakeMaps")]
MeshMapSettings,
@@ -81,7 +83,7 @@ impl Panel {
use crate::state::Mode;
match self {
Self::MeshMapSettings | Self::CommonSettings | Self::MeshMapBakers | Self::BakingLog => mode == Mode::Baking,
Self::Assets | Self::Layers | Self::Properties | Self::TextureSetSettings | Self::Export => mode == Mode::Painting,
Self::Assets | Self::AssetsSecond | Self::Layers | Self::Properties | Self::TextureSetSettings | Self::Export => mode == Mode::Painting,
Self::History => mode != Mode::Rendering,
Self::Shader => mode != Mode::Baking,
Self::Renderer => mode == Mode::Rendering,
@@ -89,9 +91,10 @@ impl Panel {
}
}
pub const ALL: [Panel; 16] = [
pub const ALL: [Panel; 17] = [
Panel::Viewport,
Panel::Assets,
Panel::AssetsSecond,
Panel::MeshMapSettings,
Panel::CommonSettings,
Panel::MeshMapBakers,
@@ -112,6 +115,8 @@ impl Panel {
match self {
Panel::Viewport => "Viewport",
Panel::Assets => "Assets",
// The second panel shows every type at first, so it's named for that, as the reference names it
Panel::AssetsSecond => "All",
Panel::MeshMapSettings => "Mesh Map Settings",
Panel::CommonSettings => "Common Settings",
Panel::MeshMapBakers => "Mesh Map Bakers",
@@ -186,8 +191,8 @@ pub fn default_workspace() -> Workspace {
split(Axis::X, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column),
);
let mut hidden: Vec<(Panel, Location<Panel>)> = Panel::ALL.into_iter().filter_map(|panel| Some((panel, floating_location(panel.float_rect()?)))).collect();
for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] {
hidden.push((panel, Location::new(Some(TextureSetList), DockPlacement::tab(None))));
for (panel, anchor) in [(MeshMapSettings, TextureSetList), (CommonSettings, TextureSetList), (MeshMapBakers, TextureSetList), (AssetsSecond, Assets)] {
hidden.push((panel, Location::new(Some(anchor), DockPlacement::tab(None))));
}
Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, Vec::new())
@@ -312,7 +317,7 @@ impl Dock {
pub(crate) fn for_baking() -> Self {
let painting = default_workspace();
let mut hidden = painting.hidden().to_vec();
for panel in [Panel::Assets, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] {
for panel in [Panel::Assets, Panel::AssetsSecond, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] {
if let Ok(location) = painting.layout().location(&panel) {
hidden.push((panel, location));
}
@@ -602,7 +607,8 @@ fn min_size(panel: Panel) -> Vec2 {
/// The body of every panel except the viewport, in the dock or on the rail
pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) {
// No project open: the library and the log work, the other panels about a project stay empty
let works_empty = matches!(panel, Panel::Assets | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties | Panel::Export);
let works_empty =
matches!(panel, Panel::Assets | Panel::AssetsSecond | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties | Panel::Export);
if !app.session.project_open && !works_empty {
return;
}
@@ -612,6 +618,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) {
egui::Frame::new().inner_margin(margin).show(ui, |ui| match panel {
Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui),
Panel::Assets => crate::shelf::body(app, ui),
Panel::AssetsSecond => crate::shelf_second::body(app, ui),
Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui),
Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui),
Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui),
+13
View File
@@ -161,12 +161,21 @@ mod session_log_file;
pub mod settings_window;
pub mod shader_settings;
pub mod shelf;
pub mod shelf_custom_preview;
pub mod shelf_drag_ghost;
pub mod shelf_drag_ghost_shown;
pub mod shelf_drag_verdict;
mod shelf_entry;
pub mod shelf_favorite;
mod shelf_folders;
mod shelf_menu;
pub mod shelf_panes;
pub mod shelf_preview;
pub mod shelf_query;
pub mod shelf_second;
mod shelf_tabs;
mod shelf_toolbar;
pub mod shelf_updates;
pub mod shelf_view;
mod shortcut_dispatch;
mod slot_thumbnail;
@@ -1290,6 +1299,7 @@ impl eframe::App for TextureCraftApp {
self.ui.prefs.apply_resource_limits();
control::poll(self, ctx);
shelf_updates::tick(self, ctx);
#[cfg(not(target_arch = "wasm32"))]
self.run_file_dialog_answers();
web_files::poll(self);
@@ -1440,6 +1450,9 @@ impl eframe::App for TextureCraftApp {
windows::show(self, &ctx);
// After every drop target has said whether it takes the dragged asset
shelf_drag_ghost::show(&ctx);
// Finish after the dock and windows have requested their thumbnails
self.layer_panel.end(&ctx, &self.session);
+47 -7
View File
@@ -1,7 +1,7 @@
use egui::{Align2, CornerRadius, FontId, Frame, Margin, Rect, RectAlign, RichText, Role, Sense, Shadow, Stroke, WidgetInfo, pos2, vec2};
use egui_phosphor::regular as ic;
use super::{PropertySheet, ROW_HEIGHT, SMALL_TEXT_SIZE};
use super::{PropertySheet, ROW_HEIGHT, SIDE_PADDING_POINTS, SMALL_TEXT_SIZE};
use crate::theme::HARD_SHADOW;
/// The i's slot at the panel edge; a row with an i at its left starts this much further right
@@ -16,6 +16,9 @@ const INFO_ICON_SIZE: f32 = 13.0;
/// Room the tooltip leaves at the panel's right edge, so it covers no number, dial or switch
const TIP_VALUE_ROOM: f32 = 70.0;
/// Width of a tooltip beside its window
const BESIDE_TIP_WIDTH: f32 = 320.0;
/// How far the tooltip reaches up into its row
const TIP_OVERLAP: f32 = 2.0;
@@ -47,6 +50,48 @@ impl<'u> PropertySheet<'u> {
self.paint_info_in(self.right - INFO_SLOT, self.right - INFO_ICON_SIZE / 2.0, center_y);
}
/// Paints an i for the row just laid out in the `column` right of the sheet, its tooltip beside the window the sheet is in
pub(crate) fn beside_info(&mut self, column: f32, tip: &str) {
let center_y = self.cursor_y() - ROW_HEIGHT / 2.0;
let row_top = center_y - ROW_HEIGHT / 2.0;
let edge = self.right + SIDE_PADDING_POINTS + column;
let slot = Rect::from_min_max(pos2(edge - SIDE_PADDING_POINTS - INFO_SLOT, row_top), pos2(edge - SIDE_PADDING_POINTS, row_top + ROW_HEIGHT));
let id = self.next_id();
let response = self.ui.interact(slot, id, Sense::hover());
response.widget_info(|| WidgetInfo::labeled(Role::Image, true, tip));
let tokens = self.tokens;
let color = if response.hovered() { tokens.text } else { tokens.text_dim };
self.ui.painter().text(slot.center(), Align2::CENTER_CENTER, ic::INFO, FontId::proportional(INFO_ICON_SIZE), color);
// Beside the window, from this row down, so it covers none of the rows under it
let layer = self.ui.layer_id().id;
let window = self.ui.ctx().memory(|memory| memory.area_rect(layer)).unwrap_or(self.ui.clip_rect());
let anchor = Rect::from_min_max(pos2(window.left(), row_top), pos2(window.right(), row_top + ROW_HEIGHT));
let mut tooltip = egui::Tooltip::for_enabled(&response);
tooltip.popup = tooltip
.popup
.anchor(anchor)
.align(RectAlign::RIGHT_START)
.align_alternatives(&[RectAlign::LEFT_START])
.frame(self.tip_frame())
.width(BESIDE_TIP_WIDTH);
tooltip.show(|ui| {
ui.set_width(BESIDE_TIP_WIDTH);
ui.label(RichText::new(tip).size(SMALL_TEXT_SIZE).color(tokens.text).line_height(Some(TIP_LINE_HEIGHT)));
});
}
/// The tooltips' box: the chrome, a hairline, rounded, with a hard shadow
fn tip_frame(&self) -> Frame {
Frame::NONE
.fill(self.tokens.chrome)
.stroke(Stroke::new(1.0, self.tokens.field_border))
.corner_radius(CornerRadius::same(TIP_ROUNDING))
.inner_margin(TIP_MARGIN)
.shadow(TIP_SHADOW)
}
/// Paints the pending i at `glyph_x` in its slot from `slot_left`
fn paint_info_in(&mut self, slot_left: f32, glyph_x: f32, center_y: f32) {
let Some(tip) = self.info.take() else { return };
@@ -63,12 +108,7 @@ impl<'u> PropertySheet<'u> {
// Under the row from the i, ending before the value column; above it where the window ends first
let anchor = Rect::from_min_max(pos2(self.left, row_top), pos2(self.right - TIP_VALUE_ROOM, row_top + ROW_HEIGHT));
let frame = Frame::NONE
.fill(tokens.chrome)
.stroke(Stroke::new(1.0, tokens.field_border))
.corner_radius(CornerRadius::same(TIP_ROUNDING))
.inner_margin(TIP_MARGIN)
.shadow(TIP_SHADOW);
let frame = self.tip_frame();
let text_width = anchor.width() - TIP_MARGIN.sum().x;
let mut tooltip = egui::Tooltip::for_enabled(&response);
+2 -2
View File
@@ -82,7 +82,7 @@ pub(crate) use size_columns_response::SizeColumnsResponse;
pub(crate) use slot_response::SlotResponse;
pub(crate) use stack_slider::StackSlider;
pub(crate) use stacked_rows::{CHECK_SIZE, paint_check};
pub(crate) use switch_control::paint_focus_outline;
pub(crate) use switch_control::{TOGGLE_ROOM, paint_focus_outline};
pub(crate) fn paint_keyboard_focus(ui: &egui::Ui, response: &egui::Response, tokens: &crate::theme::Tokens) {
if response.has_focus() {
@@ -124,7 +124,7 @@ const VALUE_MIN_WIDTH: f32 = 26.0;
const TRACK_TO_VALUE: f32 = 14.0;
/// Size of regular labels and SemiBold values
const TEXT_SIZE: f32 = 12.0;
pub(crate) const TEXT_SIZE: f32 = 12.0;
/// Size of captions, pill names and the switch's words
const SMALL_TEXT_SIZE: f32 = 11.0;
@@ -5,4 +5,6 @@ pub(crate) enum SectionScope {
Docked,
/// The right-click Properties popup over a view
Popup,
/// The Assets panel's refresh popup, which has no strip
Shelf,
}
@@ -38,6 +38,9 @@ const TOGGLE_LABEL_AIR: f32 = 10.0;
/// From that column to the pill's centre: the pill starts on the column
const TOGGLE_CENTER_OFFSET: f32 = PILL_SIZE.x / 2.0;
/// Room a toggle takes right of its label: the air and the switch
pub(crate) const TOGGLE_ROOM: f32 = TOGGLE_LABEL_AIR + PILL_SIZE.x;
/// From one of a pair's toggles to the next, and from its name to its pill's centre
const PAIR_PITCH: f32 = 76.0;
const PAIR_NAME_TO_PILL: f32 = 32.0;
@@ -191,6 +194,15 @@ impl PropertySheet<'_> {
/// An on/off beside its label; every toggle in a panel lines up past the longest toggle label
pub(crate) fn toggle(&mut self, label: &str, on: &mut bool) -> bool {
self.toggle_in(label, on, true)
}
/// A [`Self::toggle`] greyed out and off: a setting this app can't act on yet, said in its row's i
pub(crate) fn unavailable_toggle(&mut self, label: &str) {
self.toggle_in(label, &mut false, false);
}
fn toggle_in(&mut self, label: &str, on: &mut bool, enabled: bool) -> bool {
let rect = self.take(ROW_HEIGHT);
let center_y = rect.center().y;
let label_x = self.left + self.lead_shift();
@@ -201,11 +213,19 @@ impl PropertySheet<'_> {
let column = (self.column() - self.left).max(self.used.toggle_label_end).max(label_end);
let pill = Rect::from_center_size(pos2(self.left + column + TOGGLE_CENTER_OFFSET, center_y), PILL_SIZE);
let clicked = self.toggle_hit(Rect::from_min_max(pos2(label_x, rect.top()), pos2(pill.right(), rect.bottom())), label, on);
let hit = Rect::from_min_max(pos2(label_x, rect.top()), pos2(pill.right(), rect.bottom()));
let clicked = if enabled {
self.toggle_hit(hit, label, on)
} else {
let id = self.next_id();
let response = self.ui.interact(hit, id, Sense::hover());
response.widget_info(|| WidgetInfo::selected(Role::CheckBox, false, false, label));
false
};
let text = self.tokens.text;
let text = if enabled { self.tokens.text } else { self.tokens.text_dim };
self.ui.painter().text(pos2(label_x, center_y), Align2::LEFT_CENTER, label, font, text);
self.pill(pill.center(), *on, true);
self.pill(pill.center(), *on, enabled);
self.drawn(center_y + PILL_SIZE.y / 2.0);
clicked
}
+4 -1
View File
@@ -2,11 +2,14 @@
use serde::{Deserialize, Serialize};
/// The search text, tab and library folder of a saved shelf query, under the name it lists as
/// The search text, tab, library folder and Favorites choice of a saved shelf query, under the name it lists as
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SavedSearch {
pub name: String,
pub filter: String,
pub tab: usize,
pub path: Vec<String>,
/// Only favorites show; searches saved before favorites show everything
#[serde(default)]
pub favorites_only: bool,
}
+36 -41
View File
@@ -108,10 +108,12 @@ impl Asset {
}
/// The drag-and-drop payload of a shelf tile.
#[derive(Clone, Debug)]
#[derive(Clone)]
pub struct ShelfDrag {
pub asset: Asset,
pub label: String,
/// The tile's thumbnail, shown at the pointer while dragging (the name when there is none)
pub thumb: Option<egui::TextureHandle>,
}
/// Apply `asset` the way a shelf click does: a simple material becomes the brush's material (no
@@ -209,7 +211,6 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response
DecalDrop::show_menu(app, ui, response);
}
let tokens = Tokens::get(ui.ctx());
let accepts = |drag: &ShelfDrag| match drag.asset {
Asset::Alpha(_) => true,
Asset::Material(_) | Asset::Library(_) => zone != DropZone::Brush,
@@ -217,8 +218,13 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response
Asset::SmartMask(_) | Asset::SavedMask(_) | Asset::Filter(_) => false,
};
let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.goes_onto_set();
if response.dnd_hover_payload::<ShelfDrag>().is_some_and(|drag| accepts(&drag) && !onto_set(&drag.asset)) {
ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside);
if let Some(drag) = response.dnd_hover_payload::<ShelfDrag>().filter(|drag| accepts(drag)) {
// The 3D view outlines the set under the pointer itself; its background takes nothing
if !onto_set(&drag.asset) {
crate::shelf_drag_ghost::outline_target(ui, response.rect);
} else if set_under_pointer(app, ui, response).is_some() {
crate::shelf_drag_ghost::accept(ui.ctx());
}
}
let pointer = ui.input(|input| input.pointer.interact_pos());
@@ -252,7 +258,6 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response
/// The Assets panel body (a dock tab)
pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
let ctx = ui.ctx().clone();
let filter = app.ui.shelf_filter.to_lowercase();
scan_library(app);
let all_entries = ShelfEntry::all(app);
@@ -266,6 +271,10 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
let folder = app.ui.shelf_path.clone();
let picked_tab = app.ui.shelf_tab;
let mut matching: Vec<ShelfEntry> = all_entries.into_iter().filter(|entry| entry.matches(&filter)).collect();
if app.ui.shelf_favorites_only {
matching.retain(|entry| crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some());
}
let path_pane_open = app.ui.shelf_panes.filter_by_path;
let mut applicable = if path_pane_open {
crate::shelf_folders::paths(matching.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab())))
@@ -280,15 +289,16 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
let mut counts: Vec<usize> = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect();
// Saved smart materials and masks count toward their tabs even without tiles
let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER);
// Saved smart materials and masks count toward their tabs even without tiles; they can't be favorites yet
let favorites_only = app.ui.shelf_favorites_only;
let in_user_library = !favorites_only && folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER);
let saved_materials_matching = saved_matching(app, &filter, false);
let saved_masks_matching = saved_matching(app, &filter, true);
for (tab, saved) in [(Tab::Smart, saved_materials_matching), (Tab::Masks, saved_masks_matching)] {
if in_user_library && let Some(count) = TABS.iter().position(|(shown, _, _)| *shown == tab).and_then(|position| counts.get_mut(position)) {
*count += saved;
}
if path_pane_open && saved > 0 && crate::shelf_tabs::shows(picked_tab, tab) {
if path_pane_open && !favorites_only && saved > 0 && crate::shelf_tabs::shows(picked_tab, tab) {
applicable.push(vec![crate::shelf_entry::USER.to_string()]);
}
}
@@ -300,11 +310,14 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
let tab = app.ui.shelf_tab;
let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown);
let show_user_brushes = crate::shelf_tabs::shows(tab, Tab::Brushes)
let show_user_brushes = !favorites_only
&& crate::shelf_tabs::shows(tab, Tab::Brushes)
&& folder.len() <= 2
&& folder.iter().zip([crate::shelf_entry::USER, "Brushes"]).all(|(selected, part)| selected == part);
let mut entries: Vec<ShelfEntry> = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect();
entries.sort_by_cached_key(|entry| entry.label().to_lowercase());
// Favorites first, the most recently added first, then by name
let favorites = &app.ui.shelf_favorites;
entries.sort_by_cached_key(|entry| (crate::shelf_favorite::rank(favorites, entry).unwrap_or(usize::MAX), entry.label().to_lowercase()));
// The toolbar has its own strip at the panel's bottom, so nothing above it can push it out
let area = ui.available_rect_before_wrap();
@@ -317,7 +330,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
ui.set_min_size(vec2(width, grid_rect.height()));
crate::shelf_panes::column(app, ui, &paths, &applicable);
});
ui.separator();
crate::shelf_panes::edge(app, ui, width, grid_rect.width());
}
// Saved smart materials are files in the user's library, without folders of their own
@@ -326,7 +339,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
grid(app, ui, &entries, grid_rect.height(), [saved_materials, saved_masks], show_user_brushes, &filter);
});
ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui));
drag_preview(&ctx);
}
/// The tiles of `entries` in a scroll area `height` high, then user brushes, saved smart materials and saved smart masks when selected
@@ -383,18 +395,6 @@ fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) {
});
}
/// The dragged asset's name next to the pointer.
fn drag_preview(ctx: &egui::Context) {
let tk = Tokens::get(ctx);
let (Some(d), Some(pos)) = (egui::DragAndDrop::payload::<ShelfDrag>(ctx), ctx.input(|i| i.pointer.hover_pos())) else { return };
let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("shelf_drag")));
let galley = p.layout_no_wrap(d.label.clone(), egui::FontId::proportional(11.0), tk.text_strong);
let rect = egui::Rect::from_min_size(pos + vec2(14.0, 12.0), galley.size() + vec2(12.0, 6.0));
p.rect_filled(rect, 3.0, tk.row_selected);
p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
p.galley(rect.min + vec2(6.0, 3.0), galley, tk.text_strong);
}
pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool {
filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter))
}
@@ -493,7 +493,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) {
let location = path.display().to_string();
let asset = if masks { Asset::SavedMask(location) } else { Asset::Library(location) };
if response.drag_started() {
response.dnd_set_drag_payload(ShelfDrag { asset, label: label.to_owned() });
response.dnd_set_drag_payload(ShelfDrag { asset, label: label.to_owned(), thumb: None });
} else {
selected.push(asset);
}
@@ -514,7 +514,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) {
#[cfg(target_arch = "wasm32")]
fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str, _: bool) {}
/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu
/// The tile of `entry`, outlined when `selected`: a click applies it, a right-click opens its menu
fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) {
// An image removed this frame has nothing to show
if let ShelfEntry::Image(name) = entry
@@ -523,13 +523,15 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry
return;
}
let texture = entry.thumbnail(app, ctx);
// A picture the user picked replaces the thumbnail, unless its file is gone; it is read only once its tile shows
let thumbnail = entry.thumbnail(app, ctx);
let custom_file = crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry);
let asset = entry.asset();
let session = &app.session;
let response = tile_in_view(
ui,
&mut app.thumbs,
|_, _| texture,
|ui, thumbs| custom_file.and_then(|file| thumbs.custom_preview(ui.ctx(), file)).or(thumbnail),
|thumbs| match entry {
ShelfEntry::SavedBrush { path: Some(path), .. } => Some(thumbs.saved_brush_preview(path, &session.images)),
_ => entry.preview(session),
@@ -548,6 +550,10 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry
if entry.includes_randomness() {
randomness_badge(ui.painter(), view.thumbnail_rect(response.rect));
}
if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() {
crate::shelf_favorite::star(ui.painter(), view.thumbnail_rect(response.rect), Tokens::get(ctx).warning);
ctx.accesskit_node_builder(response.id, |node| node.set_description(tr("Favorite")));
}
if response.clicked() || response.secondary_clicked() {
let (kind, id) = entry.identity();
@@ -557,18 +563,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry
entry.activate(app);
}
if let ShelfEntry::Image(name) = entry {
response.context_menu(|ui| {
if ui.button(tr("Add as decal (view center)")).clicked() {
app.run("layer.add.decal", json!({"image": name}));
ui.close();
}
if ui.button(tr("Remove resource")).clicked() {
app.run("resource.remove", json!({"name": name}));
ui.close();
}
});
}
crate::shelf_menu::show(app, &response, entry);
}
/// Asset tile with optional dragging and a larger hover preview, at the medium size
@@ -601,7 +596,7 @@ fn tile_in_view(
if let Some(asset) = drag
&& response.drag_started()
{
response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() });
response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string(), thumb: texture.clone() });
}
let painter = ui.painter();
@@ -0,0 +1,67 @@
//! A picture the user picked to show on an asset's tile instead of its rendered thumbnail ("Set custom preview..." in the asset menu)
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::shelf_entry::ShelfEntry;
/// The custom preview's size in pixels: the largest tile's thumbnail on a high-density screen
pub(crate) const CUSTOM_PREVIEW_PX: u32 = 164;
/// The image file shown on the tile of the asset with [`ShelfEntry::identity`] `kind` and `id`
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShelfCustomPreview {
pub kind: String,
pub id: String,
pub file: PathBuf,
}
impl ShelfCustomPreview {
fn is(&self, entry: &ShelfEntry) -> bool {
let (kind, id) = entry.identity();
self.kind == kind && self.id == id
}
}
/// The image file `entry` shows instead of its thumbnail, if the user picked one
pub(crate) fn file_for<'a>(previews: &'a [ShelfCustomPreview], entry: &ShelfEntry) -> Option<&'a Path> {
previews.iter().find(|preview| preview.is(entry)).map(|preview| preview.file.as_path())
}
/// Shows `file` on the tile of the asset with identity `kind` and `id`, replacing an earlier pick
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn set(previews: &mut Vec<ShelfCustomPreview>, kind: String, id: String, file: PathBuf) {
previews.retain(|preview| preview.kind != kind || preview.id != id);
previews.push(ShelfCustomPreview { kind, id, file });
}
/// Shows `entry`'s own thumbnail again
pub(crate) fn remove(previews: &mut Vec<ShelfCustomPreview>, entry: &ShelfEntry) {
previews.retain(|preview| !preview.is(entry));
}
/// The largest centred square of `image`, scaled to [`CUSTOM_PREVIEW_PX`] (smaller images keep their size)
pub(crate) fn square(image: &image::DynamicImage) -> image::RgbaImage {
let side = image.width().min(image.height());
let cropped = image.crop_imm((image.width() - side) / 2, (image.height() - side) / 2, side, side);
let size = side.min(CUSTOM_PREVIEW_PX);
cropped.resize_exact(size, size, image::imageops::FilterType::Triangle).to_rgba8()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_wide_picture_keeps_its_middle() {
let red = image::Rgba([255, 0, 0, 255]);
let blue = image::Rgba([0, 0, 255, 255]);
let wide = image::RgbaImage::from_fn(6, 2, |x, _| if (2..4).contains(&x) { blue } else { red });
let square = square(&image::DynamicImage::ImageRgba8(wide));
assert_eq!(square.width(), square.height(), "the preview is square");
assert!(square.pixels().all(|pixel| *pixel == blue), "only the middle of a wide picture shows");
}
}
+154
View File
@@ -0,0 +1,154 @@
//! The picture that follows a dragged asset or layer, with a badge saying whether the place under it takes it
use egui::{Color32, Context, Id, LayerId, Order, Pos2, Rect, Stroke, TextureId, Vec2, vec2};
use crate::shelf::ShelfDrag;
pub use crate::shelf_drag_ghost_shown::ShelfDragGhostShown;
pub use crate::shelf_drag_verdict::ShelfDragVerdict;
use crate::theme::Tokens;
/// Side of the dragged asset's thumbnail
const GHOST_SIZE: f32 = 48.0;
/// The thumbnail's top-left corner from the pointer: just under its tip
const GHOST_OFFSET: Vec2 = vec2(4.0, 4.0);
/// How opaque the thumbnail is, so the target shows through it
const GHOST_OPACITY: f32 = 0.6;
/// Corner rounding of the name chip
const CHIP_ROUNDING: f32 = 3.0;
/// Side of the badge
const BADGE_SIZE: f32 = 9.0;
/// The badge's centre from the pointer: past the pointer arrow's tail, on the thumbnail's corner
const BADGE_OFFSET: Vec2 = vec2(14.0, 22.0);
/// Size of the badge's icon
const BADGE_ICON_SIZE: f32 = 7.5;
/// Corner rounding of the square badge
const BADGE_ROUNDING: f32 = 2.0;
/// Fill of the square badge and colour of the icon on the red one
const BADGE_LIGHT: Color32 = Color32::from_gray(245);
/// Colour of the icon on the square badge
const BADGE_DARK: Color32 = Color32::from_gray(35);
/// Opacity of the thin dark outline that keeps the badge apart from whatever is under it
const BADGE_OUTLINE_ALPHA: u8 = 140;
/// Padding of the name chip shown when the asset has no thumbnail
const CHIP_PADDING: Vec2 = vec2(6.0, 3.0);
/// Text size of the name chip
const CHIP_TEXT_SIZE: f32 = 11.0;
/// Width of the outline around a drop target that takes the dragged asset
const TARGET_OUTLINE_WIDTH: f32 = 2.0;
/// How far the outline sits inside the target's edge, so a neighbouring panel doesn't cut it
const TARGET_OUTLINE_INSET: f32 = 1.0;
/// Corner rounding of the outline
const TARGET_OUTLINE_ROUNDING: f32 = 3.0;
/// Pass number of the last drop target that took the dragged asset (ctx temp data)
const ACCEPTED: &str = "shelf_drag_accepted";
/// What the last pass painted (ctx temp data)
const SHOWN: &str = "shelf_drag_shown";
/// The name of the layer being dragged in the layer stack, whose payload is only its id (ctx temp data)
const LAYER: &str = "shelf_drag_layer";
/// Note that the drop target being drawn takes the dragged asset or layer, where it paints its drop highlight
pub(crate) fn accept(ctx: &Context) {
let pass = ctx.cumulative_pass_nr();
ctx.data_mut(|data| data.insert_temp(Id::unique(ACCEPTED), pass));
}
/// Outlines drop target `rect` while the dragged asset hovers it, and notes that it takes the asset
pub(crate) fn outline_target(ui: &egui::Ui, rect: Rect) {
let stroke = Stroke::new(TARGET_OUTLINE_WIDTH, Tokens::get(ui.ctx()).accent);
ui.painter().rect_stroke(rect.shrink(TARGET_OUTLINE_INSET), TARGET_OUTLINE_ROUNDING, stroke, egui::StrokeKind::Inside);
accept(ui.ctx());
}
/// Note the name of the layer whose drag starts: a chip with it follows the pointer, since an empty layer's thumbnail shows nothing
pub(crate) fn start_layer(ctx: &Context, label: &str) {
ctx.data_mut(|data| data.insert_temp(Id::unique(LAYER), label.to_owned()));
}
/// The picture and name of what is being dragged: an asset, or a layer (its name only)
fn dragged(ctx: &Context) -> Option<(Option<TextureId>, String)> {
if let Some(drag) = egui::DragAndDrop::payload::<ShelfDrag>(ctx) {
return Some((drag.thumb.as_ref().map(egui::TextureHandle::id), drag.label.clone()));
}
if !egui::DragAndDrop::has_payload_of_type::<u64>(ctx) {
return None;
}
ctx.data(|data| data.get_temp::<String>(Id::unique(LAYER))).map(|label| (None, label))
}
/// The ghost painted this pass, if an asset or a layer is being dragged
pub fn shown(ctx: &Context) -> Option<ShelfDragGhostShown> {
ctx.data(|data| data.get_temp(Id::unique(SHOWN)))
}
/// Paint the dragged asset and its badge at the pointer, once a pass after every drop target
pub(crate) fn show(ctx: &Context) {
let (Some((thumb, label)), Some(pointer)) = (dragged(ctx), ctx.input(|input| input.pointer.hover_pos())) else {
ctx.data_mut(|data| data.remove::<ShelfDragGhostShown>(Id::unique(SHOWN)));
return;
};
let pass = ctx.cumulative_pass_nr();
let accepted = ctx.data(|data| data.get_temp::<u64>(Id::unique(ACCEPTED))) == Some(pass);
let verdict = if accepted { ShelfDragVerdict::Valid } else { ShelfDragVerdict::NotValid };
let painter = ctx.layer_painter(LayerId::new(Order::Tooltip, Id::unique("shelf_drag_ghost")));
let tokens = Tokens::get(ctx);
let ghost = match thumb {
Some(thumb) => {
let rect = Rect::from_min_size(pointer + GHOST_OFFSET, Vec2::splat(GHOST_SIZE));
let uv = Rect::from_min_max(Pos2::ZERO, egui::pos2(1.0, 1.0));
painter.image(thumb, rect, uv, Color32::WHITE.gamma_multiply(GHOST_OPACITY));
rect
}
None => name_chip(&painter, &tokens, pointer + GHOST_OFFSET, &label),
};
let badge = badge(&painter, &tokens, pointer + BADGE_OFFSET, verdict);
ctx.data_mut(|data| data.insert_temp(Id::unique(SHOWN), ShelfDragGhostShown { verdict, ghost, badge }));
}
/// The name in a chip at `top_left`, for what has no thumbnail (saved smart materials and masks, layers)
fn name_chip(painter: &egui::Painter, tokens: &Tokens, top_left: Pos2, label: &str) -> Rect {
let galley = painter.layout_no_wrap(label.to_owned(), egui::FontId::proportional(CHIP_TEXT_SIZE), tokens.text_strong);
let rect = Rect::from_min_size(top_left, galley.size() + CHIP_PADDING * 2.0);
painter.rect_filled(rect, CHIP_ROUNDING, tokens.row_selected);
painter.rect_stroke(rect, CHIP_ROUNDING, Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside);
painter.galley(rect.min + CHIP_PADDING, galley, tokens.text_strong);
rect
}
/// The badge at `centre`: a crosshair on a light square where a drop works, else a no-entry sign
fn badge(painter: &egui::Painter, tokens: &Tokens, centre: Pos2, verdict: ShelfDragVerdict) -> Rect {
let rect = Rect::from_center_size(centre, Vec2::splat(BADGE_SIZE));
let outline = Stroke::new(1.0, Color32::from_black_alpha(BADGE_OUTLINE_ALPHA));
let (icon, color) = match verdict {
ShelfDragVerdict::Valid => {
painter.rect(rect, BADGE_ROUNDING, BADGE_LIGHT, outline, egui::StrokeKind::Outside);
(egui_phosphor::regular::CROSSHAIR_SIMPLE, BADGE_DARK)
}
ShelfDragVerdict::NotValid => {
painter.circle(centre, BADGE_SIZE / 2.0, tokens.danger, outline);
(egui_phosphor::regular::PROHIBIT, BADGE_LIGHT)
}
};
let glyph = painter.layout_no_wrap(icon.to_owned(), egui::FontId::proportional(BADGE_ICON_SIZE), color);
painter.galley(centre - glyph.mesh_bounds.center().to_vec2(), glyph, color);
rect.expand(outline.width)
}
@@ -0,0 +1,16 @@
//! Where the drag ghost and its badge were painted, and what the badge said
use egui::Rect;
use crate::shelf_drag_verdict::ShelfDragVerdict;
/// The ghost as the last pass painted it
#[derive(Clone, Copy, Debug)]
pub struct ShelfDragGhostShown {
/// What the badge says
pub verdict: ShelfDragVerdict,
/// Where the thumbnail (or the name chip) is
pub ghost: Rect,
/// Where the badge is
pub badge: Rect,
}
+10
View File
@@ -0,0 +1,10 @@
//! What the drag badge says about the place under the pointer
/// Whether the place under the pointer takes the dragged asset
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ShelfDragVerdict {
/// A drop here does something: a crosshair on a light square
Valid,
/// A drop here does nothing: a no-entry sign on red
NotValid,
}
+16 -1
View File
@@ -13,7 +13,7 @@ use texturecraft_engine::paint::presets::{BrushPreset, PRESETS};
use texturecraft_engine::smart_masks::{SMART_MASKS, SmartMask};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::i18n::{n_, tr};
use crate::shelf::{Asset, Tab, apply};
use crate::shelf_preview::ShelfPreview;
@@ -124,6 +124,21 @@ impl ShelfEntry {
path.len() <= own.len() && path.iter().zip(own).all(|(wanted, have)| wanted == have)
}
/// What the asset is used as, lowercase (English, shown through `tr`): the menu's Usages row
pub(crate) fn usage(&self) -> &'static str {
match self {
ShelfEntry::Material(material) if material.smart => n_("smart material"),
ShelfEntry::Material(_) => n_("material"),
ShelfEntry::SmartMask(_) => n_("smart mask"),
ShelfEntry::Filter(_) => n_("filter"),
ShelfEntry::Brush(_) | ShelfEntry::SavedBrush { .. } => n_("brush"),
ShelfEntry::Alpha(_) => n_("alpha"),
ShelfEntry::Procedural(_) => n_("procedural"),
ShelfEntry::Environment(_) => n_("environment"),
ShelfEntry::Image(_) => n_("texture"),
}
}
/// The name under the tile, translated where the asset's name is
pub(crate) fn label(&self) -> &str {
match self {
+78
View File
@@ -0,0 +1,78 @@
//! An asset the user marked as a favorite in the Assets panel: it shows a star and comes first in its type
use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, epaint::Mesh, vec2};
use serde::{Deserialize, Serialize};
use crate::shelf_entry::ShelfEntry;
/// The star's outer and inner radius and its centre's inset from the thumbnail's top-right corner, in points
const STAR_OUTER_RADIUS: f32 = 5.5;
const STAR_INNER_RADIUS: f32 = 2.4;
const STAR_INSET: f32 = 4.0;
/// The offset and colour of the star's shadow, which keeps it readable on light thumbnails
const STAR_SHADOW_OFFSET: f32 = 1.0;
const STAR_SHADOW: Color32 = Color32::from_black_alpha(170);
const STAR_POINTS: usize = 5;
/// The width of the outline that smooths the star's edges (a mesh has no anti-aliasing), in points
const STAR_EDGE_WIDTH: f32 = 0.6;
/// A favorite asset by its [`ShelfEntry::identity`]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShelfFavorite {
pub kind: String,
pub id: String,
}
impl ShelfFavorite {
fn is(&self, entry: &ShelfEntry) -> bool {
let (kind, id) = entry.identity();
self.kind == kind && self.id == id
}
}
/// Where `entry` is in `favorites` (most recently added first), or None if it isn't one
pub(crate) fn rank(favorites: &[ShelfFavorite], entry: &ShelfEntry) -> Option<usize> {
favorites.iter().position(|favorite| favorite.is(entry))
}
/// Adds `entry` in front of `favorites`, or removes it if it is one
pub(crate) fn toggle(favorites: &mut Vec<ShelfFavorite>, entry: &ShelfEntry) {
if let Some(index) = rank(favorites, entry) {
favorites.remove(index);
return;
}
let (kind, id) = entry.identity();
favorites.insert(0, ShelfFavorite { kind: kind.to_owned(), id: id.to_owned() });
}
/// A filled star in `color` at the thumbnail's top-right corner, over a dark shadow
pub(crate) fn star(painter: &Painter, thumbnail: Rect, color: Color32) {
let center = thumbnail.right_top() + vec2(-STAR_INSET, STAR_INSET);
star_shape(painter, center + vec2(STAR_SHADOW_OFFSET, STAR_SHADOW_OFFSET), STAR_SHADOW);
star_shape(painter, center, color);
}
/// A five-pointed star around `center`, point up: a triangle fan from the centre, outlined in its colour
fn star_shape(painter: &Painter, center: Pos2, color: Color32) {
let corner_count = STAR_POINTS * 2;
let corners: Vec<Pos2> = (0..corner_count)
.map(|corner| {
let radius = if corner % 2 == 0 { STAR_OUTER_RADIUS } else { STAR_INNER_RADIUS };
let angle = corner as f32 * std::f32::consts::TAU / corner_count as f32 - std::f32::consts::FRAC_PI_2;
center + radius * vec2(angle.cos(), angle.sin())
})
.collect();
let mut mesh = Mesh::default();
mesh.colored_vertex(center, color);
for corner in &corners {
mesh.colored_vertex(*corner, color);
}
let last = corner_count as u32;
for corner in 1..=last {
mesh.add_triangle(0, corner, corner % last + 1);
}
painter.add(Shape::mesh(mesh));
painter.add(Shape::closed_line(corners, Stroke::new(STAR_EDGE_WIDTH, color)));
}
+477
View File
@@ -0,0 +1,477 @@
//! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it; the Name of an asset the user owns is a field that renames it
use egui::{Align2, Color32, CornerRadius, FontId, Id, Response, Sense, Ui, pos2, vec2};
use serde_json::json;
use crate::TextureCraftApp;
use crate::i18n::{n_, tr};
use crate::shelf_entry::{LIBRARIES, ShelfEntry};
use crate::theme::Tokens;
/// A menu row's height and the inset of its hover face from the menu's sides, in points
const ROW_HEIGHT: f32 = 24.0;
const HOVER_INSET: f32 = 3.0;
const HOVER_ROUNDING: u8 = 3;
/// Where a row's text starts, from the menu's left edge, in points
const TEXT_X: f32 = 10.0;
/// The space after the text of the widest row, in points
const RIGHT_PADDING: f32 = 24.0;
/// The air between the info block's label column and its values, in points
const LABEL_GAP: f32 = 12.0;
/// The widest the info block's values get before the path is cut in the middle, in points
const MAX_VALUE_WIDTH: f32 = 220.0;
/// The menu's text size, in points
const TEXT_SIZE: f32 = 12.0;
/// The Name field's row and field heights, and the air before its text, in points
const FIELD_ROW_HEIGHT: f32 = 28.0;
const FIELD_HEIGHT: f32 = 24.0;
const FIELD_TEXT_INSET: f32 = 8.0;
/// The air above and below the separators, in points
const SEPARATOR_SPACE: f32 = 3.0;
/// The category's place in an asset's path: after the library and the type's folder
const CATEGORY_PART: usize = 2;
/// A menu just opened from the keyboard gives the focus to its first row that can be picked (ctx temp data)
const FOCUS_FIRST_ROW: &str = "shelf_menu_focus_first_row";
/// The right-click menu on the tile whose response is `response`
pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &ShelfEntry) {
// Clicks inside keep the menu open, so the Name field can be typed in; its rows close it themselves
let mut menu = egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside);
response.ctx.accesskit_node_builder(response.id, |node| node.set_has_popup(egui::accesskit::HasPopup::Menu));
// The keyboard opens it on the focused tile, and Escape gives the focus back to the tile
let keyboard_id = response.id.with("menu_from_keyboard");
let return_focus = menu.is_open() && response.ctx.input(|input| input.key_pressed(egui::Key::Escape));
if response.has_focus()
&& response
.ctx
.input_mut(|input| input.consume_key(egui::Modifiers::SHIFT, egui::Key::F10) || input.consume_key(egui::Modifiers::NONE, egui::Key::Menu))
{
menu = menu.open_memory(Some(egui::SetOpenCommand::Bool(true)));
response.ctx.data_mut(|data| {
data.insert_temp(keyboard_id, true);
data.insert_temp(Id::unique(FOCUS_FIRST_ROW), true);
});
} else if response.secondary_clicked() {
response.ctx.data_mut(|data| data.remove::<bool>(keyboard_id));
}
// A menu opened from the keyboard has no pointer position to open at: it opens at the tile
if response.ctx.data(|data| data.get_temp::<bool>(keyboard_id)).unwrap_or_default() {
menu = menu.anchor(response);
}
menu.show(|ui| {
let tokens = Tokens::get(ui.ctx());
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
let info = info_rows(entry);
let width = menu_width(ui, &info, &row_labels(entry));
ui.set_width(width);
let column = label_column(ui, &info);
// A saved brush or a project image is the user's own: its Name row is a field that renames it
let mut shown_info = info.as_slice();
let rename = match entry {
ShelfEntry::SavedBrush { name, .. } => Some((name.as_str(), "brush.preset.rename")),
ShelfEntry::Image(name) => Some((name.as_str(), "resource.rename")),
_ => None,
};
if let Some((name, command)) = rename
&& let Some((_, rest)) = info.split_first()
{
shown_info = rest;
let field_id = ui.make_persistent_id(("asset_name", entry.identity()));
if let Some(renamed) = name_field(ui, width, column, field_id, name, &tokens)
&& let Some(result) = app.run(command, json!({"name": name, "to": renamed}))
&& let Some(new_name) = result["name"].as_str()
{
// The rows below would act on the old name: the menu draws again under the new one next frame
keep_star_and_preview(app, entry, new_name);
return;
}
}
info_block(ui, width, column, shown_info, &tokens);
separator(ui, &tokens);
match entry {
ShelfEntry::Image(name) => {
let reloadable = app.session.doc.project.resource_sources.contains_key(name);
let reload = row(ui, width, tr("Reload"), reloadable, &tokens);
if reload.clicked() {
crate::shelf_updates::update_from_files(app, Some(vec![name.clone()]));
ui.close();
}
if !reloadable {
reload.on_hover_text(tr("Not imported from a file: no file to reload from"));
}
if row(ui, width, tr("Delete"), true, &tokens).clicked() {
app.run("resource.remove", json!({"name": name}));
ui.close();
}
separator(ui, &tokens);
if row(ui, width, tr("Export resource..."), true, &tokens).clicked() {
export_image(app, name);
ui.close();
}
}
ShelfEntry::SavedBrush { name, .. } => {
if row(ui, width, tr("Replace with the current brush"), true, &tokens).clicked() {
app.run("brush.preset.store", json!({"name": name, "overwrite": true}));
ui.close();
}
if row(ui, width, tr("Delete"), true, &tokens).clicked() {
app.run("brush.preset.delete", json!({"name": name}));
ui.close();
}
separator(ui, &tokens);
if row(ui, width, tr("Export resource..."), true, &tokens).clicked() {
export_brush(app, name);
ui.close();
}
}
_ => {
row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export"));
}
}
custom_preview_rows(app, ui, width, entry, &tokens);
show_in(app, ui, width, entry, &tokens);
if row(ui, width, favorite_label(app, entry), true, &tokens).clicked() {
crate::shelf_favorite::toggle(&mut app.ui.shelf_favorites, entry);
ui.close();
}
if let ShelfEntry::Image(name) = entry {
separator(ui, &tokens);
if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() {
app.run("layer.add.decal", json!({"image": name}));
ui.close();
}
}
separator(ui, &tokens);
if row(ui, width, tr("Close"), true, &tokens).clicked() {
ui.close();
}
});
if return_focus {
response.request_focus();
}
}
/// Moves the favorite star and custom preview of `entry`, just renamed to `new_name`, to its new identity
fn keep_star_and_preview(app: &mut TextureCraftApp, entry: &ShelfEntry, new_name: &str) {
let (kind, old_id) = entry.identity();
let new_id = match entry {
ShelfEntry::SavedBrush { .. } => app
.session
.brush_presets
.list
.iter()
.find(|preset| preset.name == new_name)
.map(|preset| preset.file.as_ref().and_then(|file| file.to_str()).unwrap_or(&preset.name).to_owned()),
_ => Some(new_name.to_owned()),
};
let Some(new_id) = new_id else { return };
let ui = &mut app.ui;
let favorites = ui.shelf_favorites.iter_mut().map(|favorite| (&favorite.kind, &mut favorite.id));
let previews = ui.shelf_custom_previews.iter_mut().map(|preview| (&preview.kind, &mut preview.id));
for (_, id) in favorites.chain(previews).filter(|(stored_kind, id)| *stored_kind == kind && *id == old_id) {
id.clone_from(&new_id);
}
}
/// The info block's label and value rows: rows only where the asset has the data
fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> {
let path = entry.path();
let shown_path: Vec<&str> = path.iter().map(|part| LIBRARIES.iter().find(|(id, _)| id == part).map_or_else(|| tr(part), |(_, name)| tr(name))).collect();
let mut rows =
vec![(tr("Name"), entry.label().to_string()), (tr("Usages"), tr(entry.usage()).to_string()), (tr("Path"), format!("/{}/", shown_path.join("/")))];
if let Some(category) = path.get(CATEGORY_PART) {
rows.push((tr("Category"), tr(category).to_string()));
}
rows
}
/// The labels of the rows under the info block, for the menu's width
fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> {
let mut labels = vec![
tr("Export resource..."),
tr("Set custom preview..."),
tr("Remove custom preview"),
tr("Show in"),
tr("Add to favorites"),
tr("Remove from favorites"),
tr("Close"),
];
match entry {
ShelfEntry::Image(_) => labels.extend([tr("Reload"), tr("Delete"), tr("Add as decal (view center)")]),
ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]),
_ => {}
}
labels
}
/// Set custom preview... picks a picture to show on the tile; Remove custom preview, once one is set, shows the asset's own thumbnail again
fn custom_preview_rows(app: &mut TextureCraftApp, ui: &mut Ui, width: f32, entry: &ShelfEntry, tokens: &Tokens) {
if row(ui, width, tr("Set custom preview..."), true, tokens).clicked() {
pick_custom_preview(app, entry);
ui.close();
}
if crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry).is_some()
&& row(ui, width, tr("Remove custom preview"), true, tokens).clicked()
{
crate::shelf_custom_preview::remove(&mut app.ui.shelf_custom_previews, entry);
ui.close();
}
}
/// Asks for a picture, then shows it on `entry`'s tile
#[cfg(not(target_arch = "wasm32"))]
fn pick_custom_preview(app: &mut TextureCraftApp, entry: &ShelfEntry) {
use crate::file_dialogs::{Bound, FileDialog};
let (kind, id) = entry.identity();
let (kind, id) = (kind.to_owned(), id.to_owned());
let dialog = FileDialog::open().filter(tr("Images"), crate::web_files::IMAGE_EXTS);
app.ask_file(dialog, Bound::App, move |app, paths| {
let Some(file) = paths.into_iter().next() else { return };
if image::image_dimensions(&file).is_err() {
app.toast(crate::i18n::trf("Could not read {file} as a picture", &[("file", &file.display())]), true);
return;
}
app.thumbs.forget_custom_preview(&file);
crate::shelf_custom_preview::set(&mut app.ui.shelf_custom_previews, kind, id, file);
});
}
#[cfg(target_arch = "wasm32")]
fn pick_custom_preview(app: &mut TextureCraftApp, _: &ShelfEntry) {
app.toast(tr("Custom previews need the desktop app"), true);
}
/// The row that adds the asset to the favorites, or takes a favorite out
fn favorite_label(app: &TextureCraftApp, entry: &ShelfEntry) -> &'static str {
if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() { tr("Remove from favorites") } else { tr("Add to favorites") }
}
fn text_width(ui: &Ui, text: &str) -> f32 {
ui.fonts_mut(|fonts| fonts.layout_no_wrap(text.to_owned(), FontId::proportional(TEXT_SIZE), Color32::WHITE).size().x)
}
/// The label column's width: the longest label and its gap
fn label_column(ui: &Ui, info: &[(&str, String)]) -> f32 {
info.iter().map(|(label, _)| text_width(ui, label)).fold(0.0, f32::max) + LABEL_GAP
}
/// The widest row, the info block's values capped at [`MAX_VALUE_WIDTH`]
fn menu_width(ui: &Ui, info: &[(&str, String)], labels: &[&str]) -> f32 {
let widest_value = info.iter().map(|(_, value)| text_width(ui, value)).fold(0.0, f32::max).min(MAX_VALUE_WIDTH);
let widest_row = labels.iter().map(|label| text_width(ui, label)).fold(0.0, f32::max);
TEXT_X + (label_column(ui, info) + widest_value).max(widest_row) + RIGHT_PADDING
}
/// The label (dim) and value rows, values `column` points after the labels; a value too wide is cut in the middle with "…"
fn info_block(ui: &mut Ui, width: f32, column: f32, info: &[(&str, String)], tokens: &Tokens) {
let value_width = width - TEXT_X - column - RIGHT_PADDING;
for (label, value) in info {
let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover());
let shown = cut_middle(ui, value, value_width);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{label} {value}")));
let painter = ui.painter();
painter.text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, *label, FontId::proportional(TEXT_SIZE), tokens.text_dim);
painter.text(pos2(rect.left() + TEXT_X + column, rect.center().y), Align2::LEFT_CENTER, shown, FontId::proportional(TEXT_SIZE), tokens.text);
}
}
/// The Name row of an asset the user owns: a field in the value column that returns the new name once typing ends (Enter or a click elsewhere) with a changed, non-blank name. Escape keeps the old one
fn name_field(ui: &mut Ui, width: f32, column: f32, field_id: egui::Id, name: &str, tokens: &Tokens) -> Option<String> {
let (rect, _) = ui.allocate_exact_size(vec2(width, FIELD_ROW_HEIGHT), Sense::hover());
let label = tr("Name");
ui.painter().text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), tokens.text_dim);
// Check raw Escape even if the menu consumed it
let escaped = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })));
if escaped {
ui.data_mut(|data| data.remove::<String>(field_id));
}
let mut text = ui.data(|data| data.get_temp::<String>(field_id)).unwrap_or_else(|| name.to_owned());
// The field's text lines up with the values below it
let field = egui::Rect::from_min_max(
pos2(rect.left() + TEXT_X + column - FIELD_TEXT_INSET, rect.center().y - FIELD_HEIGHT / 2.0),
pos2(rect.right() - TEXT_X, rect.center().y + FIELD_HEIGHT / 2.0),
);
ui.painter().rect(field, CornerRadius::same(HOVER_ROUNDING), tokens.field, egui::Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside);
let edit = egui::TextEdit::singleline(&mut text)
.id(field_id)
.font(FontId::proportional(TEXT_SIZE))
.text_color(tokens.text)
.frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(FIELD_TEXT_INSET as i8, 0)))
.align(Align2::LEFT_CENTER);
let response = ui.new_child(egui::UiBuilder::new().max_rect(field.shrink(1.0))).add_sized(field.shrink(1.0).size(), edit);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, label));
if response.has_focus() {
ui.data_mut(|data| data.insert_temp(field_id, text));
return None;
}
ui.data_mut(|data| data.remove::<String>(field_id));
let typed = text.trim();
(response.lost_focus() && !escaped && !typed.is_empty() && typed != name).then(|| typed.to_owned())
}
/// `text`, or its start and end around "…" so it fits `width` points
fn cut_middle(ui: &Ui, text: &str, width: f32) -> String {
if text_width(ui, text) <= width {
return text.to_owned();
}
let chars: Vec<char> = text.chars().collect();
let mut kept = chars.len();
loop {
let head = kept.div_ceil(2);
let tail = kept / 2;
let cut: String = chars[..head].iter().chain(['…'].iter()).chain(chars[chars.len() - tail..].iter()).collect();
if kept == 0 || text_width(ui, &cut) <= width {
return cut;
}
kept -= 1;
}
}
/// A hairline across the menu between groups of rows
fn separator(ui: &mut Ui, tokens: &Tokens) {
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), SEPARATOR_SPACE * 2.0 + 1.0), Sense::hover());
ui.painter().hline(rect.x_range(), rect.center().y, egui::Stroke::new(1.0, tokens.separator));
}
/// The file manager's own name for showing a file in it
fn show_in_folder_label() -> &'static str {
if cfg!(target_os = "windows") {
tr("Show in Explorer...")
} else if cfg!(target_os = "macos") {
tr("Show in Finder...")
} else {
tr("Show in file manager...")
}
}
/// The Show in row: a submenu that opens the folder of the asset's file, greyed for an asset with no file on this computer
fn show_in(app: &mut TextureCraftApp, ui: &mut Ui, width: f32, entry: &ShelfEntry, tokens: &Tokens) {
let file = match entry {
ShelfEntry::SavedBrush { name, .. } => app.session.brush_presets.file_for(name),
ShelfEntry::Image(name) => app.session.doc.project.resource_sources.get(name).map(|source| std::path::PathBuf::from(&source.path)),
_ => None,
};
let folder = file.as_deref().and_then(std::path::Path::parent).filter(|folder| folder.is_dir()).map(std::path::Path::to_path_buf);
// Reserved under the row, so the row stays highlighted while its submenu is open
let open_highlight = ui.painter().add(egui::Shape::Noop);
let response = row(ui, width, tr("Show in"), folder.is_some(), tokens);
let caret_color = if folder.is_some() { tokens.text } else { tokens.text_dim };
ui.painter().text(
pos2(response.rect.right() - TEXT_X, response.rect.center().y),
Align2::RIGHT_CENTER,
egui_phosphor::regular::CARET_RIGHT,
FontId::proportional(TEXT_SIZE),
caret_color,
);
let Some(folder) = folder else {
let reason = match (file.is_some(), entry) {
(true, _) => n_("The folder of this asset's file is gone"),
(false, ShelfEntry::Image(_)) => n_("Imported before this session: no file to show"),
(false, ShelfEntry::SavedBrush { .. }) => n_("This brush isn't saved to a file"),
(false, _) => n_("Built-in assets have no file to show"),
};
response.on_hover_text(tr(reason));
return;
};
let submenu = egui::containers::menu::SubMenu::new().show(ui, &response, |ui| {
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
let label = show_in_folder_label();
let submenu_width = text_width(ui, label) + TEXT_X + RIGHT_PADDING;
if row(ui, submenu_width, label, true, tokens).clicked() {
open_folder(app, &folder);
ui.close();
}
});
if submenu.is_some() {
let highlight = egui::Shape::rect_filled(response.rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::same(HOVER_ROUNDING), tokens.button);
ui.painter().set(open_highlight, highlight);
}
}
#[cfg(not(target_arch = "wasm32"))]
fn open_folder(app: &mut TextureCraftApp, folder: &std::path::Path) {
if let Err(error) = app.file_dialogs.show_folder(folder) {
app.toast(crate::i18n::trf("Could not open the folder: {error}", &[("error", &error)]), true);
}
}
#[cfg(target_arch = "wasm32")]
fn open_folder(app: &mut TextureCraftApp, _: &std::path::Path) {
app.toast(tr("Showing files needs the desktop app"), true);
}
/// One menu row: a hover face inset from the sides, its text dim and unclickable when not `enabled`
fn row(ui: &mut Ui, width: f32, label: &str, enabled: bool, tokens: &Tokens) -> Response {
let sense = if enabled { Sense::click() } else { Sense::hover() };
let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), sense);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label));
if enabled && ui.data_mut(|data| data.remove_temp::<bool>(Id::unique(FOCUS_FIRST_ROW))).unwrap_or_default() {
response.request_focus();
}
let painter = ui.painter();
if enabled && (response.hovered() || response.has_focus()) {
painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::same(HOVER_ROUNDING), tokens.button);
}
let color = if enabled { tokens.text } else { tokens.text_dim };
painter.text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), color);
if enabled { response } else { response.on_hover_cursor(egui::CursorIcon::NotAllowed) }
}
/// Asks where to save image resource `name`, then writes it there as imported
#[cfg(not(target_arch = "wasm32"))]
fn export_image(app: &mut TextureCraftApp, name: &str) {
use crate::file_dialogs::{Bound, FileDialog};
let extension = std::path::Path::new(name).extension().and_then(|extension| extension.to_str()).unwrap_or_default().to_owned();
let name = name.to_owned();
let dialog = FileDialog::save().filter(tr("Image"), &[extension.as_str()]).file_name(&name);
app.ask_file(dialog, Bound::Project, move |app, paths| {
if let Some(path) = paths.first() {
app.run("resource.export", json!({"name": name, "path": path.to_string_lossy()}));
}
});
}
#[cfg(target_arch = "wasm32")]
fn export_image(app: &mut TextureCraftApp, _: &str) {
app.toast(tr("Exporting resources needs the desktop app"), true);
}
/// Asks where to save saved brush `name`, then writes it there as a brush preset file
#[cfg(not(target_arch = "wasm32"))]
fn export_brush(app: &mut TextureCraftApp, name: &str) {
use crate::file_dialogs::{Bound, FileDialog};
use texturecraft_engine::brush_preset_cmds::BRUSH_EXT;
let name = name.to_owned();
let dialog = FileDialog::save().filter(tr("Brush preset"), &[BRUSH_EXT]).file_name(format!("{name}.{BRUSH_EXT}"));
app.ask_file(dialog, Bound::App, move |app, paths| {
if let Some(path) = paths.first() {
app.run("brush.preset.export", json!({"name": name, "path": path.to_string_lossy()}));
}
});
}
#[cfg(target_arch = "wasm32")]
fn export_brush(app: &mut TextureCraftApp, _: &str) {
app.toast(tr("Exporting resources needs the desktop app"), true);
}
+60 -12
View File
@@ -15,12 +15,17 @@ use crate::theme::Tokens;
use crate::unavailable::NOT_AVAILABLE;
use crate::widgets::icon_button;
const COLUMN_FRACTION: f32 = 0.45;
const COLUMN_MIN_WIDTH_POINTS: f32 = 110.0;
/// Width of the draggable edge between the panes and the grid
const EDGE_WIDTH_POINTS: f32 = 6.0;
/// The grid keeps at least this much width when the edge is dragged right
const GRID_MIN_WIDTH_POINTS: f32 = 80.0;
const SPLITTER_HEIGHT_POINTS: f32 = 6.0;
const PANE_MIN_HEIGHT_POINTS: f32 = 40.0;
/// The reference's built-in saved searches after "All", shown greyed until they work
const BUILT_IN_SEARCHES: [&str; 3] = [n_("Favorites"), n_("3D Assets"), n_("Flattened layers")];
/// The built-in saved search after "All" that shows only the favorite assets
const FAVORITES: &str = n_("Favorites");
/// The reference's other built-in saved searches, shown greyed until they work
const UNAVAILABLE_SEARCHES: [&str; 2] = [n_("3D Assets"), n_("Flattened layers")];
/// The reference's font libraries after the asset libraries, shown greyed until they work
const FONT_LIBRARIES: [&str; 2] = [n_("System fonts"), n_("User fonts")];
/// The pane header's caption size in points
@@ -49,7 +54,29 @@ pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) {
/// The width of the panes' column in a panel `width` wide, or None while no pane is open
pub(crate) fn column_width(app: &TextureCraftApp, width: f32) -> Option<f32> {
let panes = &app.ui.shelf_panes;
(panes.saved_searches || panes.filter_by_path).then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH_POINTS).min(width))
let share = app.ui.shelf_panes_share;
(panes.saved_searches || panes.filter_by_path)
.then(|| (width * share).min(width - EDGE_WIDTH_POINTS - GRID_MIN_WIDTH_POINTS).max(COLUMN_MIN_WIDTH_POINTS).min(width))
}
/// The draggable edge between the panes' column (`column` wide) and the grid in a panel `width` wide
pub(crate) fn edge(app: &mut TextureCraftApp, ui: &mut Ui, column: f32, width: f32) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(EDGE_WIDTH_POINTS, ui.available_height()), egui::Sense::hover());
let visuals = ui.visuals();
let line_stroke = visuals.widgets.noninteractive.bg_stroke;
let widest = (width - EDGE_WIDTH_POINTS - GRID_MIN_WIDTH_POINTS).max(COLUMN_MIN_WIDTH_POINTS);
if width > 0.0 && widest > COLUMN_MIN_WIDTH_POINTS {
let colors =
ResizeHandleStyle { hovered: visuals.widgets.hovered.bg_fill, dragged: visuals.widgets.active.bg_fill, focused: visuals.selection.bg_fill };
let delta = ResizeHandle::new(ui.scope_id().with("shelf_panes_edge"), Axis::X, rect, tr("Resize Assets filter panes and grid"), colors)
.hit_margin(0.0)
.value(column.clamp(COLUMN_MIN_WIDTH_POINTS, widest), COLUMN_MIN_WIDTH_POINTS..=widest)
.show(ui);
if delta != 0.0 {
app.ui.shelf_panes_share = (column + delta).clamp(COLUMN_MIN_WIDTH_POINTS, widest) / width;
}
}
ui.painter().vline(rect.center().x, rect.y_range(), line_stroke);
}
/// Draws the open panes and a divider when both are visible.
@@ -193,7 +220,12 @@ fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) {
});
}
/// "All", then the saved queries; the header's button saves the current one, a right-click deletes one
/// Saved searches' first rows: "All", then Favorites, then the searches that aren't available
const ALL_ROW: usize = 0;
const FAVORITES_ROW: usize = 1;
const FIXED_SEARCH_ROWS: usize = 2;
/// "All", Favorites, then the saved queries; the header's button saves the current one, a right-click deletes one
fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) {
let size = ui.spacing().interact_size.y;
header(ui, tr("Saved searches"), |ui| {
@@ -205,8 +237,9 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) {
}
});
let all_selected = app.ui.shelf_filter.is_empty() && app.ui.shelf_path.is_empty() && app.ui.shelf_tab == crate::shelf_tabs::NO_TYPE;
let first_saved_row = 1 + BUILT_IN_SEARCHES.len();
let favorites_only = app.ui.shelf_favorites_only;
let all_selected = !favorites_only && app.ui.shelf_filter.is_empty() && app.ui.shelf_path.is_empty() && app.ui.shelf_tab == crate::shelf_tabs::NO_TYPE;
let first_saved_row = FIXED_SEARCH_ROWS + UNAVAILABLE_SEARCHES.len();
let row_height = ui.spacing().interact_size.y;
let total_rows = first_saved_row + app.ui.shelf_saved_searches.len();
let mut deleted_index = None;
@@ -218,14 +251,22 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) {
total_rows,
|ui, visible_rows| {
for row in visible_rows {
if row == 0 {
if row == ALL_ROW {
if ui.selectable_label(all_selected, tr("All")).clicked() {
crate::shelf_toolbar::reset_query(app);
}
continue;
}
if let Some(name) = BUILT_IN_SEARCHES.get(row - 1) {
if row == FAVORITES_ROW {
if ui.selectable_label(favorites_only, tr(FAVORITES)).clicked() {
crate::shelf_toolbar::reset_query(app);
app.ui.shelf_favorites_only = true;
}
continue;
}
if let Some(name) = UNAVAILABLE_SEARCHES.get(row - FIXED_SEARCH_ROWS) {
ui.add_enabled(false, egui::Button::selectable(false, tr(name))).on_disabled_hover_text(tr(NOT_AVAILABLE));
continue;
}
@@ -233,10 +274,14 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) {
let saved_index = row - first_saved_row;
let Some(saved) = app.ui.shelf_saved_searches.get(saved_index) else { continue };
let selected = saved.filter == app.ui.shelf_filter && saved.tab == app.ui.shelf_tab && saved.path == app.ui.shelf_path;
let selected = saved.favorites_only == favorites_only
&& saved.filter == app.ui.shelf_filter
&& saved.tab == app.ui.shelf_tab
&& saved.path == app.ui.shelf_path;
let response = ui.selectable_label(selected, &saved.name);
if response.clicked() {
(app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone());
app.ui.shelf_favorites_only = saved.favorites_only;
}
response.context_menu(|ui| {
@@ -254,18 +299,21 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) {
}
}
/// The shelf's query, named after its search text, else its folder, else its tab
/// The shelf's query, named after its search text, else its folder, else Favorites, else its tab
fn current_query(app: &TextureCraftApp) -> SavedSearch {
let filter = &app.ui.shelf_filter;
let tab = app.ui.shelf_tab;
let path = &app.ui.shelf_path;
let favorites_only = app.ui.shelf_favorites_only;
let name = if !filter.is_empty() {
filter.as_str()
} else if let Some(folder) = path.last() {
crate::shelf_folders::name(path.len() - 1, folder)
} else if favorites_only {
tr(FAVORITES)
} else {
TABS.get(tab).map_or_else(|| tr("All"), |(_, _, label)| tr(label))
};
SavedSearch { name: name.to_owned(), filter: filter.clone(), tab, path: path.clone() }
SavedSearch { name: name.to_owned(), filter: filter.clone(), tab, path: path.clone(), favorites_only }
}
+24
View File
@@ -0,0 +1,24 @@
//! One Assets panel's query: search, type, folder and favorites only
use serde::{Deserialize, Serialize};
/// One Assets panel's search, type and folder, and whether it shows only favorites
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ShelfQuery {
/// The search text
pub filter: String,
/// The picked type: an index into the shelf's types, or past them for every type
pub tab: usize,
/// The library folder: a library id, then folder names (empty: all libraries)
pub path: Vec<String>,
/// Only favorites (the Favorites saved search)
pub favorites_only: bool,
}
impl Default for ShelfQuery {
/// Every asset of every type
fn default() -> Self {
Self { filter: String::new(), tab: crate::shelf_tabs::NO_TYPE, path: Vec::new(), favorites_only: false }
}
}
+23
View File
@@ -0,0 +1,23 @@
//! The second Assets panel, opened by the folder button: the same panel with its own query
use egui::Ui;
use crate::TextureCraftApp;
use crate::shelf_query::ShelfQuery;
/// Swap `query` with the first Assets panel's query in `ui`
fn swap_query(ui: &mut crate::state::UiState, query: &mut ShelfQuery) {
std::mem::swap(&mut ui.shelf_filter, &mut query.filter);
std::mem::swap(&mut ui.shelf_tab, &mut query.tab);
std::mem::swap(&mut ui.shelf_path, &mut query.path);
std::mem::swap(&mut ui.shelf_favorites_only, &mut query.favorites_only);
}
/// The second Assets panel's body: the Assets panel drawn with its own query
pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
let mut query = std::mem::take(&mut app.ui.shelf_second);
swap_query(&mut app.ui, &mut query);
ui.push_id("assets_second", |ui| crate::shelf::body(app, ui));
swap_query(&mut app.ui, &mut query);
app.ui.shelf_second = query;
}
+7 -16
View File
@@ -1,4 +1,4 @@
//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query and import on the right
//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query, new panel and import on the right
use egui::Ui;
use egui_phosphor::regular as ic;
@@ -18,6 +18,7 @@ pub(crate) fn height(ui: &Ui) -> f32 {
/// The toolbar
pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
let size = ui.spacing().interact_size.y;
let panel = ui.max_rect();
ui.add_space(GAP_ABOVE);
ui.horizontal(|ui| {
crate::shelf_panes::toggles(app, ui, size);
@@ -25,12 +26,13 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
if icon_button(ui, ic::PLUS, tr("Import resources..."), false, size).clicked() {
crate::menus::invoke(app, &ui.ctx().clone(), "resource.import");
}
if icon_button(ui, ic::FOLDER, tr("New Assets panel"), false, size).clicked() {
app.ui.dock.focus(crate::docking::Panel::AssetsSecond);
}
if icon_button(ui, ic::X_CIRCLE, tr("Reset query"), false, size).clicked() {
reset_query(app);
}
if icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Refresh"), false, size).clicked() {
refresh(app);
}
crate::shelf_updates::button(app, ui, size, panel);
});
});
}
@@ -40,16 +42,5 @@ pub(crate) fn reset_query(app: &mut TextureCraftApp) {
app.ui.shelf_filter.clear();
app.ui.shelf_tab = crate::shelf_tabs::NO_TYPE;
app.ui.shelf_path.clear();
}
/// Read the user's saved assets from disk again and redraw their thumbnails
fn refresh(app: &mut TextureCraftApp) {
app.library = None;
#[cfg(not(target_arch = "wasm32"))]
for warning in app.session.load_brush_presets(crate::user_dir("brushes")) {
app.toast(warning, true);
}
app.thumbs.forget_saved_files();
app.ui.shelf_favorites_only = false;
}
+231
View File
@@ -0,0 +1,231 @@
//! The shelf's refresh popup: read the Assets panel and the project's images again every few minutes, or now by hand
use egui::{Context, Id, Ui, vec2};
use egui_phosphor::regular as ic;
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::TextureCraftApp;
use crate::i18n::{n_, tr};
use crate::property_sheet::{NumberField, PropertySheet, SIDE_PADDING_POINTS, SectionScope, in_scope};
use crate::widgets::icon_dropdown_button;
/// Least and most minutes between automatic updates
const MIN_MINUTES: u32 = 1;
const MAX_MINUTES: u32 = 24 * 60;
/// Air between the popup and the toolbar under it
const POPUP_GAP: f32 = 1.0;
/// Air between the two update buttons and under the last one
const BUTTON_GAP: f32 = 6.0;
/// Room right of a row's switch for its i
const INFO_COLUMN: f32 = 28.0;
/// How soon a run that waited for a stroke tries again
const STROKE_RETRY: std::time::Duration = std::time::Duration::from_millis(250);
/// A drag of 20 points moves the minutes by one
const MINUTES_PER_DRAG_POINT: f32 = 0.05;
/// How much shorter a manual update button is than a sheet row, so neighbouring buttons don't touch
const BUTTON_INSET: f32 = 4.0;
const SKIP_MISMATCH: &str = n_("Skip assets when their parameters mismatch");
/// Which automatic updates are on and how often they run
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ShelfUpdates {
/// Read the user's saved assets again
pub assets: bool,
/// Read the project's images again from the files they were imported from when a file changed
pub resources: bool,
pub minutes: u32,
}
impl Default for ShelfUpdates {
fn default() -> Self {
ShelfUpdates { assets: false, resources: false, minutes: MIN_MINUTES }
}
}
/// When the automatic updates last ran, on egui's clock
fn last_run_id() -> Id {
Id::unique("shelf_updates_last_run")
}
/// Runs the automatic updates once their minutes have passed since the last run, and wakes the app for the next one
pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &Context) {
let updates = app.ui.shelf_updates;
if !updates.assets && !updates.resources {
ctx.data_mut(|data| data.remove::<f64>(last_run_id()));
return;
}
// An update during a stroke would land in the stroke's undo step: it waits for the stroke to end
if app.session.stroke_active() {
ctx.request_repaint_after(STROKE_RETRY);
return;
}
let now = ctx.input(|input| input.time);
let every = f64::from(updates.minutes.clamp(MIN_MINUTES, MAX_MINUTES)) * 60.0;
let last = ctx.data_mut(|data| *data.get_temp_mut_or(last_run_id(), now));
if now - last < every {
ctx.request_repaint_after(std::time::Duration::from_secs_f64(every - (now - last)));
return;
}
ctx.data_mut(|data| data.insert_temp(last_run_id(), now));
if updates.assets {
refresh_assets(app);
}
if updates.resources {
update_resources(app, ctx);
}
ctx.request_repaint_after(std::time::Duration::from_secs_f64(every));
}
/// Read the user's saved assets from disk again and redraw their thumbnails
pub(crate) fn refresh_assets(app: &mut TextureCraftApp) {
app.library = None;
#[cfg(not(target_arch = "wasm32"))]
for warning in app.session.load_brush_presets(crate::user_dir("brushes")) {
app.toast(warning, true);
}
app.thumbs.forget_saved_files();
}
/// Reads the project's changed image files again; a file that is gone or can't be read says why once, until it reads again
fn update_resources(app: &mut TextureCraftApp, ctx: &Context) {
let Some(status) = app.run("resource.status", json!({})) else { return };
let rows = status["resources"].as_array().cloned().unwrap_or_default();
let mut failures: Vec<(String, String)> =
rows.iter().filter(|row| row["status"] == "missing").map(|row| (text(&row["name"]), text(&row["error"]))).collect();
if status["outdated"].as_u64().is_some_and(|outdated| outdated > 0)
&& let Some(result) = app.run("resource.update", json!({}))
{
failures.extend(result["failed"].as_array().into_iter().flatten().map(|failure| (text(&failure["name"]), text(&failure["error"]))));
}
let reported_id = reported_failures_id(app.session.project_id);
let mut reported: Vec<String> = ctx.data(|data| data.get_temp(reported_id)).unwrap_or_default();
reported.retain(|name| failures.iter().any(|(failed, _)| failed == name));
for (name, error) in failures {
if !reported.contains(&name) {
app.toast(format!("{name}: {error}"), true);
reported.push(name);
}
}
ctx.data_mut(|data| data.insert_temp(reported_id, reported));
}
/// Reads the files of `names` (every changed image when None) again through the Resources Updater, which says what happened
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn update_from_files(app: &mut TextureCraftApp, names: Option<Vec<String>>) {
crate::resources_updater::update(app, names);
}
/// The browser reads no files: the command's refusal says so
#[cfg(target_arch = "wasm32")]
pub(crate) fn update_from_files(app: &mut TextureCraftApp, names: Option<Vec<String>>) {
app.run("resource.update", names.map_or_else(|| json!({}), |names| json!({ "names": names })));
}
/// A string field of a command's result, empty when it has none
fn text(value: &serde_json::Value) -> String {
value.as_str().unwrap_or_default().to_owned()
}
/// The files of project `project_id` whose failure to read was already shown (ctx temp data)
fn reported_failures_id(project_id: u64) -> Id {
Id::unique(("shelf_updates_reported_failures", project_id))
}
/// The refresh button with its popup of update settings, opening upward from the toolbar `panel` with its left edge on the panel's
pub(crate) fn button(app: &mut TextureCraftApp, ui: &mut Ui, size: f32, panel: egui::Rect) {
let label = tr("Refresh");
let response = icon_dropdown_button(ui, ic::ARROWS_CLOCKWISE, label, false, size).on_hover_text(label);
let width = popup_width(ui, panel.width());
egui::Popup::from_toggle_button_response(&response)
.anchor(panel)
.align(egui::RectAlign::TOP_START)
.gap(POPUP_GAP)
.width(width)
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
.show(|ui| {
ui.set_width(width);
popup(app, ui);
});
}
/// The panel's width, or wider to fit the longest row
fn popup_width(ui: &Ui, panel_width: f32) -> f32 {
let font = egui::FontId::proportional(crate::property_sheet::TEXT_SIZE);
let longest = ui.painter().layout_no_wrap(tr(SKIP_MISMATCH).to_owned(), font, egui::Color32::WHITE).size().x;
panel_width.max(longest + crate::property_sheet::TOGGLE_ROOM + INFO_COLUMN + 2.0 * SIDE_PADDING_POINTS)
}
fn popup(app: &mut TextureCraftApp, ui: &mut Ui) {
let updates = &mut app.ui.shelf_updates;
let full = ui.available_rect_before_wrap();
let rows = full.with_max_x(full.right() - INFO_COLUMN);
in_scope(ui, SectionScope::Shelf, |ui| {
ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| {
PropertySheet::show(ui, "shelf_updates", |sheet| {
sheet.section(tr("Automatic updates"), false);
sheet.toggle(tr("Assets panel"), &mut updates.assets);
sheet.beside_info(INFO_COLUMN, tr("Reads your saved assets from disk again every few minutes, so new and changed ones show here."));
sheet.toggle(tr("Resources used in project"), &mut updates.resources);
sheet.beside_info(
INFO_COLUMN,
tr("Every few minutes, reads again the images whose files changed since this project imported them. Each update is one undo step."),
);
let mut minutes = [NumberField {
tag: "",
tag_color: None,
value: updates.minutes as f32,
speed: MINUTES_PER_DRAG_POINT,
decimals: 0,
suffix: tr(" min"),
}];
if sheet.number_fields(tr("Update every"), &mut minutes, None, false).is_some() {
updates.minutes = (minutes[0].value.round() as u32).clamp(MIN_MINUTES, MAX_MINUTES);
}
sheet.beside_info(INFO_COLUMN, tr("How often the automatic updates above run."));
sheet.section(tr("Advanced settings"), false);
sheet.unavailable_toggle(tr(SKIP_MISMATCH));
sheet.beside_info(
INFO_COLUMN,
tr("For assets with parameters: an update whose parameters were renamed or removed would change your texturing, so it is skipped. TextureCraft doesn't update assets with parameters from their files yet, so there is nothing to skip."),
);
sheet.section(tr("Manual"), false);
});
});
});
let button_size = vec2(full.width() - 2.0 * SIDE_PADDING_POINTS, crate::property_sheet::ROW_HEIGHT - BUTTON_INSET);
let add_button = |ui: &mut Ui, label: &str| {
let clicked = ui
.horizontal(|ui| {
ui.add_space(SIDE_PADDING_POINTS);
ui.add_sized(button_size, egui::Button::new(label)).clicked()
})
.inner;
ui.add_space(BUTTON_GAP);
clicked
};
if add_button(ui, tr("Update Assets panel")) {
refresh_assets(app);
}
if add_button(ui, tr("Update resources used in project")) {
update_from_files(app, None);
}
}
+57 -3
View File
@@ -6,6 +6,8 @@ use texturecraft_engine::core::{BakedMap, Channel, ChannelBlend, NormalFormat};
use crate::docking::Dock;
use crate::keymap::Keymap;
use crate::saved_search::SavedSearch;
use crate::shelf_custom_preview::ShelfCustomPreview;
use crate::shelf_favorite::ShelfFavorite;
use crate::shelf_panes::ShelfPanes;
use crate::shelf_view::ShelfView;
@@ -525,6 +527,18 @@ pub(crate) fn default_shelf_panes_split() -> f32 {
0.45
}
/// The share of the Assets panel's width the filter panes take until their edge is dragged
fn default_shelf_panes_share() -> f32 {
0.45
}
fn deserialize_shelf_panes_share<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<f32, D::Error> {
let share = f32::deserialize(deserializer)?;
// A finite JSON number can overflow f32 and prevent the next settings save
Ok(if share.is_finite() { share } else { default_shelf_panes_share() })
}
fn deserialize_shelf_panes_split<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<f32, D::Error> {
let share = f32::deserialize(deserializer)?;
@@ -623,9 +637,27 @@ pub struct UiState {
/// The asset shelf's saved queries, in the order they were saved
#[serde(default)]
pub shelf_saved_searches: Vec<SavedSearch>,
/// The asset shelf's favorite assets, most recently added first
#[serde(default)]
pub shelf_favorites: Vec<ShelfFavorite>,
/// The asset shelf shows only favorites (the Favorites saved search)
#[serde(default)]
pub shelf_favorites_only: bool,
/// The second Assets panel's search, type and folder, swapped in while it draws
#[serde(default)]
pub shelf_second: crate::shelf_query::ShelfQuery,
/// The asset shelf's automatic updates (its refresh popup)
#[serde(default)]
pub shelf_updates: crate::shelf_updates::ShelfUpdates,
/// Pictures the user picked to show on asset tiles instead of their thumbnails
#[serde(default)]
pub shelf_custom_previews: Vec<ShelfCustomPreview>,
/// Saved searches' share of the pane column above Filter by path, set by the splitter between them
#[serde(default = "default_shelf_panes_split", deserialize_with = "deserialize_shelf_panes_split")]
pub shelf_panes_split: f32,
/// The share of the Assets panel's width the filter panes take
#[serde(default = "default_shelf_panes_share", deserialize_with = "deserialize_shelf_panes_share")]
pub shelf_panes_share: f32,
pub props_tab: PropsTab,
#[serde(default)]
pub text: TextUi,
@@ -796,6 +828,11 @@ impl UiState {
self.shelf_tab = keep.shelf_tab;
self.shelf_path = keep.shelf_path;
self.shelf_saved_searches = keep.shelf_saved_searches;
self.shelf_favorites = keep.shelf_favorites;
self.shelf_favorites_only = keep.shelf_favorites_only;
self.shelf_second = keep.shelf_second;
self.shelf_custom_previews = keep.shelf_custom_previews;
self.shelf_updates = keep.shelf_updates;
}
}
@@ -831,7 +868,13 @@ impl Default for UiState {
shelf_view: ShelfView::default(),
shelf_panes: ShelfPanes::default(),
shelf_saved_searches: Vec::new(),
shelf_favorites: Vec::new(),
shelf_favorites_only: false,
shelf_second: crate::shelf_query::ShelfQuery::default(),
shelf_custom_previews: Vec::new(),
shelf_updates: crate::shelf_updates::ShelfUpdates::default(),
shelf_panes_split: default_shelf_panes_split(),
shelf_panes_share: default_shelf_panes_share(),
props_tab: PropsTab::Brush,
text: TextUi::default(),
rename: None,
@@ -978,15 +1021,26 @@ mod tests {
}
#[test]
fn adopting_a_layout_keeps_the_shelf_query_and_saved_searches() {
let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] };
let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], ..UiState::default() };
fn adopting_a_layout_keeps_the_shelf_query_saved_searches_favorites_and_custom_previews() {
let saved =
crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()], favorites_only: false };
let favorite = crate::shelf_favorite::ShelfFavorite { kind: "material".into(), id: "gold".into() };
let mut ui =
UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], shelf_favorites_only: true, ..UiState::default() };
ui.shelf_saved_searches.push(saved.clone());
ui.shelf_favorites.push(favorite.clone());
let preview = crate::shelf_custom_preview::ShelfCustomPreview { kind: "material".into(), id: "gold".into(), file: "gold.png".into() };
ui.shelf_custom_previews.push(preview.clone());
ui.shelf_updates.resources = true;
ui.adopt_layout(UiState::default());
assert_eq!((ui.shelf_filter.as_str(), ui.shelf_tab, ui.shelf_path.as_slice()), ("rust", 2, ["starter".to_string()].as_slice()));
assert_eq!(ui.shelf_saved_searches, [saved]);
assert_eq!(ui.shelf_favorites, [favorite], "favorites are the user's own too");
assert!(ui.shelf_favorites_only, "the Favorites search is part of the query");
assert_eq!(ui.shelf_custom_previews, [preview], "custom previews are the user's own");
assert!(ui.shelf_updates.resources, "automatic updates are a setting, not part of a layout");
}
#[test]
+22
View File
@@ -70,6 +70,8 @@ pub struct Thumbs {
big_shown: VecDeque<String>,
/// The frame that last took in the worker's results
received_in_pass: u64,
/// Pictures the user picked as asset previews, by file; None for a file that doesn't load
custom_previews: HashMap<PathBuf, Option<TextureHandle>>,
/// Per active generator picture size: the current effect, pending key and last finished picture
set_pictures: HashMap<(u64, usize), (Option<String>, Option<TextureHandle>)>,
}
@@ -314,6 +316,26 @@ impl Thumbs {
self.rendered.retain(|key, _| current(key));
self.big_shown.retain(current);
self.saved_brush_previews.clear();
self.custom_previews.clear();
}
/// Load the picture at `file` again next time: the user picked it anew, maybe after changing it
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn forget_custom_preview(&mut self, file: &Path) {
self.custom_previews.remove(file);
}
/// The picture at `file` as an asset's custom preview (its centred square), loaded once; None if it doesn't load
pub(crate) fn custom_preview(&mut self, ctx: &egui::Context, file: &Path) -> Option<TextureHandle> {
self.custom_previews
.entry(file.to_path_buf())
.or_insert_with(|| {
let image = crate::shelf_custom_preview::square(&image::open(file).ok()?);
let size = [image.width() as usize, image.height() as usize];
let pixels = ColorImage::from_rgba_unmultiplied(size, image.as_raw());
Some(ctx.load_texture(format!("custom_preview_{}", file.display()), pixels, TextureOptions::LINEAR))
})
.clone()
}
/// Smart mask thumbnail; None until the worker returns it
@@ -110,7 +110,7 @@ fn an_image_dropped_on_the_slot_becomes_the_environment() {
h.run_steps(SETTLE);
let slot = h.get_by_role_and_label(Role::Button, "Studio Soft").rect().center();
egui::DragAndDrop::set_payload(&h.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into() });
egui::DragAndDrop::set_payload(&h.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into(), thumb: None });
h.hover_at(slot);
h.run_steps(2);
h.event(Event::PointerButton { pos: slot, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
+4
View File
@@ -90,9 +90,13 @@ mod resources_updater;
mod sample_project;
mod settings_window;
mod shelf_click;
mod shelf_drag_ghost;
mod shelf_drop;
mod shelf_hover_preview;
mod shelf_menu;
mod shelf_panel;
mod shelf_second;
mod shelf_updates;
mod shift_lines_2d;
mod shift_lines_3d;
mod shortcut_keys;
+100
View File
@@ -0,0 +1,100 @@
//! A dragged asset or layer shows at the pointer with a badge saying whether the place under it takes it
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::materials::MATERIALS;
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::shelf_drag_ghost::{ShelfDragVerdict, shown};
/// Distance between the view points searched for a set or the background
const SEARCH_STEP: f32 = 8.0;
/// How far the pointer moves off the tile before it counts as a drag
const DRAG_START: f32 = 12.0;
/// The sample project at 1600 x 960, the shelf on Materials
fn sample_app() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(4);
harness
}
/// The first point of the 3D view showing texture set `set`, or the background when `None`
fn point_over(harness: &Harness<'_, TextureCraftApp>, set: Option<usize>) -> Pos2 {
let app = harness.state();
let rect = app.viewport_rect;
let steps = |length: f32| (1..(length / SEARCH_STEP) as usize).map(|step| step as f32 * SEARCH_STEP);
steps(rect.height())
.flat_map(|y| steps(rect.width()).map(move |x| (x, y)))
.find(|&(x, y)| app.session.texture_set_at(Vec2::new(x, y), app.session.viewport) == set)
.map(|(x, y)| rect.min + egui::vec2(x, y))
.unwrap()
}
#[test]
fn the_badge_says_whether_the_place_under_the_pointer_takes_the_asset_without_covering_the_pointer() {
// The grid's first plain material (by name), so its tile is in view
let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap();
let mut harness = sample_app();
let (set, background) = (point_over(&harness, Some(0)), point_over(&harness, None));
let tile = harness.get_all_by_label(material.label).next().unwrap().rect().center();
assert!(shown(&harness.ctx).is_none(), "nothing follows the pointer before a drag");
harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
harness.run_steps(2);
harness.hover_at(tile + vec2(DRAG_START, DRAG_START));
harness.run_steps(2);
let mut seen = Vec::new();
for target in [set, background] {
harness.hover_at(target);
harness.run_steps(2);
let ghost = shown(&harness.ctx).expect("the dragged asset follows the pointer");
assert!(ghost.badge.min.x > target.x && ghost.badge.min.y > target.y, "the badge leaves the pointer's tip clear");
seen.push(ghost.verdict);
}
assert_eq!(seen, [ShelfDragVerdict::Valid, ShelfDragVerdict::NotValid], "a texture set takes a material, the background doesn't");
harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
harness.run_steps(2);
assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends");
}
#[test]
fn a_layer_dragged_in_the_layer_stack_gets_the_same_ghost_and_badge() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
for name in ["Ghost low", "Ghost high"] {
texturecraft_engine::execute(&mut session, "layer.add.paint", &serde_json::json!({ "name": name })).unwrap();
}
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 1200.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(4);
let background = point_over(&harness, None);
let (high, low) = (harness.get_by_label("Ghost high").rect().center(), harness.get_by_label("Ghost low").rect().center());
harness.event(Event::PointerButton { pos: high, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
harness.run_steps(2);
harness.hover_at(high + vec2(DRAG_START, DRAG_START));
harness.run_steps(2);
let mut seen = Vec::new();
for target in [low, background] {
harness.hover_at(target);
harness.run_steps(2);
seen.push(shown(&harness.ctx).expect("the dragged layer follows the pointer").verdict);
}
assert_eq!(seen, [ShelfDragVerdict::Valid, ShelfDragVerdict::NotValid], "another row takes the layer, the 3D view doesn't");
harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
harness.run_steps(2);
assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends");
}
+1 -1
View File
@@ -48,7 +48,7 @@ fn drop_material(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) {
/// Drop shelf `asset` at `position`, as a drag from the shelf ends there
fn drop_asset(harness: &mut Harness<'_, TextureCraftApp>, asset: Asset, position: Pos2) {
egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset, label: "Dragged".into() });
egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset, label: "Dragged".into(), thumb: None });
harness.hover_at(position);
harness.run_steps(2);
+268
View File
@@ -0,0 +1,268 @@
//! An asset tile's right-click menu: the info block says what the asset is, and its rows act on it
use egui::{Key, Modifiers};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use texturecraft_engine::materials::MATERIALS;
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::file_dialogs::Answer;
/// The types' positions in the shelf's type row (its table is crate-private)
const MATERIALS_TYPE: usize = 0;
const BRUSHES_TYPE: usize = 4;
const TEXTURES_TYPE: usize = 6;
/// The sample project with the shelf on type `tab`
fn shelf(tab: usize) -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.shelf_tab = tab;
harness.run_steps(4);
harness
}
fn right_click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) {
harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("no tile {label}")).click_secondary();
harness.run_steps(3);
}
#[test]
fn a_built_in_tile_menu_says_what_the_asset_is_and_where_it_lives() {
// The grid's first plain material (by name), so its tile is in view
let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap();
let mut harness = shelf(MATERIALS_TYPE);
right_click(&mut harness, material.label);
for row in [
format!("Name {}", material.label),
"Usages material".to_string(),
format!("Path /Starter assets/Materials/{}/", material.category),
format!("Category {}", material.category),
] {
assert!(harness.query_by_label(&row).is_some(), "the menu has the info row {row:?}");
}
assert!(harness.get_by_label("Export resource...").accesskit_node().is_disabled(), "a built-in has no file to export");
assert!(harness.get_by_label("Show in").accesskit_node().is_disabled(), "a built-in has no file to show");
harness.get_by_label("Close").click();
harness.run_steps(3);
assert!(harness.query_by_label("Usages material").is_none(), "Close closes the menu");
}
#[test]
fn export_resource_writes_the_image_as_imported() {
let mut harness = shelf(TEXTURES_TYPE);
let mut bytes = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes.clone()).unwrap();
harness.run_steps(3);
let dir = super::temp_dir::TempDir::new("shelf-export-resource");
let target = dir.join("exported.png");
let answer = target.clone();
harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()]))));
right_click(&mut harness, &name);
harness.get_by_label("Export resource...").click();
harness.run_steps(4);
assert_eq!(std::fs::read(&target).unwrap(), bytes, "the exported file is the resource's own bytes");
}
fn preset_names(harness: &Harness<'_, TextureCraftApp>) -> Vec<String> {
harness.state().session.brush_presets.list.iter().map(|preset| preset.name.clone()).collect()
}
/// Selects the menu's Name field text and types `text`
fn type_name(harness: &mut Harness<'_, TextureCraftApp>, text: &str) {
harness.get_by_role_and_label(egui::Role::TextInput, "Name").click();
harness.run_steps(3);
harness.key_press_modifiers(Modifiers::COMMAND, Key::A);
harness.event(egui::Event::Text(text.into()));
harness.run_steps(3);
}
#[test]
fn a_saved_brush_menu_renames_replaces_and_deletes_it() {
// A name that sorts before every built-in brush, so its tile is in view
let mut harness = shelf(BRUSHES_TYPE);
texturecraft_engine::execute(&mut harness.state_mut().session, "brush.preset.store", &json!({"name": "Aa ink"})).unwrap();
harness.run_steps(3);
right_click(&mut harness, "Aa ink");
type_name(&mut harness, "Never applied");
harness.key_press(Key::Escape);
harness.run_steps(3);
assert_eq!(preset_names(&harness), ["Aa ink"], "Escape keeps the name");
right_click(&mut harness, "Aa ink");
type_name(&mut harness, "Aa pen");
harness.key_press(Key::Enter);
harness.run_steps(3);
assert_eq!(preset_names(&harness), ["Aa pen"], "Enter renames the brush");
texturecraft_engine::execute(&mut harness.state_mut().session, "tool.brush", &json!({"size": 77})).unwrap();
right_click(&mut harness, "Aa pen");
harness.get_by_label("Replace with the current brush").click();
harness.run_steps(3);
assert_eq!(harness.state().session.brush_presets.list[0].brush, harness.state().session.tool.brush, "the preset holds the current brush");
right_click(&mut harness, "Aa pen");
harness.get_by_label("Delete").click();
harness.run_steps(3);
assert!(preset_names(&harness).is_empty(), "Delete removes the brush");
}
#[test]
fn delete_removes_a_project_image() {
let mut harness = shelf(TEXTURES_TYPE);
let mut bytes = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap();
harness.run_steps(3);
right_click(&mut harness, &name);
harness.get_by_label("Delete").click();
harness.run_steps(3);
assert!(!harness.state().session.doc.resources.contains_key(&name));
}
#[test]
fn a_project_image_menu_renames_it_keeping_its_star_and_greys_reload_without_a_file() {
let mut harness = shelf(TEXTURES_TYPE);
let mut bytes = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap();
harness.run_steps(3);
pick_from_menu(&mut harness, &name, "Add to favorites");
right_click(&mut harness, &name);
assert!(harness.get_by_label("Reload").accesskit_node().is_disabled(), "an image not imported from a file can't reload");
type_name(&mut harness, "stone");
harness.key_press(Key::Enter);
harness.run_steps(3);
let resources = &harness.state().session.doc.resources;
assert!(resources.contains_key("stone.png") && !resources.contains_key(&name), "Enter renames the image, keeping its extension");
let favorites: Vec<&str> = harness.state().ui.shelf_favorites.iter().map(|favorite| favorite.id.as_str()).collect();
assert_eq!(favorites, ["stone.png"], "the star follows the rename");
}
#[test]
fn show_in_opens_the_folder_of_a_saved_brush() {
let dir = super::temp_dir::TempDir::new("shelf-show-in");
let mut harness = shelf(BRUSHES_TYPE);
harness.state_mut().session.brush_presets.dir = Some(dir.to_path_buf());
texturecraft_engine::execute(&mut harness.state_mut().session, "brush.preset.store", &json!({"name": "Aa ink"})).unwrap();
harness.run_steps(3);
right_click(&mut harness, "Aa ink");
harness.get_by_label("Show in").click();
harness.run_steps(3);
let item = if cfg!(target_os = "windows") {
"Show in Explorer..."
} else if cfg!(target_os = "macos") {
"Show in Finder..."
} else {
"Show in file manager..."
};
harness.get_by_label(item).click();
harness.run_steps(3);
let shown = harness.state().file_dialogs.shown_folders().to_vec();
assert!(shown.iter().any(|folder| folder.canonicalize().ok() == dir.canonicalize().ok()), "the brush's folder is shown: {shown:?}");
}
#[test]
fn shift_f10_opens_the_menu_of_the_focused_tile_on_its_first_row_and_escape_returns_to_it() {
let mut harness = shelf(TEXTURES_TYPE);
let mut bytes = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap();
harness.run_steps(3);
harness.get_all_by_label(&name).next().unwrap().focus();
harness.run_steps(2);
assert!(harness.get_all_by_label(&name).next().unwrap().is_focused(), "the tile takes the focus");
harness.key_press_modifiers(Modifiers::SHIFT, Key::F10);
harness.run_steps(3);
assert!(harness.query_by_label("Usages texture").is_some(), "Shift+F10 opens the menu");
assert!(harness.get_by_label("Delete").is_focused(), "the first row that can be picked takes the focus (Reload can't: no file)");
harness.key_press(Key::Escape);
harness.run_steps(3);
assert!(harness.query_by_label("Usages texture").is_none(), "Escape closes it");
assert!(harness.get_all_by_label(&name).next().unwrap().accesskit_node().is_focused(), "the focus is back on the tile");
}
/// Whether the tile `first` comes before the tile `second` in the grid (rows top to bottom, each left to right)
fn comes_before(harness: &Harness<'_, TextureCraftApp>, first: &str, second: &str) -> bool {
let place = |label: &str| {
let rect = harness.get_by_label(label).rect();
(rect.top(), rect.left())
};
place(first) < place(second)
}
fn pick_from_menu(harness: &mut Harness<'_, TextureCraftApp>, tile: &str, row: &str) {
right_click(harness, tile);
harness.get_by_label(row).click();
harness.run_steps(3);
}
#[test]
fn favorites_come_first_newest_first_with_a_star_until_removed() {
let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect();
plain.sort_by_key(|material| material.label.to_lowercase());
let (first, second, third) = (plain[0].label, plain[1].label, plain[2].label);
let mut harness = shelf(MATERIALS_TYPE);
pick_from_menu(&mut harness, third, "Add to favorites");
pick_from_menu(&mut harness, second, "Add to favorites");
assert!(comes_before(&harness, second, third) && comes_before(&harness, third, first), "favorites first, the newest first");
assert_eq!(harness.get_by_label(second).accesskit_node().description().as_deref(), Some("Favorite"), "the star is announced");
assert_eq!(harness.get_by_label(first).accesskit_node().description(), None);
pick_from_menu(&mut harness, second, "Remove from favorites");
assert!(comes_before(&harness, first, second), "a removed favorite goes back to its place by name");
assert!(comes_before(&harness, third, first), "the other favorite stays first");
}
#[test]
fn set_custom_preview_shows_a_picked_picture_until_removed() {
let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap();
let mut harness = shelf(MATERIALS_TYPE);
let dir = super::temp_dir::TempDir::new("shelf-custom-preview");
let picture = dir.join("preview.png");
image::RgbaImage::from_pixel(8, 4, image::Rgba([40, 160, 90, 255])).save(&picture).unwrap();
let not_a_picture = dir.join("notes.png");
std::fs::write(&not_a_picture, b"not a picture").unwrap();
let answers = std::sync::Arc::new(std::sync::Mutex::new(vec![picture.clone(), not_a_picture]));
let pick = answers.clone();
harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![pick.lock().unwrap().remove(0)]))));
let picked =
|harness: &Harness<'_, TextureCraftApp>| harness.state().ui.shelf_custom_previews.iter().map(|preview| preview.file.clone()).collect::<Vec<_>>();
pick_from_menu(&mut harness, material.label, "Set custom preview...");
harness.run_steps(2);
assert_eq!(picked(&harness), std::slice::from_ref(&picture), "the tile shows the picked picture");
pick_from_menu(&mut harness, material.label, "Set custom preview...");
harness.run_steps(2);
assert_eq!(picked(&harness), [picture], "a file that isn't a picture leaves the preview as it was");
pick_from_menu(&mut harness, material.label, "Remove custom preview");
assert!(picked(&harness).is_empty(), "the tile shows its own thumbnail again");
right_click(&mut harness, material.label);
assert!(harness.query_by_label("Remove custom preview").is_none(), "only a tile with a custom preview offers to remove it");
}
+129 -5
View File
@@ -19,6 +19,8 @@ const MATERIALS_TYPE: usize = 0;
const SMART_MASKS_TYPE: usize = 2;
const BRUSHES_TYPE: usize = 4;
const ENVIRONMENTS_TYPE: usize = 7;
/// The type row with no type picked: every type shows
const EVERY_TYPE: usize = 8;
/// How far the saved brush's spacing differs from the current brush's, so loading it shows
const SAVED_SPACING_CHANGE: f32 = 0.25;
/// Tile columns the reference shows at its panel width
@@ -155,6 +157,8 @@ fn refresh_reads_the_saved_brushes_again() {
harness.run_steps(1);
button(&harness, "Refresh").click();
harness.run_steps(2);
button(&harness, "Update Assets panel").click();
harness.run_steps(3);
assert!(harness.state().session.brush_presets.find("Stale brush marker").is_none(), "the brushes folder was read again");
@@ -204,7 +208,13 @@ fn many_saved_searches_keep_the_path_filter_reachable() {
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.state_mut().ui.shelf_panes.filter_by_path = true;
harness.state_mut().ui.shelf_saved_searches = (0..100)
.map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() })
.map(|index| SavedSearch {
name: format!("search {index}"),
filter: format!("filter {index}"),
tab: MATERIALS_TYPE,
path: Vec::new(),
favorites_only: false,
})
.collect();
harness.run_steps(3);
@@ -218,7 +228,13 @@ fn a_long_saved_search_list_can_select_the_last_query() {
let mut harness = shelf(NARROW_WINDOW);
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.state_mut().ui.shelf_saved_searches = (0..1000)
.map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() })
.map(|index| SavedSearch {
name: format!("search {index}"),
filter: format!("filter {index}"),
tab: MATERIALS_TYPE,
path: Vec::new(),
favorites_only: false,
})
.collect();
harness.run_steps(3);
assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows");
@@ -388,10 +404,10 @@ fn the_panes_list_the_reference_rows_and_grey_the_missing_ones() {
let tops: Vec<f32> = rows.iter().map(|label| latest_node_with_label(&harness, label).rect().top()).collect();
assert!(tops.windows(2).all(|pair| pair[0] < pair[1]), "{rows:?} run top to bottom: {tops:?}");
}
for label in ["Favorites", "3D Assets", "Flattened layers", "System fonts", "User fonts"] {
for label in ["3D Assets", "Flattened layers", "System fonts", "User fonts"] {
assert!(latest_node_with_label(&harness, label).accesskit_node().is_disabled(), "{label} is greyed");
}
for label in ["All", "All libraries", "Project", "Starter assets", "Your assets"] {
for label in ["All", "Favorites", "All libraries", "Project", "Starter assets", "Your assets"] {
assert!(!latest_node_with_label(&harness, label).accesskit_node().is_disabled(), "{label} works");
}
assert!(shows_not_available(&mut harness, "Flattened layers"), "a greyed saved search explains itself");
@@ -458,7 +474,7 @@ fn the_smallest_saved_search_pane_can_scroll_to_and_select_the_last_query() {
harness.state_mut().ui.shelf_panes.filter_by_path = true;
harness.state_mut().ui.shelf_panes_split = 0.0;
harness.state_mut().ui.shelf_saved_searches =
vec![SavedSearch { name: "Rust search".into(), filter: "rust".into(), tab: MATERIALS_TYPE, path: Vec::new() }];
vec![SavedSearch { name: "Rust search".into(), filter: "rust".into(), tab: MATERIALS_TYPE, path: Vec::new(), favorites_only: false }];
harness.run_steps(3);
scroll_pane_to_end(&mut harness, "SAVED SEARCHES");
@@ -519,3 +535,111 @@ fn the_splitter_is_exposed_as_a_resizable_control() {
assert!(harness.state().ui.shelf_panes_split > before);
}
#[test]
fn the_favorites_search_shows_only_favorites_until_all_is_picked() {
let plain = plain_materials();
let (favorite, other) = (plain[1].label, plain[0].label);
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.run_steps(3);
button(&harness, favorite).click_secondary();
harness.run_steps(3);
button(&harness, "Add to favorites").click();
harness.run_steps(3);
button(&harness, "Favorites").click();
harness.run_steps(3);
assert!(harness.query_by_label(favorite).is_some(), "the favorite shows");
assert!(harness.query_by_label(other).is_none(), "an asset that is no favorite is hidden");
assert!(harness.query_by_label("My brushes").is_none(), "the saved brushes list is no favorite either");
button(&harness, "All").click();
harness.run_steps(3);
assert!(harness.query_by_label(other).is_some(), "All shows every asset again");
assert!(harness.query_by_label("My brushes").is_some(), "All shows the saved brushes list again");
}
/// The shelf on the Materials type with the first plain material made a favorite through its menu
fn shelf_with_a_favorite(session: texturecraft_engine::Session) -> Harness<'static, TextureCraftApp> {
let favorite = plain_materials()[0].label;
let mut harness = Harness::builder()
.with_size(REFERENCE_WINDOW)
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.shelf_tab = MATERIALS_TYPE;
harness.run_steps(4);
button(&harness, favorite).click_secondary();
harness.run_steps(3);
button(&harness, "Add to favorites").click();
harness.run_steps(3);
harness
}
#[test]
fn a_search_saved_under_favorites_shows_only_favorites_again() {
let mut harness = shelf_with_a_favorite(texturecraft_engine::sample_session(256, 64).unwrap());
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.run_steps(3);
button(&harness, "Favorites").click();
harness.run_steps(3);
button(&harness, "Save the current search").click();
harness.run_steps(2);
button(&harness, "All").click();
harness.run_steps(3);
// The saved search lists below the fixed Favorites row, under the same name
harness.get_all_by_label("Favorites").last().unwrap().click();
harness.run_steps(3);
assert_eq!(harness.state().ui.shelf_saved_searches.len(), 1);
assert!(harness.state().ui.shelf_favorites_only, "the saved search shows only favorites, as when it was saved");
}
#[test]
fn hiding_non_applicable_folders_under_favorites_hides_the_folders_of_other_assets() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
session.import_resource_bytes("photo.png", png).unwrap();
let mut harness = shelf_with_a_favorite(session);
harness.state_mut().ui.shelf_tab = EVERY_TYPE;
harness.state_mut().ui.shelf_favorites_only = true;
harness.state_mut().ui.shelf_panes.filter_by_path = true;
harness.state_mut().ui.shelf_panes.hide_non_applicable = true;
harness.run_steps(4);
assert!(harness.query_by_label("Starter assets").is_some(), "the favorite's library shows");
assert!(harness.query_by_label("Project").is_none(), "the project image is no favorite, so its library hides");
}
#[test]
fn the_edge_between_the_panes_and_the_grid_drags_and_the_width_is_saved() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.run_steps(3);
const DRAG_DISTANCE_POINTS: f32 = 40.0;
let (initial_share, edge) = (harness.state().ui.shelf_panes_share, harness.get_by_label("Resize Assets filter panes and grid").rect());
let from = edge.center();
let to = from + egui::vec2(DRAG_DISTANCE_POINTS, 0.0);
harness.hover_at(from);
harness.run_steps(1);
harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
harness.run_steps(1);
for step in 1..=4 {
harness.hover_at(from + (to - from) * (step as f32 / 4.0));
harness.run_steps(1);
}
harness.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
harness.run_steps(3);
let moved = harness.get_by_label("Resize Assets filter panes and grid").rect();
assert!(moved.center().x > edge.center().x, "the edge follows the drag: {edge:?} to {moved:?}");
assert!(harness.state().ui.shelf_panes_share > initial_share, "the panes take a larger share");
let saved = serde_json::to_value(&harness.state().ui).unwrap();
let restored: texturecraft_ui_egui::state::UiState = serde_json::from_value(saved).unwrap();
assert_eq!(restored.shelf_panes_share, harness.state().ui.shelf_panes_share, "the width is saved");
}
+47
View File
@@ -0,0 +1,47 @@
//! The Assets panel's folder button opens a second Assets panel with its own search
use egui::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::docking::Panel;
/// The sample project at 1600 x 960
fn sample_app() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(4);
harness
}
/// Type `text` into the search field of the Assets panel shown left of the 3D view
fn search_shown_panel(harness: &mut Harness<'_, TextureCraftApp>, text: &str) {
let left_of_view = harness.state().viewport_rect.min.x;
harness.get_all_by_role(Role::TextInput).find(|field| field.rect().max.x < left_of_view).expect("the shown Assets panel has a search field").click();
harness.run_steps(2);
harness.event(egui::Event::Text(text.into()));
harness.run_steps(2);
}
#[test]
fn the_folder_button_opens_a_second_assets_panel_that_searches_on_its_own() {
let mut harness = sample_app();
assert!(!harness.state().ui.dock.is_open(Panel::AssetsSecond), "one Assets panel at first");
harness.get_by_label("New Assets panel").click();
harness.run_steps(3);
assert!(harness.state().ui.dock.is_visible(Panel::AssetsSecond), "the folder button shows a second Assets panel");
search_shown_panel(&mut harness, "brick");
let ui = &harness.state().ui;
assert_eq!((ui.shelf_second.filter.as_str(), ui.shelf_filter.as_str()), ("brick", ""), "the second panel's search leaves the first panel's alone");
harness.state_mut().ui.dock.focus(Panel::Assets);
harness.run_steps(3);
search_shown_panel(&mut harness, "rust");
let ui = &harness.state().ui;
assert_eq!((ui.shelf_second.filter.as_str(), ui.shelf_filter.as_str()), ("brick", "rust"), "the first panel's search leaves the second panel's alone");
}
+134
View File
@@ -0,0 +1,134 @@
//! The Assets panel's refresh popup: automatic updates of the panel and of the project's images
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use texturecraft_engine::brush_preset_cmds::UserBrush;
use texturecraft_ui_egui::TextureCraftApp;
/// A little more than the shortest update interval, in seconds
const PAST_A_MINUTE: f64 = 61.0;
/// The sample project with the Assets panel open and its refresh popup shown
fn refresh_popup() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder()
.with_size(egui::vec2(1920.0, 1032.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(2);
harness.get_all_by_label("Refresh").next().unwrap().click();
harness.run_steps(2);
harness
}
/// Moves the app's clock on by more than a minute in one frame, then lets the frames after it settle
fn pass_a_minute(harness: &mut Harness<'_, TextureCraftApp>) {
let now = harness.ctx.input(|input| input.time);
harness.input_mut().time = Some(now + PAST_A_MINUTE);
harness.run_steps(2);
}
/// Writes `bytes` over the file at `path` with a later time, as a later save would (an equal-size file keeping its time reads as unchanged)
fn rewrite(path: &std::path::Path, bytes: &[u8]) {
std::fs::write(path, bytes).unwrap();
let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
std::fs::File::options().write(true).open(path).unwrap().set_modified(later).unwrap();
}
/// A grey one-pixel PNG of `value`
fn grey_png(value: f32) -> Vec<u8> {
texturecraft_engine::formats::gray16_png(1, 1, [value].into_iter()).unwrap()
}
#[test]
fn turning_on_project_resources_reads_a_changed_image_file_again_every_minute() {
let mut harness = refresh_popup();
let path = std::env::temp_dir().join(format!("texturecraft-auto-update-{}.png", std::process::id()));
std::fs::write(&path, grey_png(0.2)).unwrap();
let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string();
let before = harness.state().session.images[&name].rgba.clone();
rewrite(&path, &grey_png(0.8));
pass_a_minute(&mut harness);
let while_off = harness.state().session.images[&name].rgba.clone();
harness.get_by_label("Resources used in project").click();
harness.run_steps(2);
pass_a_minute(&mut harness);
let after = harness.state().session.images[&name].rgba.clone();
std::fs::remove_file(path).unwrap();
assert_eq!(while_off, before, "nothing is read again while automatic updates are off");
assert!(harness.state().ui.shelf_updates.resources, "the switch turned the update on");
assert_ne!(after, before, "the changed file was read again within a minute");
}
#[test]
fn turning_on_the_assets_panel_reads_the_saved_brushes_again_every_minute() {
let mut harness = refresh_popup();
let stale = UserBrush { name: "Stale brush marker".into(), brush: Default::default(), channels: None, file: None };
harness.state_mut().session.brush_presets.list.push(stale);
harness.get_by_label("Assets panel").click();
harness.run_steps(2);
pass_a_minute(&mut harness);
assert!(harness.state().session.brush_presets.find("Stale brush marker").is_none(), "the brushes folder was read again");
}
#[test]
fn an_automatic_update_waits_for_the_stroke_under_way_to_end() {
let mut harness = refresh_popup();
let path = std::env::temp_dir().join(format!("texturecraft-auto-update-stroke-{}.png", std::process::id()));
std::fs::write(&path, grey_png(0.2)).unwrap();
let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string();
let before = harness.state().session.images[&name].rgba.clone();
harness.get_by_label("Resources used in project").click();
harness.run_steps(2);
rewrite(&path, &grey_png(0.8));
let steps_before_stroke = harness.state().session.history_labels().len();
harness.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap();
pass_a_minute(&mut harness);
let during_stroke = harness.state().session.images[&name].rgba.clone();
harness.state_mut().session.end_stroke().unwrap();
harness.run_steps(2);
let after_stroke = harness.state().session.images[&name].rgba.clone();
std::fs::remove_file(path).unwrap();
assert_eq!(during_stroke, before, "nothing is read again while a stroke is under way");
assert_ne!(after_stroke, before, "the update runs once the stroke ended");
assert_eq!(harness.state().session.doc.resources[&name].as_slice(), grey_png(0.8).as_slice(), "the stroke's undo state didn't swallow the update");
harness.state_mut().session.undo().unwrap();
assert_eq!(harness.state().session.doc.resources[&name].as_slice(), grey_png(0.2).as_slice(), "one undo takes back the update");
assert_eq!(harness.state().session.history_labels().len(), steps_before_stroke + 1, "the stroke is still its own step");
}
#[test]
fn a_file_that_fails_to_read_is_reported_again_in_the_next_project() {
let mut harness = refresh_popup();
harness.get_by_label("Resources used in project").click();
harness.run_steps(2);
let mut reported = Vec::new();
for project in ["first", "second"] {
if project == "second" {
harness.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap();
}
let folder = std::env::temp_dir().join(format!("texturecraft-failed-read-{project}-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
let path = folder.join("photo.png");
std::fs::write(&path, grey_png(0.2)).unwrap();
let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string();
std::fs::remove_dir_all(&folder).unwrap();
harness.state_mut().toasts.clear();
pass_a_minute(&mut harness);
reported.push(harness.state().toasts.iter().any(|toast| toast.error && toast.text.starts_with(&format!("{name}:"))));
}
assert_eq!(reported, [true, true], "each project says once that its file can't be read");
}
+1 -1
View File
@@ -88,7 +88,7 @@ fn an_assets_image_dropped_on_the_stencil_slot_becomes_the_stencil() {
assert!(harness.state().session.tool.stencil.is_none());
let slot = harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).unwrap().rect().center();
egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into() });
egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into(), thumb: None });
harness.hover_at(slot);
harness.run_steps(2);
harness.event(Event::PointerButton { pos: slot, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
+238
View File
@@ -729,6 +729,244 @@ fn smart_material_shelf_snapshot() {
save(&mut harness, &output_dir, "smart-material-hover");
}
/// Writes `name` and, beside it, where the pointer is (`<name>.pointer.txt`: x y), so a picture can draw the system's pointer
fn save_with_pointer(harness: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) {
save(harness, dir, name);
if let Some(pointer) = harness.ctx.input(|input| input.pointer.hover_pos()) {
std::fs::write(dir.join(format!("{name}.pointer.txt")), format!("{} {}", pointer.x, pointer.y)).unwrap();
}
}
/// Assets types the pass 2 snapshots show, as indexes into the Assets panel's type row
const SMART_MATERIALS_TYPE: usize = 1;
const BRUSHES_TYPE: usize = 4;
const TEXTURES_TYPE: usize = 6;
/// A move from a pressed tile or row long enough to start a drag
const DRAG_START: egui::Vec2 = egui::vec2(12.0, 12.0);
/// A point in the window's top bar, so no tile shows its hover outline
const AWAY_FROM_TILES: egui::Pos2 = egui::pos2(800.0, 40.0);
/// How far down the window a point is inside Properties
const PROPERTIES_HEIGHT_SHARE: f32 = 0.75;
/// The panes' edge drag: steps and points per step
const EDGE_DRAG_STEPS: usize = 4;
const EDGE_DRAG_STEP: f32 = 15.0;
/// Assets pass 2, every screen mid-interaction (menus, submenu, favorites, custom preview, drag ghost, refresh popup, second panel); `TC_UI_THEMES` adds dark and light
#[test]
#[ignore]
fn assets_pass_two_snapshots() {
use egui::{Event, Modifiers, PointerButton, Role, vec2};
use texturecraft_engine::materials::MATERIALS;
use texturecraft_ui_egui::file_dialogs::Answer;
let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return };
std::fs::create_dir_all(&output_dir).unwrap();
let files = std::env::temp_dir().join(format!("texturecraft-assets-pass-two-{}", std::process::id()));
std::fs::create_dir_all(&files).unwrap();
let brushes = files.join("brushes");
let plate = files.join("rust_plate.png");
image::RgbaImage::from_fn(128, 128, |x, y| {
let grain = ((x * 7 + y * 13) % 23) as u8 * 3;
image::Rgba([120 + grain, 66 + grain / 2, 38, 255])
})
.save(&plate)
.unwrap();
let preview = files.join("brushed_preview.png");
image::RgbaImage::from_fn(160, 120, |x, y| {
let line = 140 + ((y * 37 + x / 9) % 41) as u8;
image::Rgba([line, line, line + 8, 255])
})
.save(&preview)
.unwrap();
let show_in = if cfg!(target_os = "windows") {
"Show in Explorer..."
} else if cfg!(target_os = "macos") {
"Show in Finder..."
} else {
"Show in file manager..."
};
let mut themes = vec![(Brightness::MediumDark, "medium")];
if std::env::var_os("TC_UI_THEMES").is_some() {
themes.extend([(Brightness::Dark, "dark"), (Brightness::Light, "light")]);
}
for (brightness, theme) in themes {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
.with_pixels_per_point(1.0)
// The system draws the pointer, not the app
.with_render_cursor(false)
.wgpu()
.build_eframe(|context| TextureCraftApp::new(context, session));
let app = harness.state_mut();
app.ui.prefs.brightness = brightness;
app.ui.prefs.language = "en".into();
let theme_brushes = brushes.join(theme);
std::fs::create_dir_all(&theme_brushes).unwrap();
app.session.brush_presets.dir = Some(theme_brushes);
app.run("brush.preset.store", serde_json::json!({"name": "Ink soft"})).unwrap();
let image = app.run("resource.import", serde_json::json!({"path": plate.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string();
let answer = preview.clone();
app.file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()]))));
app.ui.shelf_tab = SMART_MATERIALS_TYPE;
let context = harness.ctx.clone();
let started = std::time::Instant::now();
loop {
harness.run_steps(1);
let thumbnails = &mut harness.state_mut().thumbs;
if MATERIALS.iter().filter(|material| material.smart).all(|material| thumbnails.material(&context, material.id).is_some()) {
break;
}
assert!(started.elapsed() < std::time::Duration::from_secs(120), "smart material thumbnails did not arrive");
std::thread::sleep(std::time::Duration::from_millis(20));
}
let shot = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| save_with_pointer(harness, &output_dir, &format!("assets-{name}-{theme}"));
let right_click = |harness: &mut Harness<'_, TextureCraftApp>, tile: &str| {
harness.get_all_by_label(tile).next().unwrap_or_else(|| panic!("no tile {tile}")).click_secondary();
harness.run_steps(3);
};
let close_menu = |harness: &mut Harness<'_, TextureCraftApp>| {
harness.key_press(egui::Key::Escape);
harness.run_steps(3);
};
// 01: a built-in smart material, a row hovered; 03: its greyed Show in
right_click(&mut harness, "Brass Tarnished");
harness.get_by_label("Export resource...").hover();
shot(&mut harness, "01-menu-built-in");
harness.get_by_label("Show in").hover();
harness.run_steps(30);
shot(&mut harness, "03-show-in-built-in");
close_menu(&mut harness);
// 04: two favorites, the newest first, then a favorite's menu; 08: a custom preview on a third tile
for tile in ["Gold Dirty", "Bronze Statue"] {
right_click(&mut harness, tile);
harness.get_by_label("Add to favorites").click();
harness.run_steps(3);
}
right_click(&mut harness, "Brass Tarnished");
harness.get_by_label("Set custom preview...").click();
harness.run_steps(3);
settle_thumbnails(&mut harness);
harness.hover_at(AWAY_FROM_TILES);
shot(&mut harness, "04-favorites-and-custom-preview");
right_click(&mut harness, "Bronze Statue");
harness.get_by_label("Remove from favorites").hover();
shot(&mut harness, "04-menu-favorite");
close_menu(&mut harness);
// 05: the drag ghost over the layer stack (takes a material) and over Properties (doesn't)
let viewport_right = harness.state().viewport_rect.max.x;
let layer = harness.get_all_by_role(Role::ListItem).find(|row| row.rect().min.x > viewport_right).expect("a layer row").rect().center();
// Properties fills the right column under the layer stack, in the window's lower part
let properties = egui::pos2(layer.x, harness.ctx.content_rect().height() * PROPERTIES_HEIGHT_SHARE);
let tile = harness.get_all_by_label("Gold Dirty").next().unwrap().rect().center();
harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
harness.run_steps(2);
harness.hover_at(tile + DRAG_START);
harness.run_steps(2);
for (target, name) in [(layer, "05-drag-valid-layer-stack"), (properties, "05-drag-not-valid-properties")] {
harness.hover_at(target);
harness.run_steps(2);
shot(&mut harness, name);
}
harness.event(Event::PointerButton { pos: properties, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
harness.run_steps(3);
// 09: a layer dragged in the layer stack over another row (takes it) and over Properties (doesn't)
harness.state_mut().run("layer.add.paint", serde_json::json!({"name": "Dragged layer"})).unwrap();
harness.run_steps(3);
let dragged = harness.get_by_role_and_label(Role::ListItem, "Dragged layer").rect().center();
let rows: Vec<_> = harness.get_all_by_role(Role::ListItem).filter(|row| row.rect().min.x > viewport_right).map(|row| row.rect().center()).collect();
let other = *rows.iter().find(|at| at.y > dragged.y).expect("a row below it");
harness.event(Event::PointerButton { pos: dragged, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
harness.run_steps(2);
harness.hover_at(dragged + DRAG_START);
harness.run_steps(2);
for (target, name) in [(other, "09-layer-drag-valid-row"), (properties, "09-layer-drag-not-valid-properties")] {
harness.hover_at(target);
harness.run_steps(2);
shot(&mut harness, name);
}
harness.event(Event::PointerButton { pos: properties, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
harness.run_steps(3);
// 02: a project image and a saved brush; 03: Show in open on the image
harness.state_mut().ui.shelf_tab = TEXTURES_TYPE;
settle_thumbnails(&mut harness);
right_click(&mut harness, &image);
harness.get_by_label("Reload").hover();
shot(&mut harness, "02-menu-project-image");
harness.get_by_label("Show in").click();
harness.run_steps(3);
harness.get_by_label(show_in).hover();
shot(&mut harness, "03-show-in-image");
close_menu(&mut harness);
harness.state_mut().ui.shelf_tab = BRUSHES_TYPE;
settle_thumbnails(&mut harness);
right_click(&mut harness, "Ink soft");
harness.get_by_label("Replace with the current brush").hover();
shot(&mut harness, "02-menu-saved-brush");
close_menu(&mut harness);
// 06: the refresh popup, then with an i hovered
harness.state_mut().ui.shelf_tab = SMART_MATERIALS_TYPE;
harness.run_steps(3);
harness.get_all_by_label("Refresh").next().unwrap().click();
harness.run_steps(3);
harness.get_by_label("Update Assets panel").hover();
shot(&mut harness, "06-refresh-popup");
harness.get_by_label("Reads your saved assets from disk again every few minutes, so new and changed ones show here.").hover();
harness.run_steps(30);
shot(&mut harness, "06-refresh-info");
close_menu(&mut harness);
// 10: both filter panes open, their edge with the grid dragged wider
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.state_mut().ui.shelf_panes.filter_by_path = true;
harness.run_steps(3);
let edge = harness.get_by_label("Resize Assets filter panes and grid").rect().center();
harness.hover_at(edge);
harness.run_steps(1);
harness.event(Event::PointerButton { pos: edge, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
harness.run_steps(1);
for step in 1..=EDGE_DRAG_STEPS {
harness.hover_at(edge + vec2(EDGE_DRAG_STEP * step as f32, 0.0));
harness.run_steps(1);
}
shot(&mut harness, "10-panes-edge-drag");
harness.event(Event::PointerButton {
pos: edge + vec2(EDGE_DRAG_STEP * EDGE_DRAG_STEPS as f32, 0.0),
button: PointerButton::Primary,
pressed: false,
modifiers: Modifiers::NONE,
});
harness.state_mut().ui.shelf_panes.saved_searches = false;
harness.state_mut().ui.shelf_panes.filter_by_path = false;
harness.run_steps(3);
// 07: the folder button hovered, then the second panel searching "brick"
harness.get_by_label("New Assets panel").hover();
harness.run_steps(30);
shot(&mut harness, "07-folder-button");
harness.get_all_by_label("New Assets panel").next().unwrap().click();
harness.run_steps(3);
let left_of_view = harness.state().viewport_rect.min.x;
harness.get_all_by_role(Role::TextInput).find(|field| field.rect().max.x < left_of_view).expect("the second panel's search").click();
harness.run_steps(2);
harness.event(Event::Text("brick".into()));
settle_thumbnails(&mut harness);
shot(&mut harness, "07-second-panel");
}
std::fs::remove_dir_all(files).unwrap();
}
/// Compact nested rows must keep their content, mask and effect controls in the panel.
#[test]
#[ignore]