Files
Terminal.Gui/UICatalog/UICatalog.cs
Tig 4430fe2cc6 Fixes #3192. Improve correctness / clarity of existing View.AutoSize functionality/unit tests (#3202)
* Removed resharper settings from editorconfig

* Remove constructors with frame parameters from Button class.

* Remove constructors with frame parameters from CheckBox class.

* Cleanup code.

* Remove constructors with frame parameters from ComboBox class.

* @BDisp
Remove constructors with frame parameters from FrameView class.

* Remove constructors with frame parameters from Label class.

* Remove constructors with frame parameters from ListView class.

* Remove constructors with frame parameters from ScrollBarView class.

* Remove constructors with frame parameters from ScrollView class.

* Remove namespace braces.

* Cleanup code.

* Cleanup code.

* Cleanup code.

* Remove constructors with frame parameters from TextField class.

* Remove constructors with frame parameters from TimeField class.

* Fixes #3182. OnResizeNeeded returns int.MaxValue and int.MaxValue when Application.Top is null, should return Size.Empty.

* Remove constructors with frame parameters from Toplevel class.

* Remove constructors with frame parameters from Window class.

* Fix merge errors.

* Revert "Fixes #3182. OnResizeNeeded returns int.MaxValue and int.MaxValue when Application.Top is null, should return Size.Empty."

This reverts commit cf9c24b846.

* Revert unit test.

* Fixes #2882. TabView: 'Frame.DrawFrame(Rect, bool)' is obsolete: 'This method is obsolete in v2. Use use LineCanvas or Frame (#2980)

* Fixes #2882. TabView: 'Frame.DrawFrame(Rect, bool)' is obsolete: 'This method is obsolete in v2. Use use LineCanvas or Frame

* Trying fix this unit test that sometimes fail.

* Fixes #2983. View need a alternative DrawFrame for the v2.

* Use new DrawFrame method.

* Change _lines field to Lines property.

* Add TabWindow unit test.

* Add DrawIncompleteFrame method and unit tests.

* Add more unit tests to LineCanvas.

* Fix newline conflict errors.

* Revert "Change _lines field to Lines property."

This reverts commit ab6c5f3094.

* Add DrawIncompleteFrame method and unit tests.

* Add more unit tests to LineCanvas.

* Fix newline conflict errors.

* Force render immediately instead of join.

* I will never rely on zero-location-based unit test again.

* Fix TestTreeViewColor unit test fail.

* Using location of 3 to avoid be divisible by 2 and so avoiding bugs.

* Revert "Using location of 3 to avoid be divisible by 2 and so avoiding bugs."

This reverts commit dd3df135d8.

* Revert "I will never rely on zero-location-based unit test again."

This reverts commit 62adf6f285.

* Revert "Fix newline conflict errors."

This reverts commit 4acf72612d.

* Revert "Add more unit tests to LineCanvas."

This reverts commit 66bc6f514e.

* Revert "Add DrawIncompleteFrame method and unit tests."

This reverts commit 680ba264e1.

* Resolving merge conflicts.

* Revert "Use new DrawFrame method."

This reverts commit 69a7f17f19.

* Revert "Fixes #2983. View need a alternative DrawFrame for the v2."

This reverts commit dade9fd767.

* Reverting this changes to start a new one.

* Add horizontal and vertical support for combining glyphs.

* Fix text and auto size behavior.

* Add TabWidth property.

* Add unit test for WordWrap.

* Fixes #3017. View TextDirection returns incorrect size on a vertical direction instance with AutoSize as false.

* Using Frame to force read from the get method.

* Fix some issues with AutoSize and ForceValidatePosDim.

* Fixing broken unit tests.

* Restoring code I've broken.

* Removing forgotten code.

* Only LayoutStyle.Computed can change the Frame.

* DateField and TimeField depends on LayoutStyle.Computed.

* Fix unit tests related with LayoutStyle.

* Implements tabs, left and right arrows as View.

* Draws a minimum full border.

* Adds missing XML parameter.

* Adds assert tests for Frame.

* Removes duplicates InlineData.

* Adds more unit tests for minimum full border without Left and Right thickness.

* Trying to fix the TestTreeViewColor unit test fail.

* Prevents a user to set TextDirection to -1.

* Prevents any invalid TextDirection value.

* Removes (TextDirection)(-1).

* Removes unnecessary TextDirection initialization.

* Removes LayoutStyle.

* Fixing unit tests with border.

* Trying to fix TestTreeViewColor again.

* Revert "Trying to fix TestTreeViewColor again."

This reverts commit c2efa8e42e.

* Trying to fix TestTreeViewColor again.

* Fix merge errors.

* Fix merge errors.

* Restoring unit test.

* Restores the right XML comment.

* Fix Disposing unit tests that sometimes throws because some instances aren't cleared on others unit tests classes.

* Fix Disposing unit tests that sometimes throws because some instances aren't cleared on others unit tests classes.

* Only call OnResizeNeeded if it's LayoutStyle.Computed.

* Fix merge errors.

* Fix merge errors.

* Fix unit tests fail.

* Reformat.

* Again.

* Rename to OnDrawAdornments.

* Fix failing unit tests.

* Reduces indentation and cleanup code.

* Cleanup code.

* Fix bug done when cleanup.

* Replace FrameHandledMouseEvent to AdornmentHandledMouseEvent.

* Removes Tab constructor parameters.

---------

Co-authored-by: Tig <tig@users.noreply.github.com>

* Fix merge errors.

* Remove constructors with parameters from Button.

