mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-25 08:50:46 +01:00
Bound the session log folders and import MaterialX from Import Resources
Each desktop run made a new logs/session-* folder that was never removed, so the logs folder grew with every start. Starting a run now removes all but the newest earlier runs' folders, keeping ten in all. Removing File > Import MaterialX material... left no way to import a .mtlx from the GUI. Import Resources now lists .mtlx files and imports them as file.importMaterialX does, as a fill layer. The protocol doc no longer points at the removed Import PBR texture folder item. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6bc4f3cafc
commit
e604486216
6 files changed
+120
-22
No files matched your search
@@ -1,5 +1,6 @@
|
||||
//! File > Import resources...: a window to collect files, set what each is for, and import them
|
||||
//! together. Images become project resources; materials load as smart materials.
|
||||
//! together. Images become project resources; materials load as smart materials and MaterialX
|
||||
//! documents as fill layers.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
@@ -61,9 +62,18 @@ pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, n
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the file is a material (loaded as a smart material, so it has no usage or prefix)
|
||||
fn extension_of(row: &ImportRow) -> String {
|
||||
row.path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the file is a MaterialX document (added as a fill layer)
|
||||
fn is_materialx(row: &ImportRow) -> bool {
|
||||
extension_of(row) == crate::windows::MATERIALX_EXT
|
||||
}
|
||||
|
||||
/// Whether the file is a material (a smart material or a MaterialX document, so it has no usage or prefix)
|
||||
fn is_material(row: &ImportRow) -> bool {
|
||||
row.path.extension().and_then(|e| e.to_str()).is_some_and(|e| MATERIAL_EXTS.contains(&e.to_ascii_lowercase().as_str()))
|
||||
MATERIAL_EXTS.contains(&extension_of(row).as_str()) || is_materialx(row)
|
||||
}
|
||||
|
||||
fn file_name(row: &ImportRow) -> String {
|
||||
@@ -256,6 +266,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if add {
|
||||
let mut extensions: Vec<&str> = IMAGE_EXTS.to_vec();
|
||||
extensions.extend_from_slice(MATERIAL_EXTS);
|
||||
extensions.push(crate::windows::MATERIALX_EXT);
|
||||
let opening_id = window.opening_id;
|
||||
app.ask_file(FileDialog::open_many().filter(tr("Resources"), &extensions), Bound::Project, move |app, paths| {
|
||||
let Some(stored) = app.ui.windows.import_resources.as_mut().filter(|stored| stored.opening_id == opening_id) else { return };
|
||||
@@ -293,6 +304,10 @@ fn import_row(app: &mut TextureCraftApp, row: &ImportRow) -> bool {
|
||||
return false;
|
||||
};
|
||||
|
||||
if is_materialx(row) {
|
||||
return crate::windows::import_materialx(app, path);
|
||||
}
|
||||
|
||||
if is_material(row) {
|
||||
return app.run("material.load", json!({ "path": path })).is_some();
|
||||
}
|
||||
|
||||
@@ -457,11 +457,7 @@ impl TextureCraftApp {
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if cc.winit_window().is_some() {
|
||||
let path = crate::data_dir()
|
||||
.join("logs")
|
||||
.join(format!("session-{}-{}", chrono::Utc::now().format("%Y%m%dT%H%M%S%.6fZ"), std::process::id()))
|
||||
.join("log.txt");
|
||||
match session_log_file::SessionLogFile::new(path) {
|
||||
match session_log_file::SessionLogFile::start(&crate::data_dir().join("logs")) {
|
||||
Ok(file) => app.session_log_file = Some(file),
|
||||
Err(error) => app.toast(format!("{}: {error}", i18n::tr("Could not create the session log")), true),
|
||||
}
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
io::{self, Write},
|
||||
path::PathBuf,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use texturecraft_engine::LogEntry;
|
||||
|
||||
// Retain two segments to bound each run's log while preserving recent history
|
||||
const MAX_LOG_SEGMENT_BYTES: u64 = 8 * 1024 * 1024;
|
||||
/// Runs whose log folders stay in the logs folder, the new run's included, so the folder stays bounded
|
||||
const KEPT_SESSION_FOLDERS: usize = 10;
|
||||
const SESSION_FOLDER_PREFIX: &str = "session-";
|
||||
|
||||
pub(crate) struct SessionLogFile {
|
||||
pub path: PathBuf,
|
||||
@@ -18,7 +21,31 @@ pub(crate) struct SessionLogFile {
|
||||
last: Option<LogEntry>,
|
||||
}
|
||||
|
||||
/// Remove all but the `keep` newest session folders in `logs`. Their names start with a UTC time, so
|
||||
/// name order is age order. Errors are ignored: a folder an older run still holds open stays for a later start.
|
||||
fn prune(logs: &Path, keep: usize) {
|
||||
let Ok(entries) = std::fs::read_dir(logs) else { return };
|
||||
let mut folders: Vec<PathBuf> = entries
|
||||
.filter_map(Result::ok)
|
||||
.filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))
|
||||
.filter(|entry| entry.file_name().to_str().is_some_and(|name| name.starts_with(SESSION_FOLDER_PREFIX)))
|
||||
.map(|entry| entry.path())
|
||||
.collect();
|
||||
folders.sort();
|
||||
let old = folders.len().saturating_sub(keep);
|
||||
for folder in &folders[..old] {
|
||||
let _ = std::fs::remove_dir_all(folder);
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionLogFile {
|
||||
/// Start this run's log in a new session folder under `logs`, after removing the oldest runs' folders.
|
||||
pub fn start(logs: &Path) -> io::Result<Self> {
|
||||
prune(logs, KEPT_SESSION_FOLDERS - 1);
|
||||
let folder = format!("{SESSION_FOLDER_PREFIX}{}-{}", chrono::Utc::now().format("%Y%m%dT%H%M%S%.6fZ"), std::process::id());
|
||||
Self::new(logs.join(folder).join("log.txt"))
|
||||
}
|
||||
|
||||
pub fn new(path: PathBuf) -> io::Result<Self> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
@@ -100,4 +127,25 @@ mod tests {
|
||||
drop(file);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starting_a_run_removes_only_the_oldest_session_folders() {
|
||||
let logs = std::env::temp_dir().join(format!("texturecraft-session-prune-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&logs);
|
||||
let older: Vec<PathBuf> = (0..KEPT_SESSION_FOLDERS + 2).map(|i| logs.join(format!("{SESSION_FOLDER_PREFIX}20260101T0000{i:02}.000000Z-1"))).collect();
|
||||
for folder in &older {
|
||||
std::fs::create_dir_all(folder).unwrap();
|
||||
}
|
||||
let other = logs.join("kept-by-the-user");
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
|
||||
let file = SessionLogFile::start(&logs).unwrap();
|
||||
|
||||
let survivors = older.iter().filter(|folder| folder.exists()).count();
|
||||
assert_eq!(survivors + 1, KEPT_SESSION_FOLDERS, "the new run and the newest earlier runs remain");
|
||||
assert!(!older[0].exists() && older.last().unwrap().exists(), "the oldest go first");
|
||||
assert!(other.exists() && file.path.exists(), "other folders and the new log stay");
|
||||
drop(file);
|
||||
std::fs::remove_dir_all(logs).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -516,6 +516,24 @@ pub fn load_layout(app: &mut TextureCraftApp) {
|
||||
app.toast(tr("Saving UI layouts to files is available in the desktop app"), false);
|
||||
}
|
||||
|
||||
/// The extension of MaterialX documents (`file.importMaterialX`)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) const MATERIALX_EXT: &str = "mtlx";
|
||||
|
||||
/// Add the MaterialX material at `path` as a layer, logging what it could not read. Returns whether it was added.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn import_materialx(app: &mut TextureCraftApp, path: &str) -> bool {
|
||||
let Some(result) = app.run("file.importMaterialX", json!({"path": path})) else { return false };
|
||||
|
||||
let name = result["material"].as_str().unwrap_or_default();
|
||||
for warning in result["warnings"].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str) {
|
||||
app.session.log.warn(texturecraft_engine::log::LIBRARY_SOURCE, format!("MaterialX {name}: {warning}"));
|
||||
}
|
||||
app.toast(trf("Imported {name}", &[("name", &name)]), false);
|
||||
app.ui.dock.focus(crate::docking::Panel::Layers);
|
||||
true
|
||||
}
|
||||
|
||||
/// File menu actions that need dialogs. Returns true when handled.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> bool {
|
||||
@@ -561,16 +579,9 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) ->
|
||||
true
|
||||
}
|
||||
"file.importMaterialX" => {
|
||||
app.ask_file(FileDialog::open().filter(tr("MaterialX materials"), &["mtlx"]), Bound::Project, |app, paths| {
|
||||
if let Some(path) = paths.first()
|
||||
&& let Some(result) = app.run("file.importMaterialX", json!({"path": path.display().to_string()}))
|
||||
{
|
||||
let name = result["material"].as_str().unwrap_or_default();
|
||||
for warning in result["warnings"].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str) {
|
||||
app.session.log.warn(texturecraft_engine::log::LIBRARY_SOURCE, format!("MaterialX {name}: {warning}"));
|
||||
}
|
||||
app.toast(trf("Imported {name}", &[("name", &name)]), false);
|
||||
app.ui.dock.focus(crate::docking::Panel::Layers);
|
||||
app.ask_file(FileDialog::open().filter(tr("MaterialX materials"), &[MATERIALX_EXT]), Bound::Project, |app, paths| {
|
||||
if let Some(path) = paths.first() {
|
||||
import_materialx(app, &path.display().to_string());
|
||||
}
|
||||
});
|
||||
true
|
||||
|
||||
@@ -208,6 +208,33 @@ fn the_engine_command_still_imports_a_path_with_an_optional_prefix() {
|
||||
assert_eq!(prefixed["name"], "a_b_tile.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_materialx_document_imports_as_a_layer() {
|
||||
let dir = TempDir::new("import-resources-materialx");
|
||||
let file = dir.join("paint.mtlx");
|
||||
std::fs::write(
|
||||
&file,
|
||||
r#"<?xml version="1.0"?>
|
||||
<materialx version="1.39">
|
||||
<open_pbr_surface name="S" type="surfaceshader">
|
||||
<input name="base_color" type="color3" value="0.8, 0.2, 0.1" />
|
||||
</open_pbr_surface>
|
||||
<surfacematerial name="Paint" type="material"><input name="surfaceshader" type="surfaceshader" nodename="S" /></surfacematerial>
|
||||
</materialx>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut h = app();
|
||||
let layers = h.state().session.doc.project.layers.len();
|
||||
invoke(&mut h);
|
||||
add(&mut h, &[file]);
|
||||
|
||||
click(&mut h, "Import");
|
||||
|
||||
assert!(!is_open(&h), "the document was imported");
|
||||
assert!(h.state().session.doc.project.layers.len() > layers, "the material became a layer");
|
||||
assert!(resources(&h).is_empty(), "the document itself is not an image resource");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_failed_rows_remain_after_a_partial_import() {
|
||||
let dir = TempDir::new("import-resources-retry");
|
||||
|
||||
@@ -507,9 +507,10 @@ Maps are found by file name, case-insensitively, from the last known word in the
|
||||
import is an error that changes nothing. `maps` describes detection; `channels` and `resources`
|
||||
describe the successful import. Scan validates import options without decoding pixels.
|
||||
|
||||
In the app: File › Import PBR texture folder... or drop a folder, a `.zip` or several map files on the
|
||||
window. The dialog shows the maps found, lets you pick between candidates, set the normal convention and
|
||||
projection, and keep the material in the library (shelf › Materials).
|
||||
In the app: drop a folder, a `.zip` or several map files on the window. The dialog shows the maps found,
|
||||
lets you pick between candidates, set the normal convention and projection, and keep the material in the
|
||||
library (shelf › Materials). A `.mtlx` added in File › Import Resources is imported as `file.importMaterialX`
|
||||
does it.
|
||||
|
||||
## Smart masks
|
||||
|
||||
|
||||
Reference in new issue
Block a user