-
Notifications
You must be signed in to change notification settings - Fork 767
Expand file tree
/
Copy pathUICatalogRunnable.cs
More file actions
1019 lines (832 loc) · 40 KB
/
UICatalogRunnable.cs
File metadata and controls
1019 lines (832 loc) · 40 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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#nullable enable
using System.Collections.ObjectModel;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using Terminal.Gui;
using RuntimeEnvironment = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment;
using Trace = Terminal.Gui.Tracing.Trace;
namespace UICatalog;
/// <summary>
/// This is the main UI Catalog app view. It is run fresh when the app loads (if a Scenario has not been passed on
/// the command line) and each time a Scenario ends.
/// </summary>
public sealed class UICatalogRunnable : Runnable
{
// When a scenario is run, the main app is killed. The static
// members are cached so that when the scenario exits the
// main app UI can be restored to previous state
// Note, we used to pass this to scenarios that run, but it just added complexity
// So that was removed. But we still have this here to demonstrate how changing
// the scheme works.
public static string? CachedRunnableScheme { get; set; }
public UICatalogRunnable ()
{
SchemeName = CachedRunnableScheme = SchemeManager.SchemesToSchemeName (Schemes.Base);
ConfigurationManager.Applied += ConfigAppliedHandler;
}
/// <inheritdoc/>
public override void BeginInit ()
{
_menuBar = CreateMenuBar ();
_statusBar = CreateStatusBar ();
_categoryList = CreateCategoryList ();
_scenarioList = CreateScenarioList ();
Add (_menuBar, _categoryList, _scenarioList, _statusBar);
// Restore previous selections
if (_categoryList.Source?.Count > 0)
{
_categoryList.SelectedItem = _cachedCategoryIndex ?? 0;
}
else
{
_categoryList.SelectedItem = null;
}
_scenarioList.SelectedRow = _cachedScenarioIndex;
base.BeginInit ();
}
/// <inheritdoc/>
protected override void OnIsModalChanged (bool newIsModal)
{
if (App is null)
{
return;
}
_disableMouseCb?.Value = App.Mouse.IsMouseDisabled ? CheckState.Checked : CheckState.UnChecked;
_shVersion?.Title = $"{RuntimeEnvironment.OperatingSystem} {RuntimeEnvironment.OperatingSystemVersion}, {App?.Driver?.GetVersionInfo ()}";
if (string.IsNullOrEmpty ((string?)Result))
{
_isFirstRunning = false;
}
if (!_isFirstRunning)
{
_scenarioList?.SetFocus ();
}
_categoryList?.EnsureSelectedItemVisible ();
_scenarioList?.EnsureSelectedCellIsVisible ();
if (ShowStatusBar)
{
_statusBar?.Height = Dim.Auto ();
}
else
{
_statusBar?.Height = 0;
}
}
/// <inheritdoc/>
protected override void OnIsRunningChanged (bool newIsRunning)
{
if (newIsRunning)
{
// Show error dialog if any errors occurred during the scenario
if (!UICatalog.LogCapture.HasErrors)
{
return;
}
if (_scenarioList is { } && App is { } && _scenarioList.Table is { })
{
ShowScenarioErrorsDialog (App,
_scenarioList.Table [_scenarioList.SelectedRow, 0].ToString () ?? string.Empty,
UICatalog.LogCapture.GetScenarioLogs ());
}
UICatalog.LogCapture.HasErrors = false;
return;
}
ConfigurationManager.Applied -= ConfigAppliedHandler;
}
// Track if this is the first time running the main UI Catalog screen
private static bool _isFirstRunning = true;
#region MenuBar
private MenuBar? _menuBar;
private CheckBox? _force16ColorsMenuItemCb;
private OptionSelector? _themesSelector;
private OptionSelector? _topSchemesSelector;
private OptionSelector? _logLevelSelector;
private FlagSelector<ViewDiagnosticFlags>? _diagnosticFlagsSelector;
private CheckBox? _disableMouseCb;
private MenuBar CreateMenuBar ()
{
MenuBar menuBar = new ([
new MenuBarItem (Strings.menuFile,
[
new MenuItem
{
Title = Strings.cmdQuit,
HelpText = "Quit UI Catalog",
Key = Application.GetDefaultKey (Command.Quit),
// By not specifying TargetView the Key Binding will be Application-level
Command = Command.Quit
}
]),
new MenuBarItem ("_Themes", CreateThemeMenuItems ()),
new MenuBarItem ("Diag_nostics", CreateDiagnosticMenuItems ()),
new MenuBarItem ("_Logging", CreateLoggingMenuItems ()!),
new MenuBarItem (Strings.menuHelp,
[
new MenuItem ("_Documentation",
"API docs",
() => Link.OpenUrl ("https://gui-cs.github.io/Terminal.Gui"),
Key.F1),
new MenuItem ("_README",
"Project readme",
() => Link.OpenUrl ("https://github.com/gui-cs/Terminal.Gui"),
Key.F2),
new MenuItem ("_About...", "About UI Catalog", ShowAboutDialog, Key.A.WithCtrl)
])
]) { Title = "menuBar", Id = "menuBar" };
return menuBar;
View [] CreateThemeMenuItems ()
{
List<View> menuItems = [];
_force16ColorsMenuItemCb = new CheckBox { Title = "Force _16 Colors", Value = Driver.Force16Colors ? CheckState.Checked : CheckState.UnChecked };
menuItems.Add (new MenuItem
{
CommandView = _force16ColorsMenuItemCb,
Action = () =>
{
Driver.Force16Colors = !Driver.Force16Colors;
_force16ColorsShortcutCb?.Value = Driver.Force16Colors ? CheckState.Checked : CheckState.UnChecked;
SetNeedsDraw ();
}
});
menuItems.Add (new Line ());
if (ConfigurationManager.IsEnabled)
{
_themesSelector = new OptionSelector { CanFocus = true };
_themesSelector.ValueChanged += OnThemesSelectorOnValueChanged;
MenuItem menuItem = new () { CommandView = _themesSelector, HelpText = "Cycle Through Themes", Key = Key.T.WithCtrl };
menuItems.Add (menuItem);
menuItems.Add (new Line ());
_topSchemesSelector = new OptionSelector ();
_topSchemesSelector.ValueChanged += OnTopSchemesSelectorOnValueChanged;
menuItem = new MenuItem
{
Title = "Scheme for Runnable",
SubMenu = new Menu ([new MenuItem { CommandView = _topSchemesSelector, HelpText = "Cycle Through Schemes", Key = Key.S.WithCtrl }])
};
menuItems.Add (menuItem);
UpdateThemesMenu ();
}
else
{
menuItems.Add (new MenuItem { Title = "Configuration Manager is not Enabled", Enabled = false });
}
return menuItems.ToArray ();
void OnTopSchemesSelectorOnValueChanged (object? _, ValueChangedEventArgs<int?> args)
{
if (args.NewValue is null)
{
return;
}
CachedRunnableScheme = SchemeManager.GetSchemesForCurrentTheme ().Keys.ToArray () [(int)args.NewValue];
SchemeName = CachedRunnableScheme;
SetNeedsDraw ();
}
void OnThemesSelectorOnValueChanged (object? _, ValueChangedEventArgs<int?> args)
{
if (args.NewValue is null)
{
return;
}
ThemeManager.Theme = ThemeManager.GetThemeNames () [(int)args.NewValue];
}
}
View [] CreateDiagnosticMenuItems ()
{
List<View> menuItems = [];
_diagnosticFlagsSelector = new FlagSelector<ViewDiagnosticFlags> { Styles = SelectorStyles.ShowNoneFlag };
_diagnosticFlagsSelector.UsedHotKeys.Add (Key.D);
_diagnosticFlagsSelector.AssignHotKeys = true;
_diagnosticFlagsSelector.Value = Diagnostics;
_diagnosticFlagsSelector.ValueChanged += OnDiagnosticFlagsSelectorOnValueChanged;
MenuItem diagFlagMenuItem = new () { CommandView = _diagnosticFlagsSelector, HelpText = "View Diagnostics" };
menuItems.Add (diagFlagMenuItem);
menuItems.Add (new Line ());
_disableMouseCb = new CheckBox
{
Title = "_Disable MouseEventArgs", Value = App?.Mouse.IsMouseDisabled == true ? CheckState.Checked : CheckState.UnChecked
};
_disableMouseCb.ValueChanged += (_, args) => { App?.Mouse.IsMouseDisabled = args.NewValue == CheckState.Checked; };
menuItems.Add (new MenuItem { CommandView = _disableMouseCb, HelpText = "Disable MouseEventArgs" });
return menuItems.ToArray ();
void OnDiagnosticFlagsSelectorOnValueChanged (object? _, EventArgs<ViewDiagnosticFlags?> args) =>
Diagnostics = args.Value ?? ViewDiagnosticFlags.Off;
}
View [] CreateLoggingMenuItems ()
{
List<View?> menuItems = [];
_logLevelSelector = new OptionSelector
{
AssignHotKeys = true,
Labels = Enum.GetNames<LogLevel> (),
Value = Enum.GetValues<LogLevel> ().ToList ().IndexOf (Enum.Parse<LogLevel> (UICatalog.Options.DebugLogLevel))
};
MenuItem logMenu = new () { CommandView = _logLevelSelector, HelpText = "Cycle Through Log Levels", Key = Key.L.WithCtrl };
_logLevelSelector.ValueChanged += OnLogLevelSelectorOnValueChanged;
menuItems.Add (logMenu);
// add a separator
menuItems.Add (new Line ());
// Trace toggles
CheckBox lifecycleTraceCheckBox = new ()
{
Text = "_Lifecycle",
Value = Trace.EnabledCategories.HasFlag (TraceCategory.Lifecycle) ? CheckState.Checked : CheckState.UnChecked,
CanFocus = false
};
lifecycleTraceCheckBox.ValueChanging += (_, e) =>
{
if (e.NewValue == CheckState.Checked)
{
Trace.EnabledCategories |= TraceCategory.Lifecycle;
}
else
{
Trace.EnabledCategories &= ~TraceCategory.Lifecycle;
}
};
menuItems.Add (new MenuItem { CommandView = lifecycleTraceCheckBox, HelpText = "Toggle App & Driver lifecycle tracing", Key = Key.L.WithCtrl });
// ReSharper disable once StringLiteralTypo
CheckBox commandTraceCheckBox = new ()
{
Text = "C_ommand",
Value = Trace.EnabledCategories.HasFlag (TraceCategory.Command) ? CheckState.Checked : CheckState.UnChecked,
CanFocus = false
};
commandTraceCheckBox.ValueChanging += (_, e) =>
{
if (e.NewValue == CheckState.Checked)
{
Trace.EnabledCategories |= TraceCategory.Command;
}
else
{
Trace.EnabledCategories &= ~TraceCategory.Command;
}
};
menuItems.Add (new MenuItem { CommandView = commandTraceCheckBox, HelpText = "Toggle Command tracing", Key = Key.C.WithCtrl });
CheckBox mouseTraceCheckBox = new ()
{
Text = "_Mouse", Value = Trace.EnabledCategories.HasFlag (TraceCategory.Mouse) ? CheckState.Checked : CheckState.UnChecked, CanFocus = false
};
mouseTraceCheckBox.ValueChanging += (_, e) =>
{
if (e.NewValue == CheckState.Checked)
{
Trace.EnabledCategories |= TraceCategory.Mouse;
}
else
{
Trace.EnabledCategories &= ~TraceCategory.Mouse;
}
};
menuItems.Add (new MenuItem { CommandView = mouseTraceCheckBox, HelpText = "Toggle Mouse event tracing", Key = Key.U.WithCtrl });
CheckBox keyboardTraceCheckBox = new ()
{
Text = "_Keyboard",
Value = Trace.EnabledCategories.HasFlag (TraceCategory.Keyboard) ? CheckState.Checked : CheckState.UnChecked,
CanFocus = false
};
keyboardTraceCheckBox.ValueChanging += (_, e) =>
{
if (e.NewValue == CheckState.Checked)
{
Trace.EnabledCategories |= TraceCategory.Keyboard;
}
else
{
Trace.EnabledCategories &= ~TraceCategory.Keyboard;
}
};
menuItems.Add (new MenuItem { CommandView = keyboardTraceCheckBox, HelpText = "Toggle Keyboard event tracing", Key = Key.K.WithCtrl });
CheckBox navTraceCheckBox = new ()
{
Text = "_Navigation",
Value = Trace.EnabledCategories.HasFlag (TraceCategory.Navigation) ? CheckState.Checked : CheckState.UnChecked,
CanFocus = false
};
navTraceCheckBox.ValueChanging += (_, e) =>
{
if (e.NewValue == CheckState.Checked)
{
Trace.EnabledCategories |= TraceCategory.Navigation;
}
else
{
Trace.EnabledCategories &= ~TraceCategory.Navigation;
}
};
// TODO: Implement Trace.Navigation and enable this
menuItems.Add (new MenuItem
{
Enabled = false, CommandView = navTraceCheckBox, HelpText = "Toggle Focus & TabBehavior tracing", Key = Key.K.WithCtrl
});
CheckBox configTraceCheckBox = new ()
{
Text = "Con_figuration",
Value = Trace.EnabledCategories.HasFlag (TraceCategory.Configuration) ? CheckState.Checked : CheckState.UnChecked,
CanFocus = false
};
configTraceCheckBox.ValueChanging += (_, e) =>
{
if (e.NewValue == CheckState.Checked)
{
Trace.EnabledCategories |= TraceCategory.Configuration;
}
else
{
Trace.EnabledCategories &= ~TraceCategory.Configuration;
}
};
menuItems.Add (new MenuItem { CommandView = configTraceCheckBox, HelpText = "Toggle Configuration management tracing" });
CheckBox drawTraceCheckBox = new ()
{
Text = "_Draw", Value = Trace.EnabledCategories.HasFlag (TraceCategory.Draw) ? CheckState.Checked : CheckState.UnChecked, CanFocus = false
};
drawTraceCheckBox.ValueChanging += (_, e) =>
{
if (e.NewValue == CheckState.Checked)
{
Trace.EnabledCategories |= TraceCategory.Draw;
}
else
{
Trace.EnabledCategories &= ~TraceCategory.Draw;
}
};
menuItems.Add (new MenuItem { CommandView = drawTraceCheckBox, HelpText = "Toggle Draw operation tracing" });
// add a separator
menuItems.Add (new Line ());
menuItems.Add (new MenuItem ("_Open Log Folder", string.Empty, () => Link.OpenUrl (UICatalog.LOGFILE_LOCATION)));
return menuItems.ToArray ()!;
void OnLogLevelSelectorOnValueChanged (object? _, ValueChangedEventArgs<int?> args)
{
if (args.NewValue is { })
{
UICatalog.Options = UICatalog.Options with
{
DebugLogLevel = Enum.GetName (Enum.GetValues<LogLevel> () [args.NewValue.Value]) ?? string.Empty
};
}
UICatalog.LogLevelSwitch.MinimumLevel = UICatalog.LogLevelToLogEventLevel (Enum.Parse<LogLevel> (UICatalog.Options.DebugLogLevel));
}
}
}
private void UpdateThemesMenu ()
{
if (_themesSelector is null)
{
return;
}
string [] labels = ThemeManager.GetThemeNames ().ToArray ();
// Prevent resetting the selector if the themes have not changed
// BUGBUG: Just comparing the size of the arrays is not really sufficient. We should actually
// BUGBUG: deep compare the arrays.
if (_themesSelector.Labels is null || labels.Length != _themesSelector.Labels.Count)
{
_themesSelector.Value = null;
_themesSelector.AssignHotKeys = true;
_themesSelector.UsedHotKeys.Clear ();
_themesSelector.Labels = labels;
_themesSelector.Value = ThemeManager.GetThemeNames ().IndexOf (ThemeManager.GetCurrentThemeName ());
}
if (_topSchemesSelector is null)
{
return;
}
_topSchemesSelector.AssignHotKeys = true;
_topSchemesSelector.UsedHotKeys.Clear ();
int? selectedScheme = _topSchemesSelector.Value;
_topSchemesSelector.Labels = SchemeManager.GetSchemeNames ().ToArray ();
_topSchemesSelector.Value = selectedScheme;
if (CachedRunnableScheme is null || !SchemeManager.GetSchemeNames ().Contains (CachedRunnableScheme))
{
CachedRunnableScheme = SchemeManager.SchemesToSchemeName (Schemes.Base);
}
if (CachedRunnableScheme is null)
{
return;
}
int newSelectedItem = SchemeManager.GetSchemeNames ().IndexOf (CachedRunnableScheme);
// if the item is in bounds then select it
if (newSelectedItem >= 0 && newSelectedItem < SchemeManager.GetSchemeNames ().Count)
{
_topSchemesSelector.Value = newSelectedItem;
}
}
#endregion MenuBar
#region Scenario List
private TableView? _scenarioList;
private static int _cachedScenarioIndex;
public static ObservableCollection<Scenario>? CachedScenarios { get; set; }
private TableView CreateScenarioList ()
{
if (_categoryList is null)
{
throw new InvalidOperationException ("Category list must be created before scenario list");
}
if (_menuBar is null)
{
throw new InvalidOperationException ("Menu bar must be created before scenario list");
}
// Create the scenario list. The contents of the scenario list changes whenever the
// Category list selection changes (to show just the scenarios that belong to the selected
// category).
TableView scenarioList = new ()
{
X = Pos.Right (_categoryList) - 1,
Y = Pos.Bottom (_menuBar),
Width = Dim.Fill (),
Height = Dim.Height (_categoryList),
CanFocus = true,
Title = "_Scenarios",
BorderStyle = _categoryList?.BorderStyle ?? LineStyle.None,
SuperViewRendersLineCanvas = true
};
//scenarioList.Border.Settings = BorderSettings.Title | BorderSettings.Tab;
//scenarioList.Border.TabSide = Side.Top;
//scenarioList.Border.Thickness = new Thickness (1, 2, 1, 1);
// 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
scenarioList.FullRowSelect = true;
scenarioList.Style.ShowHeaders = false;
scenarioList.Style.ShowHorizontalHeaderOverline = false;
scenarioList.Style.ShowHorizontalHeaderUnderline = false;
scenarioList.Style.ShowHorizontalBottomLine = false;
scenarioList.Style.ShowVerticalCellLines = false;
scenarioList.Style.ShowVerticalHeaderLines = false;
/* By default, TableView lays out columns at render time and only
* measures y rows of data at a time. Where y is the height of the
* console. This is for the following reasons:
*
* - Performance, when tables have a large amount of data
* - Defensive, prevents a single wide cell value pushing other
* columns off-screen (requiring horizontal scrolling
*
* In the case of UICatalog here, such an approach is overkill so
* we just measure all the data ourselves and set the appropriate
* max widths as ColumnStyles
*/
int longestName = CachedScenarios?.Max (s => s.GetName ().Length) ?? 0;
scenarioList.Style.ColumnStyles.Add (0, new ColumnStyle { MaxWidth = longestName, MinWidth = longestName, MinAcceptableWidth = longestName });
scenarioList.Style.ColumnStyles.Add (1, new ColumnStyle { MaxWidth = 1 });
scenarioList.CellActivated += ScenarioView_OpenSelectedItem;
// TableView typically is a grid where nav keys are biased for moving left/right.
scenarioList.KeyBindings.Remove (Key.Home);
scenarioList.KeyBindings.Add (Key.Home, Command.Start);
scenarioList.KeyBindings.Remove (Key.End);
scenarioList.KeyBindings.Add (Key.End, Command.End);
// Ideally, TableView.MultiSelect = false would turn off any keybindings for
// multi-select options. But it currently does not. UI Catalog uses Ctrl-A for
// a shortcut to About.
scenarioList.MultiSelect = false;
scenarioList.KeyBindings.Remove (Key.A.WithCtrl);
return scenarioList;
}
/// <summary>Launches the selected scenario, setting the global _selectedScenario</summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ScenarioView_OpenSelectedItem (object? sender, EventArgs? e)
{
// Save selected item state
_cachedCategoryIndex = _categoryList?.SelectedItem;
if (_scenarioList is { })
{
_cachedScenarioIndex = _scenarioList.SelectedRow;
// Set the Result to the selected scenario name
Result = _scenarioList.Table? [_scenarioList.SelectedRow, 0];
}
Logging.Information ($"Scenario Selected; Stopping {GetType ().Name}: {Result}");
App?.RequestStop ();
}
#endregion Scenario List
#region Category List
private ListView? _categoryList;
private static int? _cachedCategoryIndex;
public static ObservableCollection<string>? CachedCategories { get; set; }
private ListView CreateCategoryList ()
{
if (_menuBar is null)
{
throw new InvalidOperationException ("Menu bar must be created before scenario list");
}
if (_statusBar is null)
{
throw new InvalidOperationException ("Status bar must be created before scenario list");
}
// Create the Category list view. This list never changes.
ListView categoryList = new ()
{
X = 0,
Y = Pos.Bottom (_menuBar),
Width = Dim.Auto (),
Height = Dim.Fill (_statusBar),
ShowMarks = false,
CanFocus = true,
Title = "_Categories",
BorderStyle = LineStyle.Rounded,
SuperViewRendersLineCanvas = true,
Source = new ListWrapper<string> (CachedCategories)
};
//categoryList.Border.Settings = BorderSettings.Title | BorderSettings.Tab;
//categoryList.Border.TabSide = Side.Top;
//categoryList.Border.Thickness = new Thickness (1, 2, 1, 1);
categoryList.Accepting += (_, e) =>
{
_scenarioList?.SetFocus ();
e.Handled = true;
};
categoryList.ValueChanged += CategoryView_SelectedChanged;
// This enables the scrollbar by causing lazy instantiation to happen
categoryList.ViewportSettings |= ViewportSettingsFlags.HasVerticalScrollBar;
return categoryList;
}
private void CategoryView_SelectedChanged (object? sender, ValueChangedEventArgs<int?> e)
{
if (e.NewValue is null || CachedCategories is null)
{
return;
}
string item = CachedCategories [e.NewValue.Value];
if (CachedScenarios is null)
{
return;
}
// First category is "All"
ObservableCollection<Scenario> newScenarioList = e.NewValue == 0
? CachedScenarios
: new ObservableCollection<Scenario> (CachedScenarios
.Where (s => s.GetCategories ().Contains (item))
.ToList ());
_scenarioList?.Table = new EnumerableTableSource<Scenario> (newScenarioList,
new Dictionary<string, Func<Scenario, object>>
{
{ "Name", s => s.GetName () }, { "Description", s => s.GetDescription () }
});
}
#endregion Category List
#region StatusBar
private StatusBar? _statusBar;
[ConfigurationProperty (Scope = typeof (AppSettingsScope), OmitClassName = true)]
[JsonPropertyName ("UICatalog.StatusBar")]
public static bool ShowStatusBar
{
get;
set
{
if (field == value)
{
return;
}
field = value;
StatusBarChanged?.Invoke (null, new ValueChangedEventArgs<bool> (!field, field));
}
} = true;
/// <summary>Raised when "UICatalog.StatusBar" changes.</summary>
public static event EventHandler<ValueChangedEventArgs<bool>>? StatusBarChanged;
private Shortcut? _shQuit;
private Shortcut? _shVersion;
private CheckBox? _force16ColorsShortcutCb;
/// <summary>
/// Returns the first F-key (F1–F12) that is not already bound in
/// <see cref="Application.KeyBindings"/>, used as the activation key for
/// <see cref="MenuBar.DefaultKey"/> or <see cref="PopoverMenu.DefaultKey"/>,
/// or assigned to a <see cref="MenuItem.Key"/> on a menu item. Falls back to
/// <see cref="Key.F12"/> if all are taken.
/// </summary>
/// <param name="ignoreKeys"></param>
private Key GetFirstUnboundFKey (HashSet<Key> ignoreKeys)
{
Key [] fKeys =
[
Key.F1,
Key.F2,
Key.F3,
Key.F4,
Key.F5,
Key.F6,
Key.F7,
Key.F8,
Key.F9,
Key.F10,
Key.F11,
Key.F12
];
// Collect keys already bound at the Application level
HashSet<Key> boundKeys = ignoreKeys;
foreach (Key fKey in fKeys)
{
if (App?.Keyboard.KeyBindings.TryGet (fKey, out _) is true)
{
boundKeys.Add (fKey);
}
}
// Also exclude the MenuBar and PopoverMenu activation keys
boundKeys.Add (MenuBar.DefaultKey);
boundKeys.Add (PopoverMenu.DefaultKey);
// Exclude keys used by MenuBar menu items
if (_menuBar is { })
{
foreach (MenuItem menuItem in _menuBar.GetMenuItemsWith (mi => mi.Key.IsValid))
{
boundKeys.Add (menuItem.Key);
}
}
// Exclude keys used by StatusBar items
if (_statusBar is { })
{
foreach (View view in _statusBar.SubViews)
{
var shortcut = (Shortcut)view;
boundKeys.Add (shortcut.Key);
}
}
foreach (Key fKey in fKeys)
{
if (!boundKeys.Contains (fKey))
{
return fKey;
}
}
return Key.F12;
}
private StatusBar CreateStatusBar ()
{
StatusBar statusBar = new () { AlignmentModes = AlignmentModes.IgnoreFirstOrLast, CanFocus = false };
// This demonstrates a shortcut that invokes RequestStop to quit the app
_shQuit = new Shortcut { CanFocus = false, Title = "Quit", Key = Application.GetDefaultKey (Command.Quit), Action = RequestStop };
_shVersion = new Shortcut { Title = "Version Info", CanFocus = false };
Shortcut statusBarShortcut = new ()
{
Key = GetFirstUnboundFKey ([]), Title = "Show/Hide Status Bar", CanFocus = false, Action = () => ShowStatusBar = !ShowStatusBar
};
_force16ColorsShortcutCb = new CheckBox
{
Title = "16 color mode", Value = Driver.Force16Colors ? CheckState.Checked : CheckState.UnChecked, CanFocus = true
};
Shortcut force16ColorsShortcut = new ()
{
CanFocus = false,
CommandView = _force16ColorsShortcutCb,
HelpText = "",
BindKeyToApplication = true,
Key = GetFirstUnboundFKey ([statusBarShortcut.Key]),
Action = () =>
{
Driver.Force16Colors = !Driver.Force16Colors;
_force16ColorsMenuItemCb?.Value = Driver.Force16Colors ? CheckState.Checked : CheckState.UnChecked;
SetNeedsDraw ();
}
};
statusBar.Add (_shQuit, statusBarShortcut, force16ColorsShortcut, _shVersion);
if (UICatalog.Options.DontEnableConfigurationManagement)
{
statusBar.AddShortcutAt (statusBar.SubViews.ToList ().IndexOf (_shVersion), new Shortcut { Title = "CM is Disabled" });
}
StatusBarChanged += (_, args) =>
{
switch (args.NewValue)
{
case true:
_statusBar?.Height = Dim.Auto ();
break;
case false:
_statusBar?.Height = 0;
break;
}
};
return statusBar;
}
#endregion StatusBar
#region Configuration Manager
/// <summary>
/// Called when CM has applied changes.
/// </summary>
private void ConfigApplied ()
{
UpdateThemesMenu ();
SchemeName = CachedRunnableScheme;
_shQuit?.Key = Application.GetDefaultKey (Command.Quit);
_disableMouseCb?.Value = App?.Mouse.IsMouseDisabled == true ? CheckState.Checked : CheckState.UnChecked;
_force16ColorsShortcutCb?.Value = Driver.Force16Colors ? CheckState.Checked : CheckState.UnChecked;
App?.TopRunnableView?.SetNeedsDraw ();
}
private void ConfigAppliedHandler (object? sender, ConfigurationManagerEventArgs? a) => ConfigApplied ();
#endregion Configuration Manager
/// <summary>
/// The URL displayed in the About Box.
/// </summary>
public const string ABOUT_URL = "https://github.com/gui-cs/Terminal.Gui";
private void ShowAboutDialog ()
{
Dialog dialog = new () { Title = "", Buttons = [new Button { Title = Strings.btnOk, IsDefault = true }] };
Label tagline = new ()
{
Text = "UI Catalog: A comprehensive sample library and test app for",
TextAlignment = Alignment.Center,
X = Pos.Center (),
Width = Dim.Auto (DimAutoStyle.Text),
Height = Dim.Auto (DimAutoStyle.Text)
};
GradientArtView asciiArt = new () { X = Pos.Center (), Y = Pos.Bottom (tagline) + 1 };
Link link = new () { Text = ABOUT_URL, Url = ABOUT_URL, X = Pos.Center (), Y = Pos.Bottom (asciiArt) + 1 };
App?.ToolTips?.SetToolTip (link, () => link.Url);
dialog.Add (tagline, asciiArt, link);
dialog.Buttons.ElementAt (0).SetFocus ();
App?.Run (dialog);
dialog.Dispose ();
}
/// <summary>
/// Renders the Terminal.Gui logo in box-drawing characters with a diagonal gradient.
/// </summary>
private sealed class GradientArtView : View
{
// @formatter:off
private const string ART = """
╺┳╸┏━╸┏━┓┏┳┓╻┏┓╻┏━┓╻ ┏━╸╻ ╻╻
┃ ┣╸ ┣┳┛┃┃┃┃┃┗┫┣━┫┃ ┃╺┓┃ ┃┃
╹ ┗━╸╹┗╸╹ ╹╹╹ ╹╹ ╹┗━╸╹┗━┛┗━┛╹
v2 - Beta
""";
// @formatter:on
private static readonly string [] _artLines = ART.ReplaceLineEndings ("\n").Split ('\n');
public GradientArtView ()
{
int artWidth = _artLines.Select (line => line.Length).Prepend (0).Max ();
Width = artWidth;
Height = _artLines.Length;
}
/// <inheritdoc/>
protected override bool OnDrawingContent (DrawContext? context)
{
List<Color> stops =
[
new (0, 128, 255), // Bright Blue
new (0, 255, 128), // Bright Green
new (255, 255), // Bright Yellow
new (255, 128) // Bright Orange
];
List<int> steps = [10];
Gradient gradient = new (stops, steps);
var artHeight = 3; // Only the box-drawing lines get the gradient
int artWidth = _artLines [0].Length;
Dictionary<Point, Color> colorMap = gradient.BuildCoordinateColorMapping (artHeight, artWidth, GradientDirection.Diagonal);
Attribute normalAttr = GetAttributeForRole (VisualRole.Normal);
for (var row = 0; row < _artLines.Length; row++)
{
string line = _artLines [row];
for (var col = 0; col < line.Length; col++)
{
char ch = line [col];
if (ch == ' ')
{
continue;
}
// Gradient only on the 3 art lines; version text uses normal color
if (row < 3)
{
Point coord = new (col, row);
if (colorMap.TryGetValue (coord, out Color color))
{
SetAttribute (new Attribute (color, normalAttr.Background));
}
else
{
SetAttribute (normalAttr);
}
}
else
{
SetAttribute (normalAttr);
}
Move (col, row);
AddStr (ch.ToString ());
}
}
return true;
}
}
/// <summary>
/// Shows a dialog displaying error logs from a scenario run.
/// </summary>
/// <param name="app"></param>
/// <param name="scenarioName">The name of the scenario that was run.</param>
/// <param name="logs">The captured log output.</param>
private static void ShowScenarioErrorsDialog (IApplication app, string scenarioName, string logs)
{
using Dialog dialog = new ();
dialog.Title = $"Errors in {scenarioName}";