* Remove parenthesis on objects initializers from Button.

* Remove constructors with parameters from CheckBox.

* Remove parenthesis on objects initializers from CheckBox.

* Remove constructors with parameters from ComboBox.

* Remove constructors with parameters from FrameView.

* Remove parenthesis on objects initializers from FrameView.

* Initial commit

* Renamed Direction enum for clarity in refactoring unit tests

* Moved nav tests to NavigationTests

* Moved view tests around

* Cleaning up TextFormatter and View.AutoSize code

* Fixed latent TextFormatter bug with \n

* removed Application dependency on some autosize unit tests

* Fixed Label tests to deal with auotsize overriding height/width

* Fixed more label tests. WIP

* Fixed all places where AutoSize = happend after setting Dims

* Started adding new primitive View.Text tests

* Code comments

* WIP: Enforce that it makes no sense to set Width/Height if AutoSize = true. Update Unit tests to match.

* WIP: Enforce that it makes no sense to set Width/Height if AutoSize = true. Update Unit tests to match.

* Remove frame set from the View constructor and prevent SetRelativeLayout running if not yet initialized.

* Changes needed for unit tests pass on remove parameters constructors from the Label class.

* Remove constructors with parameters from Label.

* Remove parenthesis on objects initializers from Label.

* Prefix private fields with underscore.

* Renamed to MaxLength.

* Remove constructors with parameters from ListView.

* MakeWrapper not needed anymore.

* Remove parenthesis on objects initializers from ListView.

* WIP: Enforce that it makes no sense to set Width/Height if AutoSize = true. Update Unit tests to match.

* Massive code cleanup - use parameterless constructors and ensure AutoSize is set properly. Code reformat.

* Massive code cleanup - use parameterless constructors and ensure AutoSize is set properly. Code reformat.

* Fixed messagebox

* Remove constructors with parameters from ScrollBarView and ScrollView.

* Remove parenthesis on objects initializers from ScrollBarView and ScrollView.

* Cleanup code.

* Fix merge errors.

* Add empty dotsettings for solution and projects.

* Set ReSharper language analysis level for projects to  C#12

* Make ReSharper consider itself the boss for style

* Add rule to enforce property backing fields above the property

* Disable auto-detection of naming rules so ReSharper doesn't change them by itself

* Don't let someone's VS settings override the indent settings

* Explicitly set tab width to 4 spaces and force spaces.

* Rules to keep various multi-line constructs aligned within themselves

* Curly brace rules (Using K&R style, per current project spec)

* Blank line rules

Mostly to add breaks in various situations, and also to enforce max of 1 blank line.

* Increase auto-wrap to 160 from default of 120

* Line break at end of all files, to make Unixy systems happy

* Keep attributes on their own lines except for methods and records that are themselves single-line

* Increase attribute auto-wrap to 60 from default of 38

* Wrap/chop rules for long method signatures and record declarations

Chop if either already multi-line or if over 8 parameters.
Chop AFTER the left paren and BEFORE the first parameter.

* Chop rules for generics

For generics with multi-line type parameters or multiple type parameter constraints, chop in a way that has consistent alignment.

* Always enforce enum members on their own lines

* One-line functions completely on one line

They're usually expression-bodied anyway, here, so this is almost irrelevant

* Keep control flow statements on their own lines

* Follow same chop rules for method invocation as method declaration

* Chop long or multi-line method chains or patterns

* Wrap rules for binary operators

Operator at beginning of new lines
Auto-chop if long or already multi-line

* Spaces between keywords and their opening parentheses

* Add file layout rules for organization of reorderable items like fields, properties, etc.

Ugly XML, so load it up in the UI to look at it
It's MOSTLY the ReSharper defaults, but with more aggressive sorting, generally by access modifier and name, within each grouping.

* Deconstructors use per-member types

* Use keywords for built-in types and increase severity of inspection for violations

Also apply to IntPtr and similar, which should now be nint and similar

* Apply syntax style on completion.

* Use var when evident for built-in and simple types, but not elsewhere

* Increase severity for some minor redundancy and clarity inspections

* Enforce braces always required for blocks, and treat as error

* Warn if a local function is not statement-bodied

* Increase various inspection severities

IF Condition => Severity:
Attributes not wrapped property => Suggestion
Constructors expression-bodied => Error
default doesn't have type when it isn't clear => suggestion
Namespaces not file-scoped => error
Methods not statement-bodied => hint
Null check pattern not the object property pattern => Error

* Adjust preference order of null check patterns to make object pattern highest

* XmlDoc rules to keep tags and contents aligned and wrapped

* Add a few custom profiles for code cleanup and make the full profile default

* Remove parts for languages not used in this solution

* copied in v2_develop changes

* Merged v2_develop

* Added Begin/Init unit tests. Removed Application dependencey from AutoSizeFalse tests

* TextFormatter.Lines -> GetLines ()

* Let ReSharper know we intend to localize things

* TextFormatter code cleanup

* copied in v2_develop changes

* Merged v2_develop

* Spaces aren't wanted here either.

* Fix merge errors.

* Fixes ContentBottomRightCorner related with https://github.com/gui-cs/Terminal.Gui/issues/3211#issue-2098878820

* Remove constructors with parameters from ContextMenu.

* Remove commented code.

* Remove constructors with parameters from OpenDialog.

* Remove constructors with parameters from SaveDialog.

* Remove constructors with parameters from TextField.

* Remove constructors with parameters from TimeField.

* Fix unit test.

* Remove unnecessary SetInitialProperties method.

