-
Notifications
You must be signed in to change notification settings - Fork 767
Expand file tree
/
Copy pathRunner.cs
More file actions
383 lines (311 loc) · 12.9 KB
/
Runner.cs
File metadata and controls
383 lines (311 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#nullable enable
using System.Data;
using System.Reflection;
using System.Text.Json;
namespace UICatalog;
/// <summary>
/// Provides functionality for running and benchmarking Terminal.Gui <see cref="Scenario"/>s.
/// </summary>
public class Runner
{
/// <summary>
/// Sets <see cref="ConfigurationManager.RuntimeConfig"/> with "Application.ForceDriver" and ["Driver.Force16Colors" based on the params.
/// </summary>
/// <param name="forceDriver">The driver to use, or null to use the default.</param>
/// <param name="force16Colors">
/// Whether to force 16-color mode. If null, the current setting is preserved.
/// </param>
public void SetRuntimeConfig (string? forceDriver = null, bool? force16Colors = null)
{
// Create runtime config JSON containing "Application.ForceDriver" and "Driver.Force16Colors" if specified
Dictionary<string, object> runtimeConfig = new ();
if (!string.IsNullOrEmpty (forceDriver))
{
runtimeConfig ["Application.ForceDriver"] = forceDriver;
}
if (force16Colors.HasValue)
{
runtimeConfig ["Driver.Force16Colors"] = force16Colors.Value;
}
if (runtimeConfig.Count == 0)
{
return;
}
ConfigurationManager.RuntimeConfig = JsonSerializer.Serialize (runtimeConfig);
}
/// <summary>
/// Runs a single scenario with optional benchmarking.
/// </summary>
/// <param name="scenarioName"></param>
/// <param name="benchmark">Whether to collect benchmark metrics.</param>
/// <returns>Benchmark results if benchmarking was enabled, otherwise null.</returns>
public BenchmarkResults? RunScenario (string scenarioName, bool benchmark)
{
// Mark log position so we can capture logs for just this scenario
UICatalog.LogCapture.MarkScenarioStart ();
// Create instance of the scenario
var scenario = (Scenario)Activator.CreateInstance (Scenario.GetScenarios ()
.FirstOrDefault (s => s.GetName ().Equals (scenarioName, StringComparison.OrdinalIgnoreCase))
!.GetType ())!;
if (benchmark)
{
scenario.StartBenchmark ();
}
Logging.Information ($"Calling {scenario.GetName ()}.Main()");
scenario.Main ();
Logging.Information ($"Returned from {scenario.GetName ()}.Main()");
BenchmarkResults? results = null;
if (benchmark)
{
results = scenario.EndBenchmark ();
}
scenario.Dispose ();
// Check for undisposed views (logs errors if DEBUG_IDISPOSABLE is defined)
#if DEBUG_IDISPOSABLE
View.VerifyViewsWereDisposed ();
#endif
return results;
}
/// <summary>
/// Runs benchmarks for all provided scenarios.
/// </summary>
/// <param name="scenarios">The scenarios to benchmark.</param>
/// <returns>List of benchmark results for all scenarios.</returns>
public List<BenchmarkResults> BenchmarkAllScenarios (IEnumerable<Scenario> scenarios)
{
List<BenchmarkResults> resultsList = [];
foreach (Scenario s in scenarios)
{
BenchmarkResults? result = RunScenario (s.GetName (), true);
if (result is { })
{
resultsList.Add (result);
}
}
return resultsList;
}
/// <summary>
/// Saves benchmark results to a JSON file.
/// </summary>
/// <param name="results">The results to save.</param>
/// <param name="filePath">The file path to write to.</param>
public static void SaveResultsToFile (List<BenchmarkResults> results, string filePath)
{
string output = JsonSerializer.Serialize (results, new JsonSerializerOptions { WriteIndented = true });
using StreamWriter file = File.CreateText (filePath);
file.Write (output);
file.Close ();
}
/// <summary>
/// Displays benchmark results in a TableView UI.
/// </summary>
/// <param name="results">The results to display.</param>
public static void DisplayResultsUI (List<BenchmarkResults> results)
{
if (results.Count <= 0)
{
return;
}
using IApplication app = Application.Create ();
app.Init ();
using Window benchmarkWindow = new ();
benchmarkWindow.Title = "Benchmark Results";
if (benchmarkWindow.Border is { })
{
benchmarkWindow.Border.Thickness = new Thickness (0, 0, 0, 0);
}
TableView resultsTableView = new () { Width = Dim.Fill (), Height = Dim.Fill () };
// TableView provides many options for table headers. For simplicity we turn all
// of these off. By enabling FullRowSelect and turning off headers, TableView looks just
// like a ListView
resultsTableView.FullRowSelect = true;
resultsTableView.Style.ShowHeaders = true;
resultsTableView.Style.ShowHorizontalHeaderOverline = false;
resultsTableView.Style.ShowHorizontalHeaderUnderline = true;
resultsTableView.Style.ShowHorizontalBottomLine = false;
resultsTableView.Style.ShowVerticalCellLines = true;
resultsTableView.Style.ShowVerticalHeaderLines = true;
// TableView typically is a grid where nav keys are biased for moving left/right.
resultsTableView.KeyBindings.Remove (Key.Home);
resultsTableView.KeyBindings.Add (Key.Home, Command.Start);
resultsTableView.KeyBindings.Remove (Key.End);
resultsTableView.KeyBindings.Add (Key.End, Command.End);
// Ideally, TableView.MultiSelect = false would turn off any keybindings for
// multi-select options. But it currently does not.
resultsTableView.MultiSelect = false;
DataTable dt = new ();
dt.Columns.Add (new DataColumn ("Scenario", typeof (string)));
dt.Columns.Add (new DataColumn ("Duration", typeof (TimeSpan)));
dt.Columns.Add (new DataColumn ("Refreshed", typeof (int)));
dt.Columns.Add (new DataColumn ("LaidOut", typeof (int)));
dt.Columns.Add (new DataColumn ("ClearedContent", typeof (int)));
dt.Columns.Add (new DataColumn ("DrawComplete", typeof (int)));
dt.Columns.Add (new DataColumn ("Updated", typeof (int)));
dt.Columns.Add (new DataColumn ("Iterations", typeof (int)));
foreach (BenchmarkResults r in results)
{
dt.Rows.Add (r.Scenario,
r.Duration,
r.RefreshedCount,
r.LaidOutCount,
r.ClearedContentCount,
r.DrawCompleteCount,
r.UpdatedCount,
r.IterationCount);
}
BenchmarkResults totalRow = new ()
{
Scenario = "TOTAL",
Duration = new TimeSpan (results.Sum (r => r.Duration.Ticks)),
RefreshedCount = results.Sum (r => r.RefreshedCount),
LaidOutCount = results.Sum (r => r.LaidOutCount),
ClearedContentCount = results.Sum (r => r.ClearedContentCount),
DrawCompleteCount = results.Sum (r => r.DrawCompleteCount),
UpdatedCount = results.Sum (r => r.UpdatedCount),
IterationCount = results.Sum (r => r.IterationCount)
};
dt.Rows.Add (totalRow.Scenario,
totalRow.Duration,
totalRow.RefreshedCount,
totalRow.LaidOutCount,
totalRow.ClearedContentCount,
totalRow.DrawCompleteCount,
totalRow.UpdatedCount,
totalRow.IterationCount);
dt.DefaultView.Sort = "Duration";
DataTable sortedCopy = dt.DefaultView.ToTable ();
resultsTableView.Table = new DataTableSource (sortedCopy);
benchmarkWindow.Add (resultsTableView);
app.Run (benchmarkWindow);
}
#region Interactive Mode
private static readonly FileSystemWatcher _currentDirWatcher = new ();
private static readonly FileSystemWatcher _homeDirWatcher = new ();
private bool _configWatcherStarted;
/// <summary>
/// Runs in interactive mode, showing a UI to select scenarios and running them in a loop.
/// </summary>
/// <typeparam name="T">The Runnable type to use as the scenario browser UI.</typeparam>
/// <param name="enableConfigWatcher">Whether to enable config file watching.</param>
public void RunInteractive<T> (bool enableConfigWatcher = true) where T : Runnable, new ()
{
Logging.Information ($"{typeof (T).Name}");
#if DEBUG_IDISPOSABLE
View.EnableDebugIDisposableAsserts = true;
#endif
if (enableConfigWatcher)
{
StartConfigWatcher ();
}
try
{
// Show browser UI, get selected scenario, run it, repeat until user quits
while (true)
{
IApplication app = RunBrowserUI<T> ();
var selectedScenarioName = app.GetResult<string> ();
//Logging.Trace($"Disposing app");
app.Dispose ();
if (string.IsNullOrEmpty (selectedScenarioName))
{
// User wants to quit
break;
}
RunScenario (selectedScenarioName, false);
}
}
finally
{
if (enableConfigWatcher)
{
StopConfigWatcher ();
}
#if DEBUG_IDISPOSABLE
View.VerifyViewsWereDisposed ();
#endif
}
}
/// <summary>
/// Runs the browser UI. The browser UI should set <see cref="IRunnable.Result"/> to the selected scenario name
/// </summary>
/// <typeparam name="T">The Runnable type to use as the browser UI.</typeparam>
private IApplication RunBrowserUI<T> () where T : Runnable, new ()
{
IApplication app = Application.Create ();
app.Init ();
Logging.Information ($"{typeof (T).Name}");
app.Run<T> ();
Logging.Information ($"{typeof (T).Name} Result: {app.GetResult<string> ()}");
//VerifyObjectsWereDisposed ();
return app;
}
/// <summary>
/// Starts watching for configuration file changes.
/// </summary>
public void StartConfigWatcher ()
{
if (_configWatcherStarted)
{
return;
}
// Set up a file system watcher for `./.tui/`
_currentDirWatcher.NotifyFilter = NotifyFilters.LastWrite;
string assemblyLocation = Assembly.GetExecutingAssembly ().Location;
string tuiDir;
if (!string.IsNullOrEmpty (assemblyLocation))
{
FileInfo assemblyFile = new (assemblyLocation);
tuiDir = Path.Combine (assemblyFile.Directory!.FullName, ".tui");
}
else
{
tuiDir = Path.Combine (AppContext.BaseDirectory, ".tui");
}
if (!Directory.Exists (tuiDir))
{
Directory.CreateDirectory (tuiDir);
}
_currentDirWatcher.Path = tuiDir;
_currentDirWatcher.Filter = "*config.json";
// Set up a file system watcher for `~/.tui/`
_homeDirWatcher.NotifyFilter = NotifyFilters.LastWrite;
FileInfo homeDir = new (Environment.GetFolderPath (Environment.SpecialFolder.UserProfile));
tuiDir = Path.Combine (homeDir.FullName, ".tui");
if (!Directory.Exists (tuiDir))
{
Directory.CreateDirectory (tuiDir);
}
_homeDirWatcher.Path = tuiDir;
_homeDirWatcher.Filter = "*config.json";
_currentDirWatcher.Changed += ConfigFileChanged;
_currentDirWatcher.EnableRaisingEvents = true;
_homeDirWatcher.Changed += ConfigFileChanged;
_homeDirWatcher.EnableRaisingEvents = true;
ThemeManager.ThemeChanged += ThemeManagerOnThemeChanged;
_configWatcherStarted = true;
}
/// <summary>
/// Stops watching for configuration file changes.
/// </summary>
public void StopConfigWatcher ()
{
if (!_configWatcherStarted)
{
return;
}
ThemeManager.ThemeChanged -= ThemeManagerOnThemeChanged;
_currentDirWatcher.EnableRaisingEvents = false;
_currentDirWatcher.Changed -= ConfigFileChanged;
_homeDirWatcher.EnableRaisingEvents = false;
_homeDirWatcher.Changed -= ConfigFileChanged;
_configWatcherStarted = false;
}
private static void ThemeManagerOnThemeChanged (object? sender, EventArgs<string> e) => ConfigurationManager.Apply ();
private static void ConfigFileChanged (object sender, FileSystemEventArgs e)
{
Logging.Debug ($"{e.FullPath} {e.ChangeType} - Loading and Applying");
ConfigurationManager.Load (ConfigLocations.All);
ConfigurationManager.Apply ();
}
#endregion Interactive Mode
}