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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ logs/
**[Tt]arget**
!**/CrashTarget.cs
!**/BuildInfo.cs
!editor/LuaEditor/Graph/GraphBuilder.cs
[Oo]ut
engine/include/
vcpkg_installed/
Expand Down
5 changes: 4 additions & 1 deletion editor/Assets/Importers/CompactImportWindow.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
namespace editor.Assets.Importers;

public partial class CompactImportWindow : Window {
public CompactImportWindow(CompactImportWindowViewModel vm) {
public CompactImportWindow() {
InitializeComponent();
}

public CompactImportWindow(CompactImportWindowViewModel vm) : this() {
DataContext = vm;
Loaded += (_, _) => vm.SetWindow(this);
}
Expand Down
14 changes: 14 additions & 0 deletions editor/Assets/ProjectContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ public static void Initialize(string projectPath, string corePath) {
DataSchemaStubGenerator.StartWatching();
}

// use runtime names so the stubs match registered asset types
public static void GenerateAssetTypeStubs(Action<string>? log = null) {
var path = Path.Combine(CachePath, "lua", "asset_types.d.lua");
if (!ToastEngine.IsEngineReady) {
log?.Invoke("Engine not ready, asset_types.d.lua not regenerated yet");
return;
}
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
if (!ToastEngine.GenerateAssetTypeStubs(path)) log?.Invoke($"warning: failed to write {path}");
}

public static void SyncLuaDefinitions(Action<string>? log = null) {
var src = Path.Combine(CorePath, "lua");
var dst = Path.Combine(CachePath, "lua");
Expand All @@ -96,6 +107,9 @@ public static void SyncLuaDefinitions(Action<string>? log = null) {
UIBindStubGenerator.Generate();
DataSchemaStubGenerator.Generate();

// asset markers are unavailable until the engine starts
GenerateAssetTypeStubs(log);

var luarc = Path.Combine(ProjectPath, ".luarc.json");
if (File.Exists(luarc)) return;
File.WriteAllText(luarc,
Expand Down
6 changes: 3 additions & 3 deletions editor/Assets/Types/ScriptAsset.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ public sealed class ScriptAsset : BaseAsset {
public override bool CanBeCreated => true;
public override string Category => "Logic";
public override bool HasThumbnail => false;
public override bool CanBeEdited => false;
public override string EditorTool => "";
public override bool CanBeEdited => true;
public override string EditorTool => "LuaEditor";
public override string SchemaPath => "";

public override Task CreateAsync(string path) {
File.WriteAllText(path, "-- Toast Script\n");
File.WriteAllText(path, "-- Toast Script\nlocal M = {}\n\nreturn M\n");
return Task.CompletedTask;
}
}
26 changes: 26 additions & 0 deletions editor/Components/Elements/CollapseAnimator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Diagnostics;
using Avalonia.Threading;

namespace editor.Components.Elements;

public static class CollapseAnimator {
public const int DurationMs = 180;

public static DispatcherTimer Run(double from, double to, Action<double> apply, Action? done = null) {
var clock = Stopwatch.StartNew();
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(8) };
timer.Tick += (_, _) => {
var t = Math.Min(clock.ElapsedMilliseconds / (double)DurationMs, 1.0);
if (t >= 1) {
timer.Stop();
apply(to);
done?.Invoke();
return;
}
apply(from + (to - from) * (1 - Math.Pow(1 - t, 3)));
};
timer.Start();
return timer;
}
}
128 changes: 123 additions & 5 deletions editor/Components/Elements/EnumBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Threading;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
Expand All @@ -27,8 +29,21 @@ public sealed class EnumBox : TemplatedControl {
public static readonly DirectProperty<EnumBox, bool> IsOpenProperty =
AvaloniaProperty.RegisterDirect<EnumBox, bool>(nameof(IsOpen), o => o.m_isOpen);

public static readonly StyledProperty<IReadOnlyDictionary<string, string>?> GroupsProperty =
AvaloniaProperty.Register<EnumBox, IReadOnlyDictionary<string, string>?>(nameof(Groups));

public const int SearchThreshold = 12;

private sealed record Header(string Text, bool Folded, int Count);

private readonly HashSet<string> m_folded = [];

private bool m_isOpen;
private ItemsControl? m_list;
private TextBox? m_search;
private List<string> m_visible = [];
private int m_highlight = -1;
private Button? m_highlighted;

private Popup? m_popup;

Expand All @@ -42,6 +57,11 @@ public IEnumerable<string>? Options {
set => SetValue(OptionsProperty, value);
}

public IReadOnlyDictionary<string, string>? Groups {
get => GetValue(GroupsProperty);
set => SetValue(GroupsProperty, value);
}

public bool IsOpen {
get => m_isOpen;
private set => SetAndRaise(IsOpenProperty, ref m_isOpen, value);
Expand All @@ -60,16 +80,25 @@ protected override void OnApplyTemplate(TemplateAppliedEventArgs e) {

if (root is not null) root.Tapped += OnRootTapped;
if (m_popup is not null) m_popup.Closed += OnPopupClosed;
if (m_search is not null) {
m_search.TextChanged -= OnSearchChanged;
m_search.KeyDown -= OnSearchKey;
}
m_search = e.NameScope.Find<TextBox>("PART_Search");
if (m_search is not null) {
m_search.TextChanged += OnSearchChanged;
m_search.KeyDown += OnSearchKey;
}
if (m_list is not null) {
m_list.ItemTemplate = new FuncDataTemplate<string>((opt, _) => BuildOption(opt));
m_list.ItemsSource = Options;
m_list.ItemTemplate = new FuncDataTemplate<object>((item, _) => item is Header header ? BuildHeader(header) : BuildOption((string)item));
Rebuild();
}

}

protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) {
base.OnPropertyChanged(change);
if (change.Property == OptionsProperty && m_list is not null)
m_list.ItemsSource = Options;
if ((change.Property == OptionsProperty || change.Property == GroupsProperty) && m_list is not null) Rebuild();
}

private void OnRootTapped(object? sender, TappedEventArgs e) {
Expand All @@ -85,6 +114,93 @@ private void OnPopupClosed(object? sender, EventArgs e) {
private void ToggleOpen() {
IsOpen = !IsOpen;
if (m_popup is not null) m_popup.IsOpen = IsOpen;
if (!IsOpen) return;
if (m_search is not null) {
m_search.Text = "";
m_search.IsVisible = (Options?.Count() ?? 0) > SearchThreshold;
}
m_folded.Clear();
if (Groups is { } groupNames) {
var first = groupNames.Values.FirstOrDefault();
var current = Value is { } value && groupNames.TryGetValue(value, out var own) ? own : null;
foreach (var name in groupNames.Values.Distinct())
if (name != first && name != current) m_folded.Add(name);
}
Rebuild(highlightValue: true);
if (m_search is { IsVisible: true }) Dispatcher.UIThread.Post(() => m_search.Focus());
}

private void OnSearchChanged(object? sender, TextChangedEventArgs e) => Rebuild();

private void OnSearchKey(object? sender, KeyEventArgs e) {
switch (e.Key) {
case Key.Down:
m_highlight = Math.Min(m_highlight + 1, m_visible.Count - 1);
Rebuild(keepHighlight: true);
break;
case Key.Up:
m_highlight = Math.Max(m_highlight - 1, 0);
Rebuild(keepHighlight: true);
break;
case Key.Enter:
if (m_highlight >= 0 && m_highlight < m_visible.Count) Select(m_visible[m_highlight]);
break;
case Key.Escape:
IsOpen = false;
if (m_popup is not null) m_popup.IsOpen = false;
break;
default:
return;
}
e.Handled = true;
}

private void Rebuild(bool highlightValue = false, bool keepHighlight = false) {
if (m_list is null) return;
var all = Options?.ToList() ?? [];
var query = m_search?.Text?.Trim() ?? "";
var matching = all.Where(o => query.Length == 0 || o.Contains(query, StringComparison.OrdinalIgnoreCase)).ToList();
var items = new List<object>();
if (Groups is { } groups) {
var searching = query.Length > 0;
foreach (var group in matching.GroupBy(o => groups.GetValueOrDefault(o, "Other"))) {
var folded = !searching && m_folded.Contains(group.Key);
items.Add(new Header(group.Key, folded, group.Count()));
if (!folded) items.AddRange(group);
}
m_visible = items.OfType<string>().ToList();
} else {
m_visible = matching;
items.AddRange(matching);
}
if (!keepHighlight) m_highlight = highlightValue && Value is { } v && m_visible.IndexOf(v) is var at and >= 0 ? at : m_visible.Count > 0 ? 0 : -1;
m_highlighted = null;
m_list.ItemsSource = items;
Dispatcher.UIThread.Post(() => m_highlighted?.BringIntoView(), DispatcherPriority.Loaded);
}

private Control BuildHeader(Header header) {
var line = new Button {
Content = new TextBlock {
Text = (header.Folded ? "▸ " : "▾ ") + header.Text + " " + header.Count,
FontSize = 13,
FontWeight = FontWeight.Bold,
Foreground = Brush("Text")
},
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Left,
Background = Brush("Bg4"),
BorderThickness = new Thickness(0),
Padding = new Thickness(8, 5),
Margin = new Thickness(0, 4, 0, 0),
CornerRadius = new CornerRadius(4),
Cursor = new Cursor(StandardCursorType.Hand)
};
line.Click += (_, _) => {
if (!m_folded.Remove(header.Text)) m_folded.Add(header.Text);
Rebuild(keepHighlight: true);
};
return line;
}

private void Select(string option) {
Expand All @@ -95,11 +211,12 @@ private void Select(string option) {

private Control BuildOption(string option) {
var selected = string.Equals(option, Value, StringComparison.Ordinal);
var highlighted = m_highlight >= 0 && m_highlight < m_visible.Count && m_visible[m_highlight] == option;
var btn = new Button {
Content = option,
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Left,
Background = selected ? Brush("Red") : Brushes.Transparent,
Background = selected ? Brush("Red") : highlighted ? Brush("Bg4") : Brushes.Transparent,
Foreground = Brush(selected ? "Bg1" : "Text"),
BorderThickness = new Thickness(0),
Padding = new Thickness(8, 6),
Expand All @@ -108,6 +225,7 @@ private Control BuildOption(string option) {
FontSize = 15
};
btn.Click += (_, _) => Select(option);
if (highlighted) m_highlighted = btn;
return btn;
}

Expand Down
9 changes: 9 additions & 0 deletions editor/Components/Modals/PickerWindow.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ public partial class PickerWindow : Window {
private object? m_selected;
private string? m_hoveredThumbnail;

public PickerWindow() : this(new EmptyPickerViewModel()) { }

private sealed class EmptyPickerViewModel : PickerViewModel {
public override string WindowTitle => "Select";
public override System.Collections.IEnumerable Items => Array.Empty<object>();
public override void UpdateFilter(string query, bool caseSensitive) { }
public override string? GetResult(object? selected) => null;
}

protected PickerWindow(PickerViewModel vm) {
DataContext = vm;
InitializeComponent();
Expand Down
2 changes: 2 additions & 0 deletions editor/Components/Modals/RenameModal.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
namespace editor.Components.Modals;

public partial class RenameModal : Window {
public RenameModal() : this("") { }

public RenameModal(
string initialName,
string title = "Rename",
Expand Down
16 changes: 1 addition & 15 deletions editor/Editors/PaletteView.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,21 +93,7 @@ private void AnimateWidth(int column, double from, double to, GridLength final)
m_timers[column]?.Stop();

var definition = Root.ColumnDefinitions[column];
var clock = Stopwatch.StartNew();
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(8) };
m_timers[column] = timer;
timer.Tick += (_, _) => {
var t = Math.Min(clock.ElapsedMilliseconds / (double)AnimationMs, 1.0);
var eased = 1 - Math.Pow(1 - t, 3);
if (t >= 1) {
timer.Stop();
definition.Width = final;
return;
}

definition.Width = new GridLength(from + (to - from) * eased);
};
timer.Start();
m_timers[column] = Components.Elements.CollapseAnimator.Run(from, to, width => definition.Width = new GridLength(width), () => definition.Width = final);
}

private void OnLabelTapped(object? sender, TappedEventArgs e) {
Expand Down
11 changes: 10 additions & 1 deletion editor/Engine/ToastEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ public ToastEngine(string toastPath) {
toast_init();
IsEngineReady = true;
DataSchemaStubGenerator.Generate();
// fresh projects need asset markers after engine startup
ProjectContext.GenerateAssetTypeStubs();
toast_create_avalonia_window();

ReflectionDatabase.Update();
Expand Down Expand Up @@ -236,7 +238,7 @@ public static T OnTickThread<T>(Func<T> work) {
failure = new OperationCanceledException("The engine stopped before the work could run");
finished.Set();
}));

// The loop may have ended before the adding to the queue
if (!engine.m_ticking) engine.CancelPendingTickWork();
finished.Wait();
Expand Down Expand Up @@ -645,6 +647,13 @@ public static bool GenerateDataSchemaStubs(string outPath) {
return IsEngineReady && toast_generate_data_schema_stubs(outPath) != 0;
}

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

public static bool GenerateAssetTypeStubs(string outPath) {
return IsEngineReady && toast_generate_asset_type_stubs(outPath) != 0;
}

private delegate IntPtr GameCreate();

private delegate void GameDestroy(IntPtr game);
Expand Down
Loading
Loading