* Remove unnecessary SetInitialProperties method.

* Remove parenthesis on objects initializers from Toplevel and Window.

* Remove constructors with parameters from RadioGroup.

* Remove constructors with parameters from TextView.

* Remove constructors with parameters from MenuBar.

* TEMPORARY: Turn everything that was set to error down to warning or lower

* Fixes #3219. MenuBar is opened by call OpenMenu even it's disabled.

* Remove constructors with parameters from Menu.

* Remove constructors with parameters from View.

* Change constructor to internal because is mainly useful for testing.

* ReSharper Cleanup Code.

* Added format only r# config

* Fixes #3224. TextFormatter.Lines should return a single string.Empty list even with Width or Height equal to zero.

* Remove constructors with parameters from Dialog.

* Remove constructors with parameters from TextValidateField.

* Fixes https://github.com/gui-cs/Terminal.Gui/issues/3224#issuecomment-1924096038

* Fixes #3225. Press CursorDown on TabView doesn't move to the next view.

* Fixes #3229. TextFormatter should have a FillRemaining property.

* Testing formatting merge in bdisp

* Testing formatting merge

* Testing formatting merge bdisp

* Testing formatting merge 2

* xmldoc format

* R# Full Code Cleanup

* R# Full Code Cleanup2

* R# Full Code Cleanup2

* Merged! But broke tests

* Refixing...

* Refixed DrawTests

* Refixed ViewTests

* Refixed Text Tests

* Refixed more unit tests

* Refixed scenarios

* Refixed rest of scenarios

* Refixed ViewsTests

* Refixed rest of tests. All unit tests pass again!

* Fixed warnings

* Updated R# version. Added new code cleanup settings

* Applied latest code cleanup to solution

* Another code cleanup pass

* Tweaked r# settings. .editorconfig now matches.

* r# else on separate line

* r# - update

* r# - full solution

* test commit

* test commit

* test commit

* Removed extra profiles

* Full cleanup following cleaning up profiles

* Null checking pattern rules/inspections

* Tabs and extra whitespace are evil

* Attributes on their own lines

* Code layout rules to put fields first and to put backing fields with their properties

* Merged v2_develop

* Full cleanup following dodexahedron's PR

---------

Co-authored-by: BDisp <bd.bdisp@gmail.com>
Co-authored-by: Brandon Thetford <github@snapsinazfs.com>
2024-02-11 15:54:03 -07:00

1078 lines
44 KiB
C#

