|
| 1 | +using Avalonia.Controls; |
| 2 | +using Avalonia.Threading; |
| 3 | +using Stride.CommunityToolkit.Examples.Core; |
| 4 | +using System.Collections.ObjectModel; |
| 5 | +using System.Diagnostics; |
| 6 | +using System.Text; |
| 7 | +using System.Text.RegularExpressions; |
| 8 | + |
| 9 | +namespace Stride.CommunityToolkit.Examples.Launcher; |
| 10 | + |
| 11 | +public partial class MainWindow : Window |
| 12 | +{ |
| 13 | + private readonly ObservableCollection<ExampleListItem> _examples = []; |
| 14 | + private readonly List<ExampleProjectMeta> _all = []; |
| 15 | + private Process? _running; |
| 16 | + private CancellationTokenSource? _cts; |
| 17 | + |
| 18 | + private static readonly Regex GenericWarning = new(@"\bwarning\b", RegexOptions.IgnoreCase | RegexOptions.Compiled); |
| 19 | + private static readonly Regex ShaderWarning = new(@"\b(effect|shader|hlsl|fx|mixin|compiler)\b.*\bwarning\b|\bwarning\b.*\b(effect|shader|hlsl|fx|mixin|compiler)\b", |
| 20 | + RegexOptions.IgnoreCase | RegexOptions.Compiled); |
| 21 | + |
| 22 | + public MainWindow() |
| 23 | + { |
| 24 | + InitializeComponent(); |
| 25 | + |
| 26 | + ExamplesList.ItemsSource = _examples; |
| 27 | + |
| 28 | + LoadExamples(); |
| 29 | + |
| 30 | + SearchBox.PropertyChanged += (s, e) => |
| 31 | + { |
| 32 | + if (e.Property.Name == nameof(TextBox.Text)) |
| 33 | + Filter(SearchBox.Text); |
| 34 | + }; |
| 35 | + |
| 36 | + BtnRun.Click += async (_, __) => await RunSelectedAsync(); |
| 37 | + BtnStop.Click += (_, __) => StopRunning(); |
| 38 | + BtnOpenFolder.Click += (_, __) => OpenFolder(); |
| 39 | + BtnCopyCmd.Click += (_, __) => CopyCommand(); |
| 40 | + BtnClearLog.Click += (_, __) => LogPanel.Text = string.Empty; |
| 41 | + } |
| 42 | + |
| 43 | + private void LoadExamples() |
| 44 | + { |
| 45 | + var provider = new ExampleProvider(); |
| 46 | + var examples = provider.GetExamples() |
| 47 | + .Where(e => e.Title != Constants.Quit && e.Title != Constants.Clear) |
| 48 | + .Select(e => new ExampleProjectMeta(e.Id, e.Title, GetProjectPath(e), GetOrder(e), e.Category)) |
| 49 | + .ToList(); |
| 50 | + |
| 51 | + _all.AddRange(examples); |
| 52 | + foreach (var e in _all) |
| 53 | + _examples.Add(new ExampleListItem(e)); |
| 54 | + } |
| 55 | + |
| 56 | + private static string GetProjectPath(Example example) |
| 57 | + { |
| 58 | + var baseDir = AppDomain.CurrentDomain.BaseDirectory; |
| 59 | + var examplesRoot = FindExamplesRoot(baseDir) ?? Path.GetFullPath(Path.Combine(baseDir, "..", "..", "..", "..", "..", "examples", "code-only")); |
| 60 | + |
| 61 | + var projectName = example.ProjectName ?? example.Title.Replace(" ", "_"); |
| 62 | + var patterns = new[] { "*.csproj", "*.fsproj", "*.vbproj" }; |
| 63 | + |
| 64 | + foreach (var pattern in patterns) |
| 65 | + { |
| 66 | + var files = Directory.EnumerateFiles(examplesRoot, pattern, SearchOption.AllDirectories) |
| 67 | + .Where(f => Path.GetFileNameWithoutExtension(f).Contains(projectName, StringComparison.OrdinalIgnoreCase)) |
| 68 | + .ToList(); |
| 69 | + |
| 70 | + if (files.Count > 0) return files[0]; |
| 71 | + } |
| 72 | + |
| 73 | + return string.Empty; |
| 74 | + } |
| 75 | + |
| 76 | + private static string? FindExamplesRoot(string baseDir) |
| 77 | + { |
| 78 | + var dir = baseDir; |
| 79 | + for (int i = 0; i < 8 && !string.IsNullOrEmpty(dir); i++) |
| 80 | + { |
| 81 | + var candidate = Path.Combine(dir, "examples", "code-only"); |
| 82 | + if (Directory.Exists(candidate)) |
| 83 | + return candidate; |
| 84 | + |
| 85 | + dir = Path.GetDirectoryName(dir?.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); |
| 86 | + } |
| 87 | + return null; |
| 88 | + } |
| 89 | + |
| 90 | + private static int? GetOrder(Example example) |
| 91 | + { |
| 92 | + if (example.Category == Constants.BasicExample) return 1; |
| 93 | + if (example.Category == Constants.AdvanceExample) return 2; |
| 94 | + return 3; |
| 95 | + } |
| 96 | + |
| 97 | + private void Filter(string? text) |
| 98 | + { |
| 99 | + text ??= string.Empty; |
| 100 | + text = text.Trim(); |
| 101 | + |
| 102 | + _examples.Clear(); |
| 103 | + foreach (var e in _all) |
| 104 | + { |
| 105 | + if (text.Length == 0 || |
| 106 | + e.Title.Contains(text, StringComparison.OrdinalIgnoreCase) || |
| 107 | + e.Id.Contains(text, StringComparison.OrdinalIgnoreCase) || |
| 108 | + (e.Category?.Contains(text, StringComparison.OrdinalIgnoreCase) ?? false)) |
| 109 | + { |
| 110 | + _examples.Add(new ExampleListItem(e)); |
| 111 | + } |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + private ExampleProjectMeta? Current |
| 116 | + { |
| 117 | + get |
| 118 | + { |
| 119 | + var item = ExamplesList.SelectedItem as ExampleListItem; |
| 120 | + return item?.Meta; |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + private async Task RunSelectedAsync() |
| 125 | + { |
| 126 | + var meta = Current; |
| 127 | + if (meta is null) |
| 128 | + { |
| 129 | + AppendLine("⚠️ Please select an example to run."); |
| 130 | + return; |
| 131 | + } |
| 132 | + |
| 133 | + if (string.IsNullOrEmpty(meta.ProjectFile) || !File.Exists(meta.ProjectFile)) |
| 134 | + { |
| 135 | + AppendLine($"❌ Project file not found: {meta.ProjectFile}"); |
| 136 | + return; |
| 137 | + } |
| 138 | + |
| 139 | + StopRunning(); |
| 140 | + |
| 141 | + LogPanel.Text = string.Empty; |
| 142 | + AppendLine($"▶️ Starting: {meta.Title}"); |
| 143 | + AppendLine($"📁 Project: {meta.ProjectFile}"); |
| 144 | + AppendLine(new string('-', 80)); |
| 145 | + |
| 146 | + _cts = new CancellationTokenSource(); |
| 147 | + |
| 148 | + var psi = new ProcessStartInfo |
| 149 | + { |
| 150 | + FileName = "dotnet", |
| 151 | + Arguments = $"run --project \"{meta.ProjectFile}\"", |
| 152 | + WorkingDirectory = Path.GetDirectoryName(meta.ProjectFile) ?? Environment.CurrentDirectory, |
| 153 | + UseShellExecute = false, |
| 154 | + RedirectStandardOutput = true, |
| 155 | + RedirectStandardError = true, |
| 156 | + CreateNoWindow = true |
| 157 | + }; |
| 158 | + |
| 159 | + _running = new Process { StartInfo = psi, EnableRaisingEvents = true }; |
| 160 | + var process = _running; |
| 161 | + |
| 162 | + try |
| 163 | + { |
| 164 | + process.Start(); |
| 165 | + var readOut = Task.Run(() => ReadLinesAsync(process.StandardOutput, isError: false, _cts.Token)); |
| 166 | + var readErr = Task.Run(() => ReadLinesAsync(process.StandardError, isError: true, _cts.Token)); |
| 167 | + await Task.WhenAll(readOut, readErr); |
| 168 | + |
| 169 | + process.WaitForExit(); |
| 170 | + var exitCode = process.ExitCode; |
| 171 | + AppendLine($"✅ Process exited with code: {exitCode}"); |
| 172 | + } |
| 173 | + catch (Exception ex) |
| 174 | + { |
| 175 | + AppendLine($"❌ Error: {ex.Message}"); |
| 176 | + StopRunning(); |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + private void StopRunning() |
| 181 | + { |
| 182 | + try |
| 183 | + { |
| 184 | + _cts?.Cancel(); |
| 185 | + if (_running is { HasExited: false }) |
| 186 | + { |
| 187 | + AppendLine("⏹️ Stopping process..."); |
| 188 | + _running.Kill(entireProcessTree: true); |
| 189 | + _running.WaitForExit(2000); |
| 190 | + AppendLine("✅ Process stopped."); |
| 191 | + } |
| 192 | + } |
| 193 | + catch (Exception ex) |
| 194 | + { |
| 195 | + AppendLine($"⚠️ Error stopping process: {ex.Message}"); |
| 196 | + } |
| 197 | + finally |
| 198 | + { |
| 199 | + _running?.Dispose(); |
| 200 | + _running = null; |
| 201 | + _cts?.Dispose(); |
| 202 | + _cts = null; |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + private async Task ReadLinesAsync(StreamReader reader, bool isError, CancellationToken ct) |
| 207 | + { |
| 208 | + while (!ct.IsCancellationRequested) |
| 209 | + { |
| 210 | + string? line; |
| 211 | + try { line = await reader.ReadLineAsync(); } |
| 212 | + catch { break; } |
| 213 | + if (line is null) break; |
| 214 | + |
| 215 | + if (ShouldSuppress(line)) continue; |
| 216 | + |
| 217 | + AppendLine(line, isError); |
| 218 | + } |
| 219 | + } |
| 220 | + |
| 221 | + private static bool ShouldSuppress(string line) |
| 222 | + { |
| 223 | + var showAll = string.Equals(Environment.GetEnvironmentVariable("SHOW_WARNINGS"), "1", StringComparison.OrdinalIgnoreCase) |
| 224 | +|| string.Equals(Environment.GetEnvironmentVariable("SHOW_WARNINGS"), "true", StringComparison.OrdinalIgnoreCase); |
| 225 | + if (showAll) return false; |
| 226 | + |
| 227 | + if (!GenericWarning.IsMatch(line)) return false; |
| 228 | + return ShaderWarning.IsMatch(line); |
| 229 | + } |
| 230 | + |
| 231 | + private void AppendLine(string text, bool isError = false) |
| 232 | + { |
| 233 | + Dispatcher.UIThread.Post(() => |
| 234 | + { |
| 235 | + var sb = new StringBuilder(LogPanel.Text ?? string.Empty); |
| 236 | + if (sb.Length > 0) sb.AppendLine(); |
| 237 | + if (isError) sb.Append("❌ "); |
| 238 | + sb.Append(text); |
| 239 | + LogPanel.Text = sb.ToString(); |
| 240 | + }); |
| 241 | + } |
| 242 | + |
| 243 | + private void OpenFolder() |
| 244 | + { |
| 245 | + var meta = Current; |
| 246 | + if (meta is null) return; |
| 247 | + var dir = Path.GetDirectoryName(meta.ProjectFile); |
| 248 | + if (dir is null || !Directory.Exists(dir)) |
| 249 | + { |
| 250 | + AppendLine("⚠️ Folder not found."); |
| 251 | + return; |
| 252 | + } |
| 253 | + |
| 254 | + try |
| 255 | + { |
| 256 | + Process.Start(new ProcessStartInfo { FileName = dir, UseShellExecute = true }); |
| 257 | + } |
| 258 | + catch (Exception ex) |
| 259 | + { |
| 260 | + AppendLine($"❌ Error opening folder: {ex.Message}"); |
| 261 | + } |
| 262 | + } |
| 263 | + |
| 264 | + private void CopyCommand() |
| 265 | + { |
| 266 | + var meta = Current; |
| 267 | + if (meta is null) return; |
| 268 | + var cmd = $"dotnet run --project \"{meta.ProjectFile}\""; |
| 269 | + |
| 270 | + try |
| 271 | + { |
| 272 | + Clipboard?.SetTextAsync(cmd); |
| 273 | + AppendLine($"📋 Copied to clipboard: {cmd}"); |
| 274 | + } |
| 275 | + catch (Exception ex) |
| 276 | + { |
| 277 | + AppendLine($"❌ Error copying to clipboard: {ex.Message}"); |
| 278 | + } |
| 279 | + } |
| 280 | + |
| 281 | + private class ExampleListItem(ExampleProjectMeta meta) |
| 282 | + { |
| 283 | + public ExampleProjectMeta Meta { get; } = meta; |
| 284 | + |
| 285 | + public override string ToString() |
| 286 | + { |
| 287 | + var cat = !string.IsNullOrEmpty(meta.Category) ? $"[{meta.Category}] " : ""; |
| 288 | + return $"{cat}{meta.Title} ({meta.Id})"; |
| 289 | + } |
| 290 | + } |
| 291 | +} |
0 commit comments