Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 91 additions & 64 deletions editor/Assets/AssetBrowserSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using System.Text.RegularExpressions;
using Avalonia.Media;
using Avalonia.Threading;
using editor.Engine;
using Tomlyn;
using Tomlyn.Model;

Expand Down Expand Up @@ -98,6 +99,8 @@ private void Notify([CallerMemberName] string? name = null) {
public static class AssetBrowserSettings {
private const string EditorKey = "editor";
private const string SectionKey = "asset_browser";
private const string TagsKey = "tags";
private const string PrefPrefix = EditorKey + "." + SectionKey + ".";

private static DispatcherTimer? s_saveTimer;
private static List<Regex> s_hiddenRegexes = [];
Expand Down Expand Up @@ -131,35 +134,23 @@ public static void Load() {
ApplyDefaults();
var loaded = new List<(string Id, string Name, Color Color)>();

if (FindProjectFile() is { } path)
// user setting
if (ToastEngine.IsEngineReady) LoadPreferences();

if (TagsFile() is { } path && File.Exists(path))
try {
var root = TomlSerializer.Deserialize<TomlTable>(File.ReadAllText(path));
if (root is not null && root.TryGetValue(EditorKey, out var e) && e is TomlTable editor &&
editor.TryGetValue(SectionKey, out var s) && s is TomlTable section) {
ShowTags = GetBool(section, "show_tags", true);
ShowTypeBadge = GetBool(section, "show_type_badge", true);
CardSize = GetEnum(section, "card_size", AssetCardSize.Medium);
ShowCore = GetBool(section, "show_core", true);
ShowCache = GetBool(section, "show_cache", false);
SortBy = GetEnum(section, "sort_by", AssetSortBy.Name);
FoldersFirst = GetBool(section, "folders_first", true);
SearchScope = GetEnum(section, "search_scope", AssetSearchScope.Everywhere);
ConfirmDelete = GetBool(section, "confirm_delete", true);
if (section.TryGetValue("hidden_patterns", out var hp) && hp is TomlArray patterns)
HiddenPatterns = patterns.Select(p => p?.ToString()?.Trim() ?? "")
.Where(p => p.Length > 0).ToList();

if (section.TryGetValue("tags", out var t) && t is TomlTableArray tags)
foreach (var tag in tags) {
var id = tag.TryGetValue("id", out var i) ? i?.ToString() : null;
if (string.IsNullOrWhiteSpace(id) || loaded.Any(l => l.Id == id)) continue;
var name = tag.TryGetValue("name", out var n) ? n?.ToString() ?? "" : "";
var color = tag.TryGetValue("color", out var c) && Color.TryParse(c?.ToString(), out var parsed)
? parsed
: Colors.Gray;
loaded.Add((id, name, color));
}
}
if (root is not null && root.TryGetValue(SectionKey, out var s) && s is TomlTable section &&
section.TryGetValue(TagsKey, out var t) && t is TomlTableArray tags)
foreach (var tag in tags) {
var id = tag.TryGetValue("id", out var i) ? i?.ToString() : null;
if (string.IsNullOrWhiteSpace(id) || loaded.Any(l => l.Id == id)) continue;
var name = tag.TryGetValue("name", out var n) ? n?.ToString() ?? "" : "";
var color = tag.TryGetValue("color", out var c) && Color.TryParse(c?.ToString(), out var parsed)
? parsed
: Colors.Gray;
loaded.Add((id, name, color));
}
} catch {
//...
}
Expand Down Expand Up @@ -280,53 +271,99 @@ internal static void ScheduleSave() {

public static bool Save() {
s_saveTimer?.Stop();
if (FindProjectFile() is not { } path) {
if (TagsFile() is not { } path) {
Saved?.Invoke(false);
return false;
}

try {
var root = TomlSerializer.Deserialize<TomlTable>(File.ReadAllText(path)) ?? [];
if (!root.TryGetValue(EditorKey, out var e) || e is not TomlTable editor) {
editor = new TomlTable();
root[EditorKey] = editor;
// only the tags are written here
var root = (File.Exists(path) ? TomlSerializer.Deserialize<TomlTable>(File.ReadAllText(path)) : null) ?? [];
if (!root.TryGetValue(SectionKey, out var s) || s is not TomlTable section) {
section = new TomlTable();
root[SectionKey] = section;
}

var section = new TomlTable {
["show_tags"] = ShowTags,
["show_type_badge"] = ShowTypeBadge,
["card_size"] = CardSize.ToString(),
["show_core"] = ShowCore,
["show_cache"] = ShowCache,
["sort_by"] = SortBy.ToString(),
["folders_first"] = FoldersFirst,
["search_scope"] = SearchScope.ToString(),
["confirm_delete"] = ConfirmDelete
};

var patterns = new TomlArray();
foreach (var pattern in HiddenPatterns) patterns.Add(pattern);
section["hidden_patterns"] = patterns;

var tags = new TomlTableArray();
foreach (var tag in Tags)
tags.Add(new TomlTable {
["id"] = tag.Id,
["name"] = tag.Name,
["color"] = $"#{tag.Color.R:x2}{tag.Color.G:x2}{tag.Color.B:x2}"
});
section["tags"] = tags;

editor[SectionKey] = section;
if (tags.Count > 0) section[TagsKey] = tags;
else section.Remove(TagsKey);
if (section.Count == 0) root.Remove(SectionKey);

Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, TomlSerializer.Serialize(root));
Saved?.Invoke(true);
return true;

var ok = !ToastEngine.IsEngineReady || SavePreferences();
Saved?.Invoke(ok);
return ok;
} catch {
Saved?.Invoke(false);
return false;
}
}

private static void LoadPreferences() {
static bool Flag(string id, bool fallback) => ToastSettings.Flag(PrefPrefix + id, fallback);

static T Choice<T>(string id, T fallback) where T : struct, Enum =>
Enum.TryParse<T>(ToastSettings.GetText(PrefPrefix + id), true, out var parsed) ? parsed : fallback;

ShowTags = Flag("show_tags", true);
ShowTypeBadge = Flag("show_type_badge", true);
CardSize = Choice("card_size", AssetCardSize.Medium);
ShowCore = Flag("show_core", true);
ShowCache = Flag("show_cache", false);
SortBy = Choice("sort_by", AssetSortBy.Name);
FoldersFirst = Flag("folders_first", true);
SearchScope = Choice("search_scope", AssetSearchScope.Everywhere);
ConfirmDelete = Flag("confirm_delete", true);
HiddenPatterns = ParsePatterns(ToastSettings.GetText(PrefPrefix + "hidden_patterns"));
}

private static bool SavePreferences() {
ToastSettings.SetBool(PrefPrefix + "show_tags", ShowTags);
ToastSettings.SetBool(PrefPrefix + "show_type_badge", ShowTypeBadge);
ToastSettings.SetText(PrefPrefix + "card_size", CardSize.ToString(), out _);
ToastSettings.SetBool(PrefPrefix + "show_core", ShowCore);
ToastSettings.SetBool(PrefPrefix + "show_cache", ShowCache);
ToastSettings.SetText(PrefPrefix + "sort_by", SortBy.ToString(), out _);
ToastSettings.SetBool(PrefPrefix + "folders_first", FoldersFirst);
ToastSettings.SetText(PrefPrefix + "search_scope", SearchScope.ToString(), out _);
ToastSettings.SetBool(PrefPrefix + "confirm_delete", ConfirmDelete);
ToastSettings.SetText(PrefPrefix + "hidden_patterns", FormatPatterns(HiddenPatterns), out _);
return ToastSettings.SaveGroup(EditorKey);
}

private static string FormatPatterns(IEnumerable<string> patterns) =>
string.Join(';', patterns.Select(p => $"\"{p.Replace("\\", "\\\\").Replace("\"", "\\\"")}\""));

private static List<string> ParsePatterns(string text) {
var result = new List<string>();
var current = new System.Text.StringBuilder();
var quoted = false;
for (var i = 0; i <= text.Length; i++) {
if (i == text.Length || (text[i] == ';' && !quoted)) {
var item = current.ToString().Trim();
if (item.Length > 0) result.Add(item);
current.Clear();
continue;
}

var c = text[i];
if (c == '\\' && quoted && i + 1 < text.Length) current.Append(text[++i]);
else if (c == '"') quoted = !quoted;
else current.Append(c);
}

return result;
}

private static void Set<T>(T current, T value, Action<T> assign) {
if (EqualityComparer<T>.Default.Equals(current, value)) return;
assign(value);
Expand Down Expand Up @@ -360,18 +397,8 @@ private static void RebuildHiddenRegexes() {
.ToList();
}

private static string? FindProjectFile() {
private static string? TagsFile() {
if (!ProjectContext.IsInitialized) return null;
return Directory.EnumerateFiles(ProjectContext.ProjectPath, "*.toast").FirstOrDefault();
}

private static bool GetBool(TomlTable table, string key, bool fallback) {
return table.TryGetValue(key, out var value) && value is bool b ? b : fallback;
}

private static T GetEnum<T>(TomlTable table, string key, T fallback) where T : struct, Enum {
return table.TryGetValue(key, out var value) && Enum.TryParse<T>(value?.ToString(), true, out var parsed)
? parsed
: fallback;
return Path.Combine(ProjectContext.ProjectPath, "config", EditorKey + ".toml");
}
}
1 change: 1 addition & 0 deletions editor/Engine/ToastEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ public ToastEngine(string toastPath) {
// init after set_working_directory so the engine knows where to find its assets
toast_init();
IsEngineReady = true;
AssetBrowserSettings.Load();
DataSchemaStubGenerator.Generate();
// fresh projects need asset markers after engine startup
ProjectContext.GenerateAssetTypeStubs();
Expand Down
5 changes: 5 additions & 0 deletions editor/Engine/ToastSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ public static bool Flag(string key, bool fallback) {

public static bool Save() => toast_settings_save() != 0;

public static bool SaveGroup(string group) => toast_settings_save_group(group) != 0;

public static void Restore() => toast_settings_restore();

public static bool Cook(string configDir, string toastFile, string stageDir) =>
Expand Down Expand Up @@ -253,6 +255,9 @@ public static string ActivePath {
[LibraryImport(EngineLib)]
private static partial int toast_settings_save();

[LibraryImport(EngineLib, StringMarshalling = StringMarshalling.Utf8)]
private static partial int toast_settings_save_group(string group);

[LibraryImport(EngineLib)]
private static partial void toast_settings_restore();

Expand Down
1 change: 1 addition & 0 deletions engine/ffi/settings.h
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ TOAST_C_API void toast_settings_reset_all(void) NOEXCEPT;

/// @return 1 on success
TOAST_C_API int32_t toast_settings_save(void) NOEXCEPT;
TOAST_C_API int32_t toast_settings_save_group(const char* group) NOEXCEPT;
TOAST_C_API int32_t toast_settings_is_dirty(void) NOEXCEPT;

TOAST_C_API const char* toast_settings_active_path(void) NOEXCEPT;
Expand Down
6 changes: 6 additions & 0 deletions engine/src/toast/engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ void Engine::init() {
}
if (!packaged) {
params::upgradeLegacyConfig(config_dir);
params::migrateEditorConfig(config_dir, saved_config_dir);
}
if (const auto old_user_file = legacyUserSettingsFile(toast_path); !old_user_file.empty() && !saved_config_dir.empty()) {
params::migrateLegacyUserSettings(old_user_file, saved_config_dir);
Expand All @@ -389,6 +390,11 @@ void Engine::init() {
m->params_files->saveDirty();
}
});
registry.setSaveGroupHandler([this](const std::string& group) {
if (m && m->params_files) {
m->params_files->saveDirtyGroup(group);
}
});
registry.setRestoreHandler([this] {
if (m && m->params_files) {
m->params_files->reload();
Expand Down
10 changes: 10 additions & 0 deletions engine/src/toast/params/files.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,16 @@ auto Files::saveDirty() -> size_t {
return written;
}

auto Files::saveDirtyGroup(std::string_view name) -> size_t {
size_t written = 0;
for (const auto& entry : Registry::get().dirtyGroups()) {
if (entry.group->name() == name && save(*entry.group, entry.layer)) {
++written;
}
}
return written;
}

void Files::reload() {
Registry::get().clearRuntime();
for (GroupBase* group : Registry::get().groups()) {
Expand Down
4 changes: 3 additions & 1 deletion engine/src/toast/params/files.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ class TOAST_API DirectoryConfigSource final : public ConfigSource {
return m_directory;
}

private:
[[nodiscard]]
auto pathFor(std::string_view group) const -> std::filesystem::path;

private:
std::filesystem::path m_directory;
ConfigFormat m_format;
};
Expand All @@ -80,6 +80,8 @@ class TOAST_API Files {

auto saveDirty() -> size_t;

auto saveDirtyGroup(std::string_view name) -> size_t;

void reload();

private:
Expand Down
Loading
Loading