global using Attribute = Terminal.Gui.Attribute;
global using CM = Terminal.Gui.ConfigurationManager;
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Serialization;
using Terminal.Gui;
using static Terminal.Gui.ConfigurationManager;
using Command = Terminal.Gui.Command;
using RuntimeEnvironment = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment;
#nullable enable
namespace UICatalog;
/// <summary>
/// UI Catalog is a comprehensive sample library for Terminal.Gui. It provides a simple UI for adding to the
/// catalog of scenarios.
/// </summary>
/// <remarks>
/// <para>UI Catalog attempts to satisfy the following goals:</para>
/// <para>
/// <list type="number">
/// <item>
/// <description>Be an easy to use showcase for Terminal.Gui concepts and features.</description>
/// </item>
/// <item>
/// <description>Provide sample code that illustrates how to properly implement said concepts & features.</description>
/// </item>
/// <item>
/// <description>Make it easy for contributors to add additional samples in a structured way.</description>
/// </item>
/// </list>
/// </para>
/// <para>
/// See the project README for more details
/// (https://github.com/gui-cs/Terminal.Gui/tree/master/UICatalog/README.md).
/// </para>
/// </remarks>
internal class UICatalogApp
{
private static StringBuilder? _aboutMessage;
private static int _cachedCategoryIndex;
// When a scenario is run, the main app is killed. These items
// are therefore cached so that when the scenario exits the
// main app UI can be restored to previous state
private static int _cachedScenarioIndex;
private static string? _cachedTheme = string.Empty;
private static List<string>? _categories;
private static readonly FileSystemWatcher _currentDirWatcher = new ();
private static ConsoleDriver.DiagnosticFlags _diagnosticFlags;
private static string _forceDriver = string.Empty;
private static readonly FileSystemWatcher _homeDirWatcher = new ();
private static bool _isFirstRunning = true;
private static Options _options;
private static List<Scenario>? _scenarios;
// If set, holds the scenario the user selected
private static Scenario? _selectedScenario;
private static MenuBarItem? _themeMenuBarItem;
private static MenuItem []? _themeMenuItems;
private static string _topLevelColorScheme = string.Empty;
[SerializableConfigurationProperty (Scope = typeof (AppScope), OmitClassName = true)]
[JsonPropertyName ("UICatalog.StatusBar")]
public static bool ShowStatusBar { get; set; } = true;
private static void ConfigFileChanged (object sender, FileSystemEventArgs e)
{
if (Application.Top == null)
{
return;
}
// TODO: This is a hack. Figure out how to ensure that the file is fully written before reading it.
//Thread.Sleep (500);
Load ();
Apply ();
}
private static int Main (string [] args)
{
Console.OutputEncoding = Encoding.Default;
if (Debugger.IsAttached)
{
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US");
}
_scenarios = Scenario.GetScenarios ();
_categories = Scenario.GetAllCategories ();
// Process command line args
// "UICatalog [-driver <driver>] [scenario name]"
// If no driver is provided, the default driver is used.
Option<string> driverOption = new Option<string> ("--driver", "The ConsoleDriver to use.").FromAmong (
Application.GetDriverTypes ()
.Select (d => d.Name)
.ToArray ()
);
driverOption.AddAlias ("-d");
driverOption.AddAlias ("--d");
Argument<string> scenarioArgument = new Argument<string> (
"scenario",
description: "The name of the scenario to run.",
getDefaultValue: () => "none"
).FromAmong (
_scenarios.Select (s => s.GetName ())
.Append ("none")
.ToArray ()
);
var rootCommand =
new RootCommand ("A comprehensive sample library for Terminal.Gui") { scenarioArgument, driverOption };
rootCommand.SetHandler (
context =>
{
var options = new Options
{
Driver = context.ParseResult.GetValueForOption (driverOption),
Scenario = context.ParseResult.GetValueForArgument (scenarioArgument)
/* etc. */
};
// See https://github.com/dotnet/command-line-api/issues/796 for the rationale behind this hackery
_options = options;
}
);
rootCommand.Invoke (args);
UICatalogMain (_options);
return 0;
}
private static void OpenUrl (string url)
{
if (RuntimeInformation.IsOSPlatform (OSPlatform.Windows))
{
url = url.Replace ("&", "^&");
Process.Start (new ProcessStartInfo ("cmd", $"/c start {url}") { CreateNoWindow = true });
}
else if (RuntimeInformation.IsOSPlatform (OSPlatform.Linux))
{
using var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "xdg-open",
Arguments = url,
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true,
UseShellExecute = false
}
};
process.Start ();
}
else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
{
Process.Start ("open", url);
}
}
/// <summary>
/// Shows the UI Catalog selection UI. When the user selects a Scenario to run, the UI Catalog main app UI is
/// killed and the Scenario is run as though it were Application.Top. When the Scenario exits, this function exits.
/// </summary>
/// <returns></returns>
private static Scenario RunUICatalogTopLevel ()
{
// Run UI Catalog UI. When it exits, if _selectedScenario is != null then
// a Scenario was selected. Otherwise, the user wants to quit UI Catalog.
// If the user specified a driver on the command line then use it,
// ignoring Config files.
Application.Init (driverName: _forceDriver);
if (_cachedTheme is null)
{
_cachedTheme = Themes?.Theme;
}
else
{
Themes!.Theme = _cachedTheme;
Apply ();
}
Application.Run<UICatalogTopLevel> ();
Application.Shutdown ();
return _selectedScenario!;
}
private static void StartConfigFileWatcher ()
{
// Setup a file system watcher for `./.tui/`
_currentDirWatcher.NotifyFilter = NotifyFilters.LastWrite;
string assemblyLocation = Assembly.GetExecutingAssembly ().Location;
string tuiDir;
if (!string.IsNullOrEmpty (assemblyLocation))
{
var assemblyFile = new FileInfo (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";
// Setup a file system watcher for `~/.tui/`
_homeDirWatcher.NotifyFilter = NotifyFilters.LastWrite;
var f = new FileInfo (Environment.GetFolderPath (Environment.SpecialFolder.UserProfile));
tuiDir = Path.Combine (f.FullName, ".tui");
if (!Directory.Exists (tuiDir))
{
Directory.CreateDirectory (tuiDir);
}
_homeDirWatcher.Path = tuiDir;
_homeDirWatcher.Filter = "*config.json";
_currentDirWatcher.Changed += ConfigFileChanged;
//_currentDirWatcher.Created += ConfigFileChanged;
_currentDirWatcher.EnableRaisingEvents = true;
_homeDirWatcher.Changed += ConfigFileChanged;
//_homeDirWatcher.Created += ConfigFileChanged;
_homeDirWatcher.EnableRaisingEvents = true;
}
private static void StopConfigFileWatcher ()
{
_currentDirWatcher.EnableRaisingEvents = false;
_currentDirWatcher.Changed -= ConfigFileChanged;
_currentDirWatcher.Created -= ConfigFileChanged;
_homeDirWatcher.EnableRaisingEvents = false;
_homeDirWatcher.Changed -= ConfigFileChanged;
_homeDirWatcher.Created -= ConfigFileChanged;
}
private static void UICatalogMain (Options options)
{
StartConfigFileWatcher ();
// By setting _forceDriver we ensure that if the user has specified a driver on the command line, it will be used
// regardless of what's in a config file.
Application.ForceDriver = _forceDriver = options.Driver;
// If a Scenario name has been provided on the commandline
// run it and exit when done.
if (options.Scenario != "none")
{
_topLevelColorScheme = "Base";
int item = _scenarios!.FindIndex (
s =>
s.GetName ()
.Equals (options.Scenario, StringComparison.OrdinalIgnoreCase)
);
_selectedScenario = (Scenario)Activator.CreateInstance (_scenarios [item].GetType ())!;
Application.Init (driverName: _forceDriver);
_selectedScenario.Theme = _cachedTheme;
_selectedScenario.TopLevelColorScheme = _topLevelColorScheme;
_selectedScenario.Init ();
_selectedScenario.Setup ();
_selectedScenario.Run ();
_selectedScenario.Dispose ();
_selectedScenario = null;
Application.Shutdown ();
VerifyObjectsWereDisposed ();
return;
}
_aboutMessage = new StringBuilder ();
_aboutMessage.AppendLine (@"A comprehensive sample library for");
_aboutMessage.AppendLine (@"");
_aboutMessage.AppendLine (@" _______ _ _ _____ _ ");
_aboutMessage.AppendLine (@" |__ __| (_) | | / ____| (_) ");
_aboutMessage.AppendLine (@" | | ___ _ __ _ __ ___ _ _ __ __ _| || | __ _ _ _ ");
_aboutMessage.AppendLine (@" | |/ _ \ '__| '_ ` _ \| | '_ \ / _` | || | |_ | | | | | ");
_aboutMessage.AppendLine (@" | | __/ | | | | | | | | | | | (_| | || |__| | |_| | | ");
_aboutMessage.AppendLine (@" |_|\___|_| |_| |_| |_|_|_| |_|\__,_|_(_)_____|\__,_|_| ");
_aboutMessage.AppendLine (@"");
_aboutMessage.AppendLine (@"v2 - Work in Progress");
_aboutMessage.AppendLine (@"");
_aboutMessage.AppendLine (@"https://github.com/gui-cs/Terminal.Gui");
while (RunUICatalogTopLevel () is { } scenario)
{
VerifyObjectsWereDisposed ();
Themes!.Theme = _cachedTheme!;
Apply ();
scenario.Theme = _cachedTheme;
scenario.TopLevelColorScheme = _topLevelColorScheme;
scenario.Init ();
scenario.Setup ();
scenario.Run ();
scenario.Dispose ();
// This call to Application.Shutdown brackets the Application.Init call
// made by Scenario.Init() above
Application.Shutdown ();
VerifyObjectsWereDisposed ();
}
StopConfigFileWatcher ();
VerifyObjectsWereDisposed ();
}
private static void VerifyObjectsWereDisposed ()
{
#if DEBUG_IDISPOSABLE
// Validate there are no outstanding Responder-based instances
// after a scenario was selected to run. This proves the main UI Catalog
// 'app' closed cleanly.
foreach (Responder? inst in Responder.Instances)
{
Debug.Assert (inst.WasDisposed);
}
Responder.Instances.Clear ();
// Validate there are no outstanding Application.RunState-based instances
// after a scenario was selected to run. This proves the main UI Catalog
// 'app' closed cleanly.
foreach (RunState? inst in RunState.Instances)
{
Debug.Assert (inst.WasDisposed);
}
RunState.Instances.Clear ();
#endif
}
/// <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 class UICatalogTopLevel : Toplevel
{
public ListView CategoryList;
public StatusItem DriverName;
public MenuItem? miForce16Colors;
public MenuItem? miIsMenuBorderDisabled;
public MenuItem? miIsMouseDisabled;
public MenuItem? miUseSubMenusSingleFrame;
public StatusItem OS;
// UI Catalog uses TableView for the scenario list instead of a ListView to demonstate how
// TableView works. There's no real reason not to use ListView. Because we use TableView, and TableView
// doesn't (currently) have CollectionNavigator support built in, we implement it here, within the app.
public TableView ScenarioList;
private readonly CollectionNavigator _scenarioCollectionNav = new ();
public UICatalogTopLevel ()
{
_themeMenuItems = CreateThemeMenuItems ();
_themeMenuBarItem = new MenuBarItem ("_Themes", _themeMenuItems);
MenuBar = new MenuBar
{
Menus =
[
new MenuBarItem (
"_File",
new MenuItem []
{
new (
"_Quit",
"Quit UI Catalog",
RequestStop
)
}
),
_themeMenuBarItem,
new MenuBarItem ("Diag_nostics", CreateDiagnosticMenuItems ()),
new MenuBarItem (
"_Help",
new MenuItem []
{
new (
"_Documentation",
"",
() => OpenUrl ("https://gui-cs.github.io/Terminal.GuiV2Docs"),
null,
null,
(KeyCode)Key.F1
),
new (
"_README",
"",
() => OpenUrl ("https://github.com/gui-cs/Terminal.Gui"),
null,
null,
(KeyCode)Key.F2
),
new (
"_About...",
"About UI Catalog",
() => MessageBox.Query (
"About UI Catalog",
_aboutMessage!.ToString (),
0,
false,
"_Ok"
),
null,
null,
(KeyCode)Key.A.WithCtrl
)
}
)
]
};
DriverName = new StatusItem (Key.Empty, "Driver:", null);
OS = new StatusItem (Key.Empty, "OS:", null);
StatusBar = new StatusBar { Visible = ShowStatusBar };
StatusBar.Items = new []
{
new (
Application.QuitKey,
$"~{Application.QuitKey} to quit",
() =>
{
if (_selectedScenario is null)
{
// This causes GetScenarioToRun to return null
_selectedScenario = null;
RequestStop ();
}
else
{
_selectedScenario.RequestStop ();
}
}
),
new (
Key.F10,
"~F10~ Status Bar",
() =>
{
StatusBar.Visible = !StatusBar.Visible;
//ContentPane!.Height = Dim.Fill(StatusBar.Visible ? 1 : 0);
LayoutSubviews ();
SetSubViewNeedsDisplay ();
}
),
DriverName,
OS
};
// Create the Category list view. This list never changes.
CategoryList = new ListView
{
X = 0,
Y = 1,
Width = Dim.Percent (30),
Height = Dim.Fill (1),
AllowsMarking = false,
CanFocus = true,
Title = "Categories",
BorderStyle = LineStyle.Single,
SuperViewRendersLineCanvas = true,
Source = new ListWrapper (_categories)
};
CategoryList.OpenSelectedItem += (s, a) => { ScenarioList!.SetFocus (); };
CategoryList.SelectedItemChanged += CategoryView_SelectedChanged;
// 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).
ScenarioList = new TableView
{
X = Pos.Right (CategoryList) - 1,
Y = 1,
Width = Dim.Fill (),
Height = Dim.Fill (1),
//AllowsMarking = false,
CanFocus = true,
Title = "Scenarios",
BorderStyle = LineStyle.Single,
SuperViewRendersLineCanvas = true
};
// 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 = _scenarios!.Max (s => s.GetName ().Length);
ScenarioList.Style.ColumnStyles.Add (
0,
new ColumnStyle { MaxWidth = longestName, MinWidth = longestName, MinAcceptableWidth = longestName }
);
ScenarioList.Style.ColumnStyles.Add (1, new ColumnStyle { MaxWidth = 1 });
// Enable user to find & select a scenario by typing text
// TableView does not (currently) have built-in CollectionNavigator support (the ability for the
// user to type and the items that match get selected). We implement it in the app instead.
ScenarioList.KeyDown += (s, a) =>
{
if (CollectionNavigatorBase.IsCompatibleKey (a))
{
int? newItem =
_scenarioCollectionNav?.GetNextMatchingItem (
ScenarioList.SelectedRow,
(char)a
);
if (newItem is int v && newItem != -1)
{
ScenarioList.SelectedRow = v;
ScenarioList.EnsureSelectedCellIsVisible ();
ScenarioList.SetNeedsDisplay ();
a.Handled = true;
}
}
};
ScenarioList.CellActivated += ScenarioView_OpenSelectedItem;
// TableView typically is a grid where nav keys are biased for moving left/right.
ScenarioList.KeyBindings.Add (Key.Home, Command.TopHome);
ScenarioList.KeyBindings.Add (Key.End, Command.BottomEnd);
// 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);
Add (CategoryList);
Add (ScenarioList);
Add (MenuBar);
Add (StatusBar);
Loaded += LoadedHandler;
Unloaded += UnloadedHandler;
// Restore previous selections
CategoryList.SelectedItem = _cachedCategoryIndex;
ScenarioList.SelectedRow = _cachedScenarioIndex;
Applied += ConfigAppliedHandler;
}
public void ConfigChanged ()
{
if (_topLevelColorScheme == null || !Colors.ColorSchemes.ContainsKey (_topLevelColorScheme))
{
_topLevelColorScheme = "Base";
}
_cachedTheme = Themes?.Theme;
_themeMenuItems = CreateThemeMenuItems ();
_themeMenuBarItem!.Children = _themeMenuItems;
foreach (MenuItem mi in _themeMenuItems!)
{
if (mi is { Parent: null })
{
mi.Parent = _themeMenuBarItem;
}
}
ColorScheme = Colors.ColorSchemes [_topLevelColorScheme];
MenuBar.Menus [0].Children [0].Shortcut = (KeyCode)Application.QuitKey;
StatusBar.Items [0].Shortcut = Application.QuitKey;
StatusBar.Items [0].Title = $"~{Application.QuitKey} to quit";
miIsMouseDisabled!.Checked = Application.IsMouseDisabled;
int height = ShowStatusBar ? 1 : 0; // + (MenuBar.Visible ? 1 : 0);
//ContentPane.Height = Dim.Fill (height);
StatusBar.Visible = ShowStatusBar;
Application.Top.SetNeedsDisplay ();
}
public MenuItem []? CreateThemeMenuItems ()
{
List<MenuItem> menuItems = CreateForce16ColorItems ().ToList ();
menuItems.Add (null!);
var schemeCount = 0;
foreach (KeyValuePair<string, ThemeScope> theme in Themes!)
{
var item = new MenuItem
{
Title = $"_{theme.Key}",
Shortcut = (KeyCode)new Key ((KeyCode)((uint)KeyCode.D1 + schemeCount++))
.WithCtrl
};
item.CheckType |= MenuItemCheckStyle.Checked;
item.Checked = theme.Key == _cachedTheme; // CM.Themes.Theme;
item.Action += () =>
{
Themes.Theme = _cachedTheme = theme.Key;
Apply ();
};
menuItems.Add (item);
}
List<MenuItem> schemeMenuItems = new ();
foreach (KeyValuePair<string, ColorScheme> sc in Colors.ColorSchemes)
{
var item = new MenuItem { Title = $"_{sc.Key}", Data = sc.Key };
item.CheckType |= MenuItemCheckStyle.Radio;
item.Checked = sc.Key == _topLevelColorScheme;
item.Action += () =>
{
_topLevelColorScheme = (string)item.Data;
foreach (MenuItem schemeMenuItem in schemeMenuItems)
{
schemeMenuItem.Checked =
(string)schemeMenuItem.Data == _topLevelColorScheme;
}
ColorScheme = Colors.ColorSchemes [_topLevelColorScheme];
Application.Top.SetNeedsDisplay ();
};
schemeMenuItems.Add (item);
}
menuItems.Add (null!);
var mbi = new MenuBarItem ("_Color Scheme for Application.Top", schemeMenuItems.ToArray ());
menuItems.Add (mbi);
return menuItems.ToArray ();
}
private void CategoryView_SelectedChanged (object? sender, ListViewItemEventArgs? e)
{
string item = _categories! [e!.Item];
List<Scenario> newlist;
if (e.Item == 0)
{
// First category is "All"
newlist = _scenarios!;
newlist = _scenarios!;
}
else
{
newlist = _scenarios!.Where (s => s.GetCategories ().Contains (item)).ToList ();
}
ScenarioList.Table = new EnumerableTableSource<Scenario> (
newlist,
new Dictionary<string, Func<Scenario, object>>
{
{ "Name", s => s.GetName () }, { "Description", s => s.GetDescription () }
}
);
// Create a collection of just the scenario names (the 1st column in our TableView)
// for CollectionNavigator.
List<object> firstColumnList = new ();
for (var i = 0; i < ScenarioList.Table.Rows; i++)
{
firstColumnList.Add (ScenarioList.Table [i, 0]);
}
_scenarioCollectionNav.Collection = firstColumnList;
}
private void ConfigAppliedHandler (object? sender, ConfigurationManagerEventArgs? a) { ConfigChanged (); }
private MenuItem [] CreateDiagnosticFlagsMenuItems ()
{
const string OFF = "Diagnostics: _Off";
const string FRAME_RULER = "Diagnostics: Frame _Ruler";
const string FRAME_PADDING = "Diagnostics: _Frame Padding";
var index = 0;
List<MenuItem> menuItems = new ();
foreach (Enum diag in Enum.GetValues (_diagnosticFlags.GetType ()))
{
var item = new MenuItem
{
Title = GetDiagnosticsTitle (diag), Shortcut = (KeyCode)new Key (index.ToString () [0]).WithAlt
};
index++;
item.CheckType |= MenuItemCheckStyle.Checked;
if (GetDiagnosticsTitle (ConsoleDriver.DiagnosticFlags.Off) == item.Title)
{
item.Checked = (_diagnosticFlags
& (ConsoleDriver.DiagnosticFlags.FramePadding
| ConsoleDriver.DiagnosticFlags
.FrameRuler))
== 0;
}
else
{
item.Checked = _diagnosticFlags.HasFlag (diag);
}
item.Action += () =>
{
string t = GetDiagnosticsTitle (ConsoleDriver.DiagnosticFlags.Off);
if (item.Title == t && item.Checked == false)
{
_diagnosticFlags &= ~(ConsoleDriver.DiagnosticFlags.FramePadding | ConsoleDriver.DiagnosticFlags.FrameRuler);
item.Checked = true;
}
else if (item.Title == t && item.Checked == true)
{
_diagnosticFlags |= ConsoleDriver.DiagnosticFlags.FramePadding | ConsoleDriver.DiagnosticFlags.FrameRuler;
item.Checked = false;
}
else
{
Enum f = GetDiagnosticsEnumValue (item.Title);
if (_diagnosticFlags.HasFlag (f))
{
SetDiagnosticsFlag (f, false);
}
else
{
SetDiagnosticsFlag (f, true);
}
}
foreach (MenuItem menuItem in menuItems)
{
if (menuItem.Title == t)
{
menuItem.Checked =
!_diagnosticFlags.HasFlag (
ConsoleDriver.DiagnosticFlags
.FrameRuler
)
&& !_diagnosticFlags.HasFlag (ConsoleDriver.DiagnosticFlags.FramePadding);
}
else if (menuItem.Title != t)
{
menuItem.Checked =
_diagnosticFlags.HasFlag (
GetDiagnosticsEnumValue (menuItem.Title)
);
}
}
ConsoleDriver.Diagnostics = _diagnosticFlags;
Application.Top.SetNeedsDisplay ();
};
menuItems.Add (item);
}
return menuItems.ToArray ();
string GetDiagnosticsTitle (Enum diag)
{
return Enum.GetName (_diagnosticFlags.GetType (), diag) switch
{
"Off" => OFF,
"FrameRuler" => FRAME_RULER,
"FramePadding" => FRAME_PADDING,
_ => ""
};
}
Enum GetDiagnosticsEnumValue (string title)
{
return title switch
{
FRAME_RULER => ConsoleDriver.DiagnosticFlags.FrameRuler,
FRAME_PADDING => ConsoleDriver.DiagnosticFlags.FramePadding,
_ => null!
};
}
void SetDiagnosticsFlag (Enum diag, bool add)
{
switch (diag)
{
case ConsoleDriver.DiagnosticFlags.FrameRuler:
if (add)
{
_diagnosticFlags |= ConsoleDriver.DiagnosticFlags.FrameRuler;
}
else
{
_diagnosticFlags &= ~ConsoleDriver.DiagnosticFlags.FrameRuler;
}
break;
case ConsoleDriver.DiagnosticFlags.FramePadding:
if (add)
{
_diagnosticFlags |= ConsoleDriver.DiagnosticFlags.FramePadding;
}
else
{
_diagnosticFlags &= ~ConsoleDriver.DiagnosticFlags.FramePadding;
}
break;
default:
_diagnosticFlags = default (ConsoleDriver.DiagnosticFlags);
break;
}
}
}
private List<MenuItem []> CreateDiagnosticMenuItems ()
{
List<MenuItem []> menuItems = new ()
{
CreateDiagnosticFlagsMenuItems (),
new MenuItem [] { null! },
CreateDisabledEnabledMouseItems (),
CreateDisabledEnabledMenuBorder (),
CreateDisabledEnableUseSubMenusSingleFrame (),
CreateKeyBindingsMenuItems ()
};
return menuItems;
}
// TODO: This should be an ConfigurationManager setting
private MenuItem [] CreateDisabledEnabledMenuBorder ()
{
List<MenuItem> menuItems = new ();
miIsMenuBorderDisabled = new MenuItem { Title = "Disable Menu _Border" };
miIsMenuBorderDisabled.Shortcut =
(KeyCode)new Key (miIsMenuBorderDisabled!.Title!.Substring (14, 1) [0]).WithAlt
.WithCtrl;
miIsMenuBorderDisabled.CheckType |= MenuItemCheckStyle.Checked;
miIsMenuBorderDisabled.Action += () =>
{
miIsMenuBorderDisabled.Checked = (bool)!miIsMenuBorderDisabled.Checked!;
MenuBar.MenusBorderStyle = !(bool)miIsMenuBorderDisabled.Checked
? LineStyle.Single
: LineStyle.None;
};
menuItems.Add (miIsMenuBorderDisabled);
return menuItems.ToArray ();
}
private MenuItem [] CreateDisabledEnabledMouseItems ()
{
List<MenuItem> menuItems = new ();
miIsMouseDisabled = new MenuItem { Title = "_Disable Mouse" };
miIsMouseDisabled.Shortcut =
(KeyCode)new Key (miIsMouseDisabled!.Title!.Substring (1, 1) [0]).WithAlt.WithCtrl;
miIsMouseDisabled.CheckType |= MenuItemCheckStyle.Checked;
miIsMouseDisabled.Action += () =>
{
miIsMouseDisabled.Checked =
Application.IsMouseDisabled = (bool)!miIsMouseDisabled.Checked!;
};
menuItems.Add (miIsMouseDisabled);
return menuItems.ToArray ();
}
// TODO: This should be an ConfigurationManager setting
private MenuItem [] CreateDisabledEnableUseSubMenusSingleFrame ()
{
List<MenuItem> menuItems = new ();
miUseSubMenusSingleFrame = new MenuItem { Title = "Enable _Sub-Menus Single Frame" };
miUseSubMenusSingleFrame.Shortcut = KeyCode.CtrlMask
| KeyCode.AltMask
| (KeyCode)miUseSubMenusSingleFrame!.Title!.Substring (8, 1) [
0];
miUseSubMenusSingleFrame.CheckType |= MenuItemCheckStyle.Checked;
miUseSubMenusSingleFrame.Action += () =>
{
miUseSubMenusSingleFrame.Checked = (bool)!miUseSubMenusSingleFrame.Checked!;
MenuBar.UseSubMenusSingleFrame = (bool)miUseSubMenusSingleFrame.Checked;
};
menuItems.Add (miUseSubMenusSingleFrame);
return menuItems.ToArray ();
}
private MenuItem [] CreateForce16ColorItems ()
{
List<MenuItem> menuItems = new ();
miForce16Colors = new MenuItem
{
Title = "Force _16 Colors",
Shortcut = (KeyCode)Key.F6,
Checked = Application.Force16Colors,
CanExecute = () => Application.Driver.SupportsTrueColor
};
miForce16Colors.CheckType |= MenuItemCheckStyle.Checked;
miForce16Colors.Action += () =>
{
miForce16Colors.Checked = Application.Force16Colors = (bool)!miForce16Colors.Checked!;
Application.Refresh ();
};
menuItems.Add (miForce16Colors);
return menuItems.ToArray ();
}
private MenuItem [] CreateKeyBindingsMenuItems ()
{
List<MenuItem> menuItems = new ();
var item = new MenuItem { Title = "_Key Bindings", Help = "Change which keys do what" };
item.Action += () =>
{
var dlg = new KeyBindingsDialog ();
Application.Run (dlg);
};
menuItems.Add (null!);
menuItems.Add (item);
return menuItems.ToArray ();
}
private void LoadedHandler (object? sender, EventArgs? args)
{
ConfigChanged ();
miIsMouseDisabled!.Checked = Application.IsMouseDisabled;
DriverName.Title = $"Driver: {Driver.GetVersionInfo ()}";
OS.Title =
$"OS: {RuntimeEnvironment.OperatingSystem} {RuntimeEnvironment.OperatingSystemVersion}";
if (_selectedScenario != null)
{
_selectedScenario = null;
_isFirstRunning = false;
}
if (!_isFirstRunning)
{
ScenarioList.SetFocus ();
}
StatusBar.VisibleChanged += (s, e) =>
{
ShowStatusBar = StatusBar.Visible;
int height = StatusBar.Visible ? 1 : 0;
CategoryList.Height = Dim.Fill (height);
ScenarioList.Height = Dim.Fill (height);
// ContentPane.Height = Dim.Fill (height);
LayoutSubviews ();
SetSubViewNeedsDisplay ();
};
Loaded -= LoadedHandler;
CategoryList.EnsureSelectedItemVisible ();
ScenarioList.EnsureSelectedCellIsVisible ();
}
/// <summary>Launches the selected scenario, setting the global _selectedScenario</summary>
/// <param name="e"></param>
private void ScenarioView_OpenSelectedItem (object? sender, EventArgs? e)
{
if (_selectedScenario is null)
{
// Save selected item state
_cachedCategoryIndex = CategoryList.SelectedItem;
_cachedScenarioIndex = ScenarioList.SelectedRow;
// Create new instance of scenario (even though Scenarios contains instances)
var selectedScenarioName = (string)ScenarioList.Table [ScenarioList.SelectedRow, 0];
_selectedScenario = (Scenario)Activator.CreateInstance (
_scenarios!.FirstOrDefault (
s => s.GetName ()
== selectedScenarioName
)!
.GetType ()
)!;
// Tell the main app to stop
Application.RequestStop ();
}
}
private void UnloadedHandler (object? sender, EventArgs? args)
{
Applied -= ConfigAppliedHandler;
Unloaded -= UnloadedHandler;
}
}
private struct Options
{
public string Driver;
public string Scenario;
/* etc. */
}
}