From be9d1939c13ad8c9a981751ab00a3b3b1685248a Mon Sep 17 00:00:00 2001 From: Tig Date: Tue, 11 Nov 2025 20:37:33 -0700 Subject: [PATCH] Fixes #4372 - Genericize `FlagSelector`/`OptionSelector`, Replace `RadioGroup` (#4373) * Refactor selectors and improve UI components Refactored `MarginEditor` and `UICatalogTop` to use new `OptionSelector` and `FlagSelector` classes, introducing type-safe generic versions for better flexibility and maintainability. Added `SelectorBase` as a shared foundation for these components, along with the `SelectorStyles` enum for customizable styles. Enhanced unit tests to cover new implementations and edge cases. Enabled nullable reference types for improved null safety. Improved code readability, reduced redundancy, and enhanced user experience with better hotkey management, focus handling, and layout adjustments. * Refactor UI components and remove unused classes Significant refactoring and simplification of the codebase: - Updated `CharacterMap` to use `OptionSelector`. - Removed `FlagSelector`, `FlagSelector`, and `FlagSelectorStyles`. - Replaced `OptionSelector.Options` with `Labels` in `MenuBarv2`. - Removed `OptionSelector` and its associated properties/methods. - Updated terminology from "Activate" to "Select" across components. - Refactored `SelectorBase` to align with new "Select" behavior. - Removed redundant methods, properties, and event handlers. These changes streamline the codebase, reduce complexity, and align with updated design principles. * Fixes #4374 - 'Application.Screen' is empty when 'Init' returns Refactor and enhance testability of ApplicationImpl Refactored `ApplicationImpl` and related classes to improve modularity and testability. Replaced `FakeConsoleOutput` with `FakeOutput` and introduced `FakeInput` for better test isolation. Added platform-specific factories (`FakeNetComponentFactory`, `FakeWindowsComponentFactory`) to simplify fake component creation. Refactored `GuiTestContext` into partial classes, adding methods for simulating user interactions and improving initialization logic. Enhanced error handling and logging during test setup. Updated tests to use the new `FakeOutput` and `FakeInput` implementations. Standardized driver initialization with `Application.Init(null, "fake")`. Skipped tests relying on the fake driver due to known issues. Performed general cleanup, modernized syntax, and removed redundant code to improve readability and maintainability. * Disable "windows" test case in SynchronizationContextTests The `InlineData("windows")` attribute in the `SynchronizationContext_Post` test method has been commented out. This change temporarily excludes the `"windows"` driverName from the test suite while retaining other test cases (`"fake"`, `"dotnet"`, and `"unix"`). The exclusion may be for debugging, deprecation, or other maintenance purposes. * Disable "windows" test case in SynchronizationContextTests The `[InlineData("windows")]` attribute in the `SynchronizationContextTests` class has been commented out, disabling the test case for the `"windows"` driver name. This change may have been made for debugging, deprecation, or because the test is no longer relevant. Other test cases (`"fake"`, `"dotnet"`, and `"unix"`) remain active. * Update Terminal.Gui/Drivers/FakeDriver/FakeConsole.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/SelectorStyles.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/SelectorBase.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/OptionSelector.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/OptionSelector.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/OptionSelector.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/SelectorBase.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Backported Checkbox from Activate PR * Backported Checkbox from Activate PR 2 * Backported Checkbox from Activate PR 3 * Backported Selctors Scenario * Backported Bars Scenario * Backported AllViewsTester Scenario * Backported Dialogs Scenario * Backported MessageBoxes Scenario * Backported ArrangementEditor * Backported mouse binding fix * Update Terminal.Gui/Views/Selectors/OptionSelector.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Drivers/WindowsDriver/WindowsOutput.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/CheckBox.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Fixed typo * Refactor ArrangementEditor event handling Removed the `ArrangementFlagsOnValueChanged` method, which previously handled updates to `ViewToEdit` properties based on arrangement flags. Updated `ArrangementEditor_Initialized` to attach the event handler to `_arrangementSelector.ValueChanged`. The logic for handling arrangement changes has been refactored or relocated. * Refactor AlignKeys for type safety and readability Updated the `AlignKeys` method in the `Shortcuts` class to replace generic `View` references with the more specific `Shortcut` type. Improved type safety by using `IEnumerable` and `.Cast()`. Simplified the `max` calculation logic with a single LINQ query and removed redundant casting in the `foreach` loop. These changes enhance code readability, maintainability, and ensure better type safety. * Refactor ArrangementEditor for clarity and consistency Refactored `ArrangementEditor` to improve code readability and maintainability: - Enabled nullable reference types with `#nullable enable`. - Removed unused `using` directives. - Adjusted namespace declaration for formatting consistency. - Reformatted `_arrangementSelector` initialization and property assignment. - Simplified `OnViewToEditChanged` logic with a ternary expression. - Refactored `ArrangementEditor_Initialized` into a single-line block. * Update Examples/UICatalog/Scenarios/Shortcuts.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/OptionSelector.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Refactor and enhance OptionSelector and SelectorBase Refactored `OptionSelector` and `SelectorBase` to simplify logic, improve hotkey assignment, and ensure robust behavior. Updated `Shortcuts.cs` and `DialogTests.cs` to address nullability issues. Added comprehensive unit tests for `OptionSelector` and `SelectorBase`, covering properties, methods, edge cases, and layout behaviors. These changes improve code readability, maintainability, and functionality while adhering to modern C# practices. * add FlagSelector comprehensive tests Refactored `UncheckNone` and `UncheckAll` methods in `FlagSelector` to improve clarity and prevent concurrent modifications using a new `_updatingChecked` flag. Removed the old `UncheckNone` implementation and reorganized logic for maintainability. Added extensive unit tests in `FlagSelectorTests` to validate functionality, including edge cases and generic implementations. Tests cover flag combination, toggling, "None" flag behavior, and enum-based generic handling. Improved overall maintainability and test coverage for the `FlagSelector` class. * Fixes #4375. UnixDriver fails Toplevel_TabGroup_Forward_Backward Fluent Tests * Refactor RadioGroup to use OptionSelector The `RadioGroup` class has been refactored to inherit from the `OptionSelector` class instead of `View`, marking it as `[Obsolete]` and recommending the use of `OptionSelector`. The previous implementation of `RadioGroup` has been entirely removed, including its properties, methods, events, and internal logic. This includes initialization logic, key bindings, layout management, and event handling. The new `RadioGroup` is now a thin wrapper around `OptionSelector` and implements the `IDesignable` interface. The `EnableForDesign` method has been simplified to set default options for design purposes. This change simplifies the codebase and encourages the use of `OptionSelector` for managing mutually exclusive options. * Backported focus tests and add bug-exposing test case Refactored `AdvanceFocusTests` to improve assertion clarity by replacing `Assert.True`/`Assert.False` with `Assert.Equal`. Enhanced test documentation with detailed view hierarchy comments for better readability. Added a new test case, `FocusNavigation_Should_Cycle_Back_To_Top_Level_Views`, which exposes a bug in focus navigation logic where focus does not cycle back to top-level views after traversing nested views. Updated existing tests to ensure consistent handling of `TabBehavior` and made minor adjustments for improved validation of focus navigation logic. * Remove all tests for RadioGroup component The `RadioGroupTests.cs` file has been completely cleared of all test cases and associated code. This includes the removal of unit tests that validated the `RadioGroup` component's functionality, behavior, and edge cases. The deleted tests covered: - Default constructor behavior and initialization. - Handling of the `SelectedItem` property, including edge cases. - Hotkey bindings and their behavior under different focus states. - Command handling for focus, selection, and acceptance. - Orientation changes and their impact on layout. - Event handling for `SelectedItemChanged`, `Selecting`, and `Accepting`. - Mouse interactions, including single-click and double-click events. This removal eliminates all automated validation for the `RadioGroup` component, leaving it untested and increasing the risk of regressions or undetected issues in future changes. * Fix unix and fake fluent tests. * More fixes for unix and fake drivers * Change classes names for more consistency * Fix typos in docs and method signature Updated XML documentation in `FakeConsole.cs` to replace `` with `` for clarity. Corrected a parameter name in `WindowsOutput.cs`'s `WriteConsole` method from `numberOfCharsToWritten` to `numberOfCharsToWrite` to fix a typo and improve readability. * Refactor: Replace RadioGroup with OptionSelector Replaced all instances of `RadioGroup` with `OptionSelector` across the codebase to standardize the control for mutually exclusive options. Updated associated properties, methods, and event handlers to align with the `OptionSelector` API, including replacing `RadioLabels` with `AssignHotKeys` and `SelectedItemChanged` with `ValueChanged`. Removed the `RadioGroup` class, marking it as obsolete. Updated documentation, comments, and test cases to reflect the new control. Adjusted layout and positioning logic in various scenarios to ensure UI consistency. Refactored scenarios such as `Buttons`, `ColorPickers`, `DynamicMenuBar`, `FileDialogExamples`, `Images`, `PosAlignDemo`, `ProgressBarStyles`, `RegionScenario`, `Themes`, and others to use `OptionSelector`. Updated `Glyphs` and `View` classes to reflect the terminology change. Cleaned up redundant code and ensured compatibility across the application. * Refactor OptionSelector to use Value instead of SelectedItem Replaced the SelectedItem property with a nullable Value property across the codebase to simplify the API and improve consistency. Updated event handlers from SelectedItemChanged to ValueChanged and adjusted logic accordingly. Refactored UI scenarios (e.g., Buttons, CharacterMap, ColorPickers) and dependent classes (e.g., BorderEditor, DimEditor, PosEditor) to use the new Value property. Improved null handling and streamlined initialization of controls. Updated tests to validate the Value property and renamed test methods for clarity. Removed the RegionOpSelector class as it was no longer needed. Performed general code cleanup, including formatting and removal of redundant code. * Refactor OptionSelector: Replace RadioLabels with Labels Updated the `OptionSelector` class and its derived classes to replace the `RadioLabels` property with a more generic `Labels` property, aligning with the base class `SelectorBase`. This change standardizes the API and simplifies label-related functionality. Refactored all instances of `RadioLabels` across the codebase, including property assignments, method calls, and references in scenarios, tests, and examples. Updated classes include `ColorPickers`, `Dialogs`, `DimAutoDemo`, `DynamicMenuBar`, `FileDialogExamples`, `Images`, `PosAlignDemo`, `Selectors`, `Shortcuts`, `TextAlignmentAndDirection`, `Themes`, `UnicodeInMenu`, `Wizards`, `UICatalogTop`, and `ScenarioTests`. Modified `OptionSelector` to initialize `Labels` directly using `Enum.GetValues()`. Removed the `RadioLabels` property from `OptionSelector`, consolidating functionality under `Labels`. Verified functionality through updated tests and scenarios to ensure consistent behavior with the previous implementation. * Refactor: Replace "radio group" with "option selector" Updated terminology across multiple classes to replace "radio group" with "option selector" for improved clarity and consistency. - Removed unused `OptionSelector` in `ColorPickers`. - Renamed `Title` in `DimAutoDemo` to "Options" and updated `BorderStyle`. - Replaced `_radioItems` with `_optionLabels` in `DimEditor` and `PosEditor`. - Renamed `styleRadioGroup` to `styleOptionSelector` in `MessageBoxes`. - Renamed `radioGroup` to `optionSelector` in `UnicodeInMenu` and `OrientationTests`. - Adjusted related references, event handlers, and UI properties. These changes align the codebase with updated terminology and improve readability. * Replace RadioGroup with OptionSelector and update docs The `RadioGroup` control has been replaced or renamed to `OptionSelector`. Documentation has been updated to reflect this change, including the behavior of raising the `Selecting` event when an option is selected. The navigation table now describes `OptionSelector` as supporting multiple options with actions like `Advance`, `SetValue+OnAccept`, and `Focus+SetValue`. A new section introduces the `OptionSelector` view, which displays mutually-exclusive items with hotkeys. Enhancements to `Menuv2` and `MenuBarv2` include setting focus on `MenuItemv2` selections and raising the `SelectedMenuItemChanged` event. Additionally, a progress bar view has been introduced to visually indicate activity progress. * Fixed `EndAfterFirstIteration` Renamed the `EndAfterFirstIteration` property to `StopAfterFirstIteration` across the codebase for improved clarity and consistency. Updated all references in the `Application`, `ApplicationImpl`, `IApplication`, and `ITimedEvents` classes, as well as related tests and documentation. Modified the application loop logic to use `StopAfterFirstIteration` for controlling the termination of the application after the first iteration. Set its default value to `false`. Updated test cases, demo applications, and XML documentation to reflect the new property name. Added a new project, `OutputView`, to the solution with appropriate configuration entries. Performed minor code cleanup to ensure consistency in naming and behavior. * Enhance selectors and clean up documentation - Added `args.Handled = true` to `CheckBox` event handlers in `FlagSelector` and `OptionSelector` to mark events as handled. - Introduced `_value` field in `FlagSelector` and added a `Cycle` method in `OptionSelector` for better value management. - Updated `OptionSelector` documentation to reference `OptionSelector` for type-safe enum usage. - Improved `UpdateChecked` method documentation in `OptionSelector` to clarify exception behavior. - Enabled nullable reference types in `FlagSelectorTests` and `SelectorBaseTests` and moved them to a new namespace. - Removed outdated auto-generated content from `views.md`. - Removed `CheckBox.DefaultHighlightStyle` from the default theme configuration in `OutputView.cs`. * Update event handling and expand UI documentation Modified `args.Handled` in `FlagSelector` and `OptionSelector` to allow `Accepting` event propagation, improving event handling behavior. Added comments to clarify the changes. Expanded `views.md` with detailed documentation for built-in views and controls in *Terminal.Gui*, including descriptions, examples, and rendered outputs for components like `Bar`, `Button`, `CheckBox`, and more. This update enhances developer guidance for building terminal-based UIs. * Fixed `EndAfterFirstIteration` in `ApplicationImpl` Renamed the `EndAfterFirstIteration` property to `StopAfterFirstIteration` across the codebase for improved clarity. Updated its implementation to use a getter and setter that interact with the `ApplicationImpl.Instance` singleton for centralized management. Modified the `RunLoop` method to check the new `StopAfterFirstIteration` property. Updated the default value to `false` in the `Application` class. Added a private `_stopAfterFirstIteration` field and a corresponding public property in the `ApplicationImpl` class. Updated the `Run` method in `ApplicationImpl` to stop after the first iteration if the property is set to `true`, with appropriate logging. Updated the `IApplication` interface to include the `StopAfterFirstIteration` property and clarified the behavior of the `RequestStop` method. Revised XML documentation comments to reflect these changes. * Fixed EndfterFirstIteration in ApplicaitonImpl Refactored `StopAfterFirstIteration` in `ApplicationImpl` to use an auto-property for simplicity. Updated `RunIteration` to call `view.RequestStop()` instead of modifying `view.Running`. Replaced references to `Application.EndAfterFirstIteration` with `Application.StopAfterFirstIteration` across the codebase, including `ITimedEvents`, `ApplicationTests`, and `GlobalTestSetup`. Added a new test, `InitRunShutdown_StopAfterFirstIteration_Stops`, to verify the application stops correctly after the first iteration. Updated related documentation and assertions for consistency. * Refactor Value handling and improve type safety Refactored `Value` handling across multiple classes to use nullable generic types, improving type safety and eliminating unnecessary casting. Simplified `ValueChanged` event handlers with concise lambda expressions. Enhanced `FlagSelector` and `OptionSelector` with generic `ValueChanged` events and type-safe event handling. Added nullable reference type annotations to align with modern C# practices. Improved test code by using null-forgiving operators and more descriptive assertions. Cleaned up redundant code and ensured consistency in `Value` handling. Updated `FlagSelectorTests` and `SelectorBaseTests` for better readability and maintainability. Added the `System` namespace to `FlagSelectorTEnum.cs` for compatibility. Overall, these changes enhance code readability, maintainability, and robustness. * Merged v2_develop * Update README badges for v2_develop branch Updated the `.NET Core` badge to reference the `v2_develop` branch. Adjusted the `codecov` badge to remove branch-specific paths and added a token parameter. Reorganized the `codecov` badge position in the README. Retained other badges without modification. * codcov2 * fixed pos tests * Improve cleanup, coverage config, and SpinnerStyle tests Enhanced resource cleanup in `Pos.CombineTests.cs` by disposing of `Application.Top` to prevent leaks. Updated `codecov.yml` to focus coverage on `Terminal.Gui`, simplified path patterns, and clarified configurations. Added `SpinnerStyleTests` with extensive unit tests for `SpinnerStyle` and its variants, covering default properties, behaviors, edge cases, and immutability. Organized tests for readability and ensured thorough validation of all spinner styles. Enabled nullable reference types for improved safety. * Remove .NET Core badge; add comprehensive boundary tests The `.NET Core` workflow badge was removed from the `README.md` file. Added a comprehensive suite of unit tests for the `Region.DrawOuterBoundary` method in `DrawOuterBoundaryTests.cs`. These tests validate the method's behavior across various scenarios, including: - Intersected, unioned, and complex shapes. - Edge cases like empty regions, zero-width/height rectangles, and single-pixel rectangles. - Specific shapes such as L-shaped, T-shaped, and hollow rectangles. - Overlapping, adjacent, and separate rectangles. - Thread safety with parallel drawing. - Different line styles, custom attributes, and very large regions. - Various positions, sizes, and multiple calls on the same canvas. The tests use the `Xunit` framework and include both `[Fact]` and `[Theory]` test cases. These changes enhance the codebase's robustness and ensure correctness in a wide range of scenarios. --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: BDisp --- .../UICatalog/Scenarios/AllViewsTester.cs | 14 +- Examples/UICatalog/Scenarios/Bars.cs | 4 +- Examples/UICatalog/Scenarios/Buttons.cs | 69 +- .../Scenarios/CharacterMap/CharacterMap.cs | 34 +- Examples/UICatalog/Scenarios/ColorPicker.cs | 34 +- Examples/UICatalog/Scenarios/Dialogs.cs | 17 +- Examples/UICatalog/Scenarios/DimAutoDemo.cs | 8 +- .../UICatalog/Scenarios/DynamicMenuBar.cs | 20 +- .../EditorsAndHelpers/ArrangementEditor.cs | 92 +-- .../EditorsAndHelpers/BorderEditor.cs | 27 +- .../Scenarios/EditorsAndHelpers/DimEditor.cs | 18 +- .../EditorsAndHelpers/MarginEditor.cs | 36 +- .../Scenarios/EditorsAndHelpers/PosEditor.cs | 18 +- .../EditorsAndHelpers/ViewPropertiesEditor.cs | 19 +- .../UICatalog/Scenarios/FileDialogExamples.cs | 282 +++---- Examples/UICatalog/Scenarios/Images.cs | 32 +- Examples/UICatalog/Scenarios/LineDrawing.cs | 14 +- Examples/UICatalog/Scenarios/MessageBoxes.cs | 17 +- Examples/UICatalog/Scenarios/PosAlignDemo.cs | 272 +++--- .../UICatalog/Scenarios/ProgressBarStyles.cs | 28 +- .../UICatalog/Scenarios/RegionScenario.cs | 63 +- Examples/UICatalog/Scenarios/ScrollBarDemo.cs | 14 +- Examples/UICatalog/Scenarios/Selectors.cs | 287 +++++++ Examples/UICatalog/Scenarios/Shortcuts.cs | 167 ++-- .../Scenarios/TextAlignmentAndDirection.cs | 20 +- Examples/UICatalog/Scenarios/Themes.cs | 12 +- Examples/UICatalog/Scenarios/Unicode.cs | 10 +- Examples/UICatalog/Scenarios/Wizards.cs | 12 +- Examples/UICatalog/UICatalogTop.cs | 96 ++- README.md | 1 - Terminal.Gui/App/ApplicationImpl.cs | 1 + Terminal.Gui/Drawing/Glyphs.cs | 4 +- .../Drivers/WindowsDriver/WindowsOutput.cs | 1 + Terminal.Gui/Input/Mouse/MouseBinding.cs | 12 +- Terminal.Gui/ViewBase/View.Keyboard.cs | 2 +- Terminal.Gui/Views/CheckBox.cs | 64 +- Terminal.Gui/Views/FlagSelector.cs | 513 ------------ Terminal.Gui/Views/FlagSelectorStyles.cs | 31 - Terminal.Gui/Views/FlagSelectorTEnum.cs | 99 --- Terminal.Gui/Views/Menu/MenuBarv2.cs | 4 +- Terminal.Gui/Views/OptionSelector.cs | 324 -------- Terminal.Gui/Views/RadioGroup.cs | 604 -------------- Terminal.Gui/Views/Selectors/FlagSelector.cs | 244 ++++++ .../Views/Selectors/FlagSelectorTEnum.cs | 46 ++ .../Views/Selectors/OptionSelector.cs | 249 ++++++ .../Views/Selectors/OptionSelectorTEnum.cs | 53 ++ Terminal.Gui/Views/Selectors/SelectorBase.cs | 509 ++++++++++++ .../Views/Selectors/SelectorStyles.cs | 42 + Terminal.sln | 4 + .../UICatalog/ScenarioTests.cs | 44 +- .../GuiTestContext.cs | 3 +- .../UnitTests/View/Layout/Pos.CombineTests.cs | 8 +- Tests/UnitTests/Views/CheckBoxTests.cs | 8 +- Tests/UnitTests/Views/RadioGroupTests.cs | 775 ------------------ .../Drawing/Region/DrawOuterBoundaryTests.cs | 531 ++++++++++++ .../View/Navigation/AdvanceFocusTests.cs | 100 ++- .../View/Orientation/OrientationTests.cs | 8 +- .../Views/CheckBoxTests.cs | 2 +- .../Views/FlagSelectorTests.cs | 728 +++++++++++++--- .../Views/OptionSelectorTests.cs | 447 ++++++++++ .../Views/SelectorBaseTests.cs | 604 ++++++++++++++ docfx/docs/command.md | 2 +- docfx/docs/navigation.md | 2 +- docfx/docs/views.md | 65 +- docfx/scripts/OutputView/OutputView.cs | 3 +- 65 files changed, 4527 insertions(+), 3346 deletions(-) create mode 100644 Examples/UICatalog/Scenarios/Selectors.cs delete mode 100644 Terminal.Gui/Views/FlagSelector.cs delete mode 100644 Terminal.Gui/Views/FlagSelectorStyles.cs delete mode 100644 Terminal.Gui/Views/FlagSelectorTEnum.cs delete mode 100644 Terminal.Gui/Views/OptionSelector.cs delete mode 100644 Terminal.Gui/Views/RadioGroup.cs create mode 100644 Terminal.Gui/Views/Selectors/FlagSelector.cs create mode 100644 Terminal.Gui/Views/Selectors/FlagSelectorTEnum.cs create mode 100644 Terminal.Gui/Views/Selectors/OptionSelector.cs create mode 100644 Terminal.Gui/Views/Selectors/OptionSelectorTEnum.cs create mode 100644 Terminal.Gui/Views/Selectors/SelectorBase.cs create mode 100644 Terminal.Gui/Views/Selectors/SelectorStyles.cs delete mode 100644 Tests/UnitTests/Views/RadioGroupTests.cs create mode 100644 Tests/UnitTestsParallelizable/Drawing/Region/DrawOuterBoundaryTests.cs create mode 100644 Tests/UnitTestsParallelizable/Views/OptionSelectorTests.cs create mode 100644 Tests/UnitTestsParallelizable/Views/SelectorBaseTests.cs diff --git a/Examples/UICatalog/Scenarios/AllViewsTester.cs b/Examples/UICatalog/Scenarios/AllViewsTester.cs index 99fbbdb50..c3695121e 100644 --- a/Examples/UICatalog/Scenarios/AllViewsTester.cs +++ b/Examples/UICatalog/Scenarios/AllViewsTester.cs @@ -158,16 +158,13 @@ public class AllViewsTester : Scenario _eventLog = new () { - // X = Pos.Right(_layoutEditor), + X = Pos.AnchorEnd () - 1, + Y = 0, + Width = 30, + Height = Dim.Fill (), SuperViewRendersLineCanvas = true }; _eventLog.Border!.Thickness = new (1); - _eventLog.X = Pos.AnchorEnd () - 1; - _eventLog.Y = 0; - - _eventLog.Height = Dim.Height (_classListView); - - //_eventLog.Width = 30; _layoutEditor.Width = Dim.Fill ( Dim.Func ( @@ -194,7 +191,6 @@ public class AllViewsTester : Scenario Height = Dim.Fill (), CanFocus = true, TabStop = TabBehavior.TabStop, - //SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Base), Arrangement = ViewArrangement.LeftResizable | ViewArrangement.BottomResizable | ViewArrangement.RightResizable, BorderStyle = LineStyle.Double, SuperViewRendersLineCanvas = true @@ -228,7 +224,7 @@ public class AllViewsTester : Scenario if (type.IsGenericType) { // For each of the arguments - List typeArguments = new (); + List typeArguments = []; // use or the original type if applicable foreach (Type arg in type.GetGenericArguments ()) diff --git a/Examples/UICatalog/Scenarios/Bars.cs b/Examples/UICatalog/Scenarios/Bars.cs index af79c0cbd..50153f07d 100644 --- a/Examples/UICatalog/Scenarios/Bars.cs +++ b/Examples/UICatalog/Scenarios/Bars.cs @@ -185,9 +185,9 @@ public class Bars : Scenario menuLikeExamples.Add (popOverMenu); - menuLikeExamples.MouseClick += MenuLikeExamplesMouseClick; + menuLikeExamples.MouseEvent += MenuLikeExamplesMouseEvent; - void MenuLikeExamplesMouseClick (object sender, MouseEventArgs e) + void MenuLikeExamplesMouseEvent (object _, MouseEventArgs e) { if (e.Flags.HasFlag (MouseFlags.Button3Clicked)) { diff --git a/Examples/UICatalog/Scenarios/Buttons.cs b/Examples/UICatalog/Scenarios/Buttons.cs index b4c921437..f2ea4572f 100644 --- a/Examples/UICatalog/Scenarios/Buttons.cs +++ b/Examples/UICatalog/Scenarios/Buttons.cs @@ -243,17 +243,17 @@ public class Buttons : Scenario }; main.Add (label); - var radioGroup = new RadioGroup + OptionSelector osAlignment = new () { X = 4, Y = Pos.Bottom (label) + 1, - SelectedItem = 2, - RadioLabels = new [] { "_Start", "_End", "_Center", "_Fill" }, - Title = "_9 RadioGroup", + Value = Alignment.Center, + AssignHotKeys = true, + Title = "_9 OptionSelector", BorderStyle = LineStyle.Dotted, // CanFocus = false }; - main.Add (radioGroup); + main.Add (osAlignment); // Demo changing hotkey string MoveHotkey (string txt) @@ -292,7 +292,7 @@ public class Buttons : Scenario var moveHotKeyBtn = new Button { X = 2, - Y = Pos.Bottom (radioGroup) + 1, + Y = Pos.Bottom (osAlignment) + 1, Width = Dim.Width (computedFrame) - 2, SchemeName = "TopLevel", Text = mhkb @@ -309,7 +309,7 @@ public class Buttons : Scenario var moveUnicodeHotKeyBtn = new Button { X = Pos.Left (absoluteFrame) + 1, - Y = Pos.Bottom (radioGroup) + 1, + Y = Pos.Bottom (osAlignment) + 1, Width = Dim.Width (absoluteFrame) - 2, SchemeName = "TopLevel", Text = muhkb @@ -321,48 +321,21 @@ public class Buttons : Scenario }; main.Add (moveUnicodeHotKeyBtn); - radioGroup.SelectedItemChanged += (s, args) => - { - switch (args.SelectedItem) - { - case 0: - moveBtn.TextAlignment = Alignment.Start; - sizeBtn.TextAlignment = Alignment.Start; - moveBtnA.TextAlignment = Alignment.Start; - sizeBtnA.TextAlignment = Alignment.Start; - moveHotKeyBtn.TextAlignment = Alignment.Start; - moveUnicodeHotKeyBtn.TextAlignment = Alignment.Start; + osAlignment.ValueChanged += (s, args) => + { + if (args.Value is null) + { + return; + } - break; - case 1: - moveBtn.TextAlignment = Alignment.End; - sizeBtn.TextAlignment = Alignment.End; - moveBtnA.TextAlignment = Alignment.End; - sizeBtnA.TextAlignment = Alignment.End; - moveHotKeyBtn.TextAlignment = Alignment.End; - moveUnicodeHotKeyBtn.TextAlignment = Alignment.End; - - break; - case 2: - moveBtn.TextAlignment = Alignment.Center; - sizeBtn.TextAlignment = Alignment.Center; - moveBtnA.TextAlignment = Alignment.Center; - sizeBtnA.TextAlignment = Alignment.Center; - moveHotKeyBtn.TextAlignment = Alignment.Center; - moveUnicodeHotKeyBtn.TextAlignment = Alignment.Center; - - break; - case 3: - moveBtn.TextAlignment = Alignment.Fill; - sizeBtn.TextAlignment = Alignment.Fill; - moveBtnA.TextAlignment = Alignment.Fill; - sizeBtnA.TextAlignment = Alignment.Fill; - moveHotKeyBtn.TextAlignment = Alignment.Fill; - moveUnicodeHotKeyBtn.TextAlignment = Alignment.Fill; - - break; - } - }; + Alignment newValue = args.Value.Value; + moveBtn.TextAlignment = newValue; + sizeBtn.TextAlignment = newValue; + moveBtnA.TextAlignment = newValue; + sizeBtnA.TextAlignment = newValue; + moveHotKeyBtn.TextAlignment = newValue; + moveUnicodeHotKeyBtn.TextAlignment = newValue; + }; label = new () { diff --git a/Examples/UICatalog/Scenarios/CharacterMap/CharacterMap.cs b/Examples/UICatalog/Scenarios/CharacterMap/CharacterMap.cs index e4a73a928..3028eb4ee 100644 --- a/Examples/UICatalog/Scenarios/CharacterMap/CharacterMap.cs +++ b/Examples/UICatalog/Scenarios/CharacterMap/CharacterMap.cs @@ -365,40 +365,16 @@ public class CharacterMap : Scenario options [0] = "All"; Array.Copy (allCategoryNames, 0, options, 1, allCategoryNames.Length); - // TODO: When #4126 is merged update this to use OptionSelector - var selector = new OptionSelector - { - AssignHotKeysToCheckBoxes = true, - Options = options - }; + // TODO: Add a "None" option + OptionSelector selector = new (); _unicodeCategorySelector = selector; - // Default to "All" - selector.SelectedItem = 0; + selector.Value = null; _charMap!.ShowUnicodeCategory = null; - selector.SelectedItemChanged += (s, e) => - { - int? idx = selector.SelectedItem; + selector.ValueChanged += (_, e) => _charMap.ShowUnicodeCategory = e.Value; - if (idx is null) - { - return; - } - - if (idx.Value == 0) - { - _charMap.ShowUnicodeCategory = null; - } - else - { - // Map index to UnicodeCategory (offset by 1 because 0 is "All") - UnicodeCategory cat = Enum.GetValues () [idx.Value - 1]; - _charMap.ShowUnicodeCategory = cat; - } - }; - - return new() { CommandView = selector }; + return new () { CommandView = selector }; } } diff --git a/Examples/UICatalog/Scenarios/ColorPicker.cs b/Examples/UICatalog/Scenarios/ColorPicker.cs index 568e6824e..61b71d093 100644 --- a/Examples/UICatalog/Scenarios/ColorPicker.cs +++ b/Examples/UICatalog/Scenarios/ColorPicker.cs @@ -125,26 +125,25 @@ public class ColorPickers : Scenario app.Add (_demoView); - // Radio for switching color models - var rgColorModel = new RadioGroup () + var osColorModel = new OptionSelector () { Y = Pos.Bottom (_demoView), Width = Dim.Auto (), Height = Dim.Auto (), - RadioLabels = new [] - { + Labels = + [ "_RGB", "_HSV", "H_SL", "_16 Colors" - }, - SelectedItem = (int)foregroundColorPicker.Style.ColorModel, + ], + Value = (int)foregroundColorPicker.Style.ColorModel, }; - rgColorModel.SelectedItemChanged += (_, e) => + osColorModel.ValueChanged += (_, e) => { // 16 colors - if (e.SelectedItem == 3) + if (e.Value == 3) { foregroundColorPicker16.Visible = true; @@ -161,12 +160,17 @@ public class ColorPickers : Scenario { foregroundColorPicker16.Visible = false; foregroundColorPicker.Visible = true; - foregroundColorPicker.Style.ColorModel = (ColorModel)e.SelectedItem; - foregroundColorPicker.ApplyStyleChanges (); - backgroundColorPicker16.Visible = false; - backgroundColorPicker.Visible = true; - backgroundColorPicker.Style.ColorModel = (ColorModel)e.SelectedItem; + if (e.Value is { }) + { + foregroundColorPicker.Style.ColorModel = (ColorModel)e.Value; + foregroundColorPicker.ApplyStyleChanges (); + + backgroundColorPicker16.Visible = false; + backgroundColorPicker.Visible = true; + backgroundColorPicker.Style.ColorModel = (ColorModel)e.Value; + } + backgroundColorPicker.ApplyStyleChanges (); @@ -176,13 +180,13 @@ public class ColorPickers : Scenario } }; - app.Add (rgColorModel); + app.Add (osColorModel); // Checkbox for switching show text fields on and off var cbShowTextFields = new CheckBox () { Text = "Show _Text Fields", - Y = Pos.Bottom (rgColorModel) + 1, + Y = Pos.Bottom (osColorModel) + 1, Width = Dim.Auto (), Height = Dim.Auto (), CheckedState = foregroundColorPicker.Style.ShowTextFields ? CheckState.Checked : CheckState.UnChecked, diff --git a/Examples/UICatalog/Scenarios/Dialogs.cs b/Examples/UICatalog/Scenarios/Dialogs.cs index 949b45d4a..e7fd1ac77 100644 --- a/Examples/UICatalog/Scenarios/Dialogs.cs +++ b/Examples/UICatalog/Scenarios/Dialogs.cs @@ -151,18 +151,15 @@ public class Dialogs : Scenario }; frame.Add (label); - // Add hotkeys - var labels = Enum.GetNames ().Select (n => n = "_" + n); - var alignmentGroup = new RadioGroup + OptionSelector alignmentOptionSelector = new () { X = Pos.Right (label) + 1, Y = Pos.Top (label), - RadioLabels = labels.ToArray (), Title = "Ali_gn", - BorderStyle = LineStyle.Dashed + AssignHotKeys = true }; - frame.Add (alignmentGroup); - alignmentGroup.SelectedItem = labels.ToList ().IndexOf ("_" + Dialog.DefaultButtonAlignment.ToString ()); + frame.Add (alignmentOptionSelector); + alignmentOptionSelector.Value = Dialog.DefaultButtonAlignment; frame.ValidatePosDim = true; @@ -192,7 +189,7 @@ public class Dialogs : Scenario titleEdit, numButtonsEdit, glyphsNotWords, - alignmentGroup, + alignmentOptionSelector, buttonPressedLabel ); Application.Run (dlg); @@ -216,7 +213,7 @@ public class Dialogs : Scenario TextField titleEdit, TextField numButtonsEdit, CheckBox glyphsNotWords, - RadioGroup alignmentRadioGroup, + OptionSelector alignmentGroup, Label buttonPressedLabel ) { @@ -269,7 +266,7 @@ public class Dialogs : Scenario { Title = titleEdit.Text, Text = "Dialog Text", - ButtonAlignment = (Alignment)Enum.Parse (typeof (Alignment), alignmentRadioGroup.RadioLabels [alignmentRadioGroup.SelectedItem].Substring (1)), + ButtonAlignment = (Alignment)Enum.Parse (typeof (Alignment), alignmentGroup.Labels! [(int)alignmentGroup.Value!.Value] [1..]), Buttons = buttons.ToArray () }; diff --git a/Examples/UICatalog/Scenarios/DimAutoDemo.cs b/Examples/UICatalog/Scenarios/DimAutoDemo.cs index efad9eeb7..ab97889d0 100644 --- a/Examples/UICatalog/Scenarios/DimAutoDemo.cs +++ b/Examples/UICatalog/Scenarios/DimAutoDemo.cs @@ -163,15 +163,15 @@ public class DimAutoDemo : Scenario dimAutoFrameView.Add (resetButton); - var radioGroup = new RadioGroup () + var optionSelector = new OptionSelector () { - RadioLabels = ["One", "Two", "Three"], + Labels = ["One", "Two", "Three"], X = 0, Y = Pos.AnchorEnd (), - Title = "Radios", + Title = "Options", BorderStyle = LineStyle.Dotted }; - dimAutoFrameView.Add (radioGroup); + dimAutoFrameView.Add (optionSelector); return dimAutoFrameView; } diff --git a/Examples/UICatalog/Scenarios/DynamicMenuBar.cs b/Examples/UICatalog/Scenarios/DynamicMenuBar.cs index b800cc3ef..2687b4f6c 100644 --- a/Examples/UICatalog/Scenarios/DynamicMenuBar.cs +++ b/Examples/UICatalog/Scenarios/DynamicMenuBar.cs @@ -174,11 +174,11 @@ public class DynamicMenuBar : Scenario var rChkLabels = new [] { "NoCheck", "Checked", "Radio" }; - RbChkStyle = new () + OsChkStyle = new () { - X = Pos.Left (lblTitle), Y = Pos.Bottom (CkbSubMenu) + 1, RadioLabels = rChkLabels + X = Pos.Left (lblTitle), Y = Pos.Bottom (CkbSubMenu) + 1, Labels = rChkLabels }; - Add (RbChkStyle); + Add (OsChkStyle); var lblShortcut = new Label { @@ -294,7 +294,7 @@ public class DynamicMenuBar : Scenario public CheckBox CkbIsTopLevel { get; } public CheckBox CkbNullCheck { get; } public CheckBox CkbSubMenu { get; } - public RadioGroup RbChkStyle { get; } + public OptionSelector OsChkStyle { get; } public TextView TextAction { get; } public TextField TextHelp { get; } public TextField TextHotKey { get; } @@ -361,7 +361,7 @@ public class DynamicMenuBar : Scenario CkbNullCheck.CheckedState = menuItem.AllowNullChecked ? CheckState.Checked : CheckState.UnChecked; TextHelp.Enabled = CkbSubMenu.CheckedState == CheckState.UnChecked; TextAction.Enabled = CkbSubMenu.CheckedState == CheckState.UnChecked; - RbChkStyle.SelectedItem = (int)(menuItem?.CheckType ?? MenuItemCheckStyle.NoCheck); + OsChkStyle.Value = (int)(menuItem?.CheckType ?? MenuItemCheckStyle.NoCheck); TextShortcutKey.Text = menuItem?.ShortcutTag ?? ""; TextShortcutKey.Enabled = CkbIsTopLevel.CheckedState == CheckState.Checked && CkbSubMenu.CheckedState == CheckState.UnChecked @@ -434,8 +434,8 @@ public class DynamicMenuBar : Scenario HotKey = TextHotKey.Text, IsTopLevel = CkbIsTopLevel?.CheckedState == CheckState.Checked, HasSubMenu = CkbSubMenu?.CheckedState == CheckState.Checked, - CheckStyle = RbChkStyle.SelectedItem == 0 ? MenuItemCheckStyle.NoCheck : - RbChkStyle.SelectedItem == 1 ? MenuItemCheckStyle.Checked : + CheckStyle = OsChkStyle.Value == 0 ? MenuItemCheckStyle.NoCheck : + OsChkStyle.Value == 1 ? MenuItemCheckStyle.Checked : MenuItemCheckStyle.Radio, ShortcutKey = TextShortcutKey.Text, AllowNullChecked = CkbNullCheck?.CheckedState == CheckState.Checked, @@ -484,7 +484,7 @@ public class DynamicMenuBar : Scenario TextHotKey.Text = ""; CkbIsTopLevel.CheckedState = CheckState.UnChecked; CkbSubMenu.CheckedState = CheckState.UnChecked; - RbChkStyle.SelectedItem = (int)MenuItemCheckStyle.NoCheck; + OsChkStyle.Value = (int)MenuItemCheckStyle.NoCheck; TextShortcutKey.Text = ""; } @@ -829,9 +829,9 @@ public class DynamicMenuBar : Scenario HotKey = frmMenuDetails.TextHotKey.Text, IsTopLevel = frmMenuDetails.CkbIsTopLevel?.CheckedState == CheckState.Checked, HasSubMenu = frmMenuDetails.CkbSubMenu?.CheckedState == CheckState.Checked, - CheckStyle = frmMenuDetails.RbChkStyle.SelectedItem == 0 + CheckStyle = frmMenuDetails.OsChkStyle.Value == 0 ? MenuItemCheckStyle.NoCheck - : frmMenuDetails.RbChkStyle.SelectedItem == 1 + : frmMenuDetails.OsChkStyle.Value == 1 ? MenuItemCheckStyle.Checked : MenuItemCheckStyle.Radio, ShortcutKey = frmMenuDetails.TextShortcutKey.Text diff --git a/Examples/UICatalog/Scenarios/EditorsAndHelpers/ArrangementEditor.cs b/Examples/UICatalog/Scenarios/EditorsAndHelpers/ArrangementEditor.cs index 6d262ef2e..334450fbb 100644 --- a/Examples/UICatalog/Scenarios/EditorsAndHelpers/ArrangementEditor.cs +++ b/Examples/UICatalog/Scenarios/EditorsAndHelpers/ArrangementEditor.cs @@ -1,7 +1,4 @@ #nullable enable -using System; -using System.Collections.Generic; - namespace UICatalog.Scenarios; /// @@ -16,92 +13,34 @@ public sealed class ArrangementEditor : EditorBase Initialized += ArrangementEditor_Initialized; - _arrangementSlider.Options = - [ - new SliderOption - { - Legend = ViewArrangement.Movable.ToString (), - Data = ViewArrangement.Movable - }, - - new SliderOption - { - Legend = ViewArrangement.LeftResizable.ToString (), - Data = ViewArrangement.LeftResizable - }, - - new SliderOption - { - Legend = ViewArrangement.RightResizable.ToString (), - Data = ViewArrangement.RightResizable - }, - - new SliderOption - { - Legend = ViewArrangement.TopResizable.ToString (), - Data = ViewArrangement.TopResizable - }, - - new SliderOption - { - Legend = ViewArrangement.BottomResizable.ToString (), - Data = ViewArrangement.BottomResizable - }, - - new SliderOption - { - Legend = ViewArrangement.Overlapped.ToString (), - Data = ViewArrangement.Overlapped - } - ]; - - Add (_arrangementSlider); + Add (_arrangementSelector); } - private readonly Slider _arrangementSlider = new() + private readonly FlagSelector _arrangementSelector = new () { - Orientation = Orientation.Vertical, - UseMinimumSize = true, - Type = SliderType.Multiple, - AllowEmpty = true, + Orientation = Orientation.Vertical }; protected override void OnViewToEditChanged () { - _arrangementSlider.Enabled = ViewToEdit is not Adornment; + _arrangementSelector.Enabled = ViewToEdit is not Adornment; - _arrangementSlider.OptionsChanged -= ArrangementSliderOnOptionsChanged; + _arrangementSelector.ValueChanged -= ArrangementFlagsOnValueChanged; // Set the appropriate options in the slider based on _viewToEdit.Arrangement if (ViewToEdit is { }) { - _arrangementSlider.Options.ForEach ( - option => - { - _arrangementSlider.ChangeOption ( - _arrangementSlider.Options.IndexOf (option), - (ViewToEdit.Arrangement & option.Data) == option.Data); - }); + _arrangementSelector.Value = ViewToEdit.Arrangement; } - _arrangementSlider.OptionsChanged += ArrangementSliderOnOptionsChanged; + _arrangementSelector.ValueChanged += ArrangementFlagsOnValueChanged; } - private void ArrangementEditor_Initialized (object? sender, EventArgs e) { _arrangementSlider.OptionsChanged += ArrangementSliderOnOptionsChanged; } - - private void ArrangementSliderOnOptionsChanged (object? sender, SliderEventArgs e) + private void ArrangementFlagsOnValueChanged (object? sender, EventArgs e) { - if (ViewToEdit is { }) + if (ViewToEdit is { } && e.Value is { }) { - // Set the arrangement based on the selected options - var arrangement = ViewArrangement.Fixed; - - foreach (KeyValuePair> option in e.Options) - { - arrangement |= option.Value.Data; - } - - ViewToEdit.Arrangement = arrangement; + ViewToEdit.Arrangement = (ViewArrangement)e.Value; if (ViewToEdit.Arrangement.HasFlag (ViewArrangement.Overlapped)) { @@ -114,14 +53,9 @@ public sealed class ArrangementEditor : EditorBase ViewToEdit.SchemeName = ViewToEdit!.SuperView!.SchemeName; } - if (ViewToEdit.Arrangement.HasFlag (ViewArrangement.Movable)) - { - ViewToEdit.BorderStyle = LineStyle.Double; - } - else - { - ViewToEdit.BorderStyle = LineStyle.Single; - } + ViewToEdit.BorderStyle = ViewToEdit.Arrangement.HasFlag (ViewArrangement.Movable) ? LineStyle.Double : LineStyle.Single; } } + + private void ArrangementEditor_Initialized (object? sender, EventArgs e) { _arrangementSelector.ValueChanged += ArrangementFlagsOnValueChanged; } } diff --git a/Examples/UICatalog/Scenarios/EditorsAndHelpers/BorderEditor.cs b/Examples/UICatalog/Scenarios/EditorsAndHelpers/BorderEditor.cs index e5c6d0c18..ca962eb30 100644 --- a/Examples/UICatalog/Scenarios/EditorsAndHelpers/BorderEditor.cs +++ b/Examples/UICatalog/Scenarios/EditorsAndHelpers/BorderEditor.cs @@ -8,7 +8,7 @@ namespace UICatalog.Scenarios; public class BorderEditor : AdornmentEditor { private CheckBox? _ckbTitle; - private RadioGroup? _rbBorderStyle; + private OptionSelector? _osBorderStyle; private CheckBox? _ckbGradient; public BorderEditor () @@ -21,34 +21,31 @@ public class BorderEditor : AdornmentEditor private void BorderEditor_AdornmentChanged (object? sender, EventArgs e) { _ckbTitle!.CheckedState = ((Border)AdornmentToEdit!).Settings.FastHasFlags (BorderSettings.Title) ? CheckState.Checked : CheckState.UnChecked; - _rbBorderStyle!.SelectedItem = (int)((Border)AdornmentToEdit).LineStyle; + _osBorderStyle!.Value = ((Border)AdornmentToEdit).LineStyle; _ckbGradient!.CheckedState = ((Border)AdornmentToEdit).Settings.FastHasFlags (BorderSettings.Gradient) ? CheckState.Checked : CheckState.UnChecked; } private void BorderEditor_Initialized (object? sender, EventArgs e) { - List borderStyleEnum = Enum.GetValues (typeof (LineStyle)).Cast ().ToList (); - - _rbBorderStyle = new () + _osBorderStyle = new () { X = 0, - Y = Pos.Bottom (SubViews.ToArray() [^1]), + Y = Pos.Bottom (SubViews.ToArray () [^1]), Width = Dim.Fill (), - SelectedItem = (int)(((Border)AdornmentToEdit!)?.LineStyle ?? LineStyle.None), + Value = ((Border)AdornmentToEdit!)?.LineStyle ?? LineStyle.None, BorderStyle = LineStyle.Single, Title = "Border St_yle", SuperViewRendersLineCanvas = true, - RadioLabels = borderStyleEnum.Select (style => style.ToString ()).ToArray () }; - Add (_rbBorderStyle); + Add (_osBorderStyle); - _rbBorderStyle.SelectedItemChanged += OnRbBorderStyleOnSelectedItemChanged; + _osBorderStyle.ValueChanged += OnRbBorderStyleOnValueChanged; _ckbTitle = new () { X = 0, - Y = Pos.Bottom (_rbBorderStyle), + Y = Pos.Bottom (_osBorderStyle), CheckedState = CheckState.Checked, SuperViewRendersLineCanvas = true, @@ -73,10 +70,14 @@ public class BorderEditor : AdornmentEditor return; - void OnRbBorderStyleOnSelectedItemChanged (object? s, SelectedItemChangedArgs args) + void OnRbBorderStyleOnValueChanged (object? s, EventArgs args) { LineStyle prevBorderStyle = AdornmentToEdit!.BorderStyle; - ((Border)AdornmentToEdit).LineStyle = (LineStyle)args.SelectedItem!; + + if (args.Value is { }) + { + ((Border)AdornmentToEdit).LineStyle = (LineStyle)args.Value; + } if (((Border)AdornmentToEdit).LineStyle == LineStyle.None) { diff --git a/Examples/UICatalog/Scenarios/EditorsAndHelpers/DimEditor.cs b/Examples/UICatalog/Scenarios/EditorsAndHelpers/DimEditor.cs index 37007997d..ff372ecc7 100644 --- a/Examples/UICatalog/Scenarios/EditorsAndHelpers/DimEditor.cs +++ b/Examples/UICatalog/Scenarios/EditorsAndHelpers/DimEditor.cs @@ -18,7 +18,7 @@ public class DimEditor : EditorBase } private int _value; - private RadioGroup? _dimRadioGroup; + private OptionSelector? _dimOptionSelector; private TextField? _valueEdit; /// @@ -44,7 +44,7 @@ public class DimEditor : EditorBase try { - _dimRadioGroup!.SelectedItem = _dimNames.IndexOf (_dimNames.First (s => dim!.ToString ().StartsWith (s))); + _dimOptionSelector!.Value = _dimNames.IndexOf (_dimNames.First (s => dim!.ToString ().StartsWith (s))); } catch (InvalidOperationException e) { @@ -92,13 +92,13 @@ public class DimEditor : EditorBase Text = $"{Title}:" }; Add (label); - _dimRadioGroup = new () { X = 0, Y = Pos.Bottom (label), RadioLabels = _radioItems }; - _dimRadioGroup.SelectedItemChanged += OnRadioGroupOnSelectedItemChanged; + _dimOptionSelector = new () { X = 0, Y = Pos.Bottom (label), Labels = _optionLabels }; + _dimOptionSelector.ValueChanged += OnOptionSelectorOnValueChanged; _valueEdit = new () { X = Pos.Right (label) + 1, Y = 0, - Width = Dim.Func (_ => _radioItems.Max (i => i.GetColumns ()) - label.Frame.Width + 1), + Width = Dim.Func (_ => _optionLabels.Max (i => i.GetColumns ()) - label.Frame.Width + 1), Text = $"{_value}" }; @@ -117,15 +117,15 @@ public class DimEditor : EditorBase }; Add (_valueEdit); - Add (_dimRadioGroup); + Add (_dimOptionSelector); } - private void OnRadioGroupOnSelectedItemChanged (object? s, SelectedItemChangedArgs selected) { DimChanged (); } + private void OnOptionSelectorOnValueChanged (object? s, EventArgs selected) { DimChanged (); } // These need to have same order private readonly List _dimNames = ["Absolute", "Auto", "Fill", "Func", "Percent",]; - private readonly string [] _radioItems = ["Absolute(n)", "Auto", "Fill(n)", "Func(()=>n)", "Percent(n)",]; + private readonly string [] _optionLabels = ["Absolute(n)", "Auto", "Fill(n)", "Func(()=>n)", "Percent(n)",]; private void DimChanged () { @@ -136,7 +136,7 @@ public class DimEditor : EditorBase try { - Dim? dim = _dimRadioGroup!.SelectedItem switch + Dim? dim = _dimOptionSelector!.Value switch { 0 => Dim.Absolute (_value), 1 => Dim.Auto (), diff --git a/Examples/UICatalog/Scenarios/EditorsAndHelpers/MarginEditor.cs b/Examples/UICatalog/Scenarios/EditorsAndHelpers/MarginEditor.cs index 9bcf2d213..7d5d0f254 100644 --- a/Examples/UICatalog/Scenarios/EditorsAndHelpers/MarginEditor.cs +++ b/Examples/UICatalog/Scenarios/EditorsAndHelpers/MarginEditor.cs @@ -12,7 +12,7 @@ public class MarginEditor : AdornmentEditor AdornmentChanged += MarginEditor_AdornmentChanged; } - private RadioGroup? _rgShadow; + private OptionSelector? _optionsShadow; private FlagSelector? _flagSelectorTransparent; @@ -20,18 +20,18 @@ public class MarginEditor : AdornmentEditor { if (AdornmentToEdit is { }) { - _rgShadow!.SelectedItem = (int)((Margin)AdornmentToEdit).ShadowStyle; + _optionsShadow!.Value = ((Margin)AdornmentToEdit).ShadowStyle; } if (AdornmentToEdit is { }) { - _flagSelectorTransparent!.Value = (uint)((Margin)AdornmentToEdit).ViewportSettings; + _flagSelectorTransparent!.Value = (int)((Margin)AdornmentToEdit).ViewportSettings; } } private void MarginEditor_Initialized (object? sender, EventArgs e) { - _rgShadow = new RadioGroup + _optionsShadow = new () { X = 0, Y = Pos.Bottom (SubViews.ElementAt(SubViews.Count-1)), @@ -39,44 +39,36 @@ public class MarginEditor : AdornmentEditor SuperViewRendersLineCanvas = true, Title = "_Shadow", BorderStyle = LineStyle.Single, - RadioLabels = Enum.GetNames (typeof (ShadowStyle)), + AssignHotKeys = true }; if (AdornmentToEdit is { }) { - _rgShadow.SelectedItem = (int)((Margin)AdornmentToEdit).ShadowStyle; + _optionsShadow.Value = ((Margin)AdornmentToEdit).ShadowStyle; } - _rgShadow.SelectedItemChanged += (_, args) => - { - ((Margin)AdornmentToEdit!).ShadowStyle = (ShadowStyle)args.SelectedItem!; - }; + _optionsShadow.ValueChanged += (_, args) => ((Margin)AdornmentToEdit!).ShadowStyle = args.Value!.Value; - Add (_rgShadow); + Add (_optionsShadow); - var flags = new Dictionary () - { - { (uint)Terminal.Gui.ViewBase.ViewportSettingsFlags.Transparent, "Transparent" }, - { (uint)Terminal.Gui.ViewBase.ViewportSettingsFlags.TransparentMouse, "TransparentMouse" } - }; - - _flagSelectorTransparent = new FlagSelector () + _flagSelectorTransparent = new FlagSelector () { X = 0, - Y = Pos.Bottom (_rgShadow), + Y = Pos.Bottom (_optionsShadow), SuperViewRendersLineCanvas = true, Title = "_ViewportSettings", BorderStyle = LineStyle.Single, }; - _flagSelectorTransparent.SetFlags(flags.AsReadOnly ()); - + _flagSelectorTransparent.Values = [(int)ViewportSettingsFlags.Transparent, (int)ViewportSettingsFlags.TransparentMouse]; + _flagSelectorTransparent.Labels = ["Transparent", "TransparentMouse"]; + _flagSelectorTransparent.AssignHotKeys = true; Add (_flagSelectorTransparent); if (AdornmentToEdit is { }) { - _flagSelectorTransparent.Value = (uint)((Margin)AdornmentToEdit).ViewportSettings; + _flagSelectorTransparent.Value = (int)((Margin)AdornmentToEdit).ViewportSettings; } _flagSelectorTransparent.ValueChanged += (_, args) => diff --git a/Examples/UICatalog/Scenarios/EditorsAndHelpers/PosEditor.cs b/Examples/UICatalog/Scenarios/EditorsAndHelpers/PosEditor.cs index 012b2409e..45f0ab950 100644 --- a/Examples/UICatalog/Scenarios/EditorsAndHelpers/PosEditor.cs +++ b/Examples/UICatalog/Scenarios/EditorsAndHelpers/PosEditor.cs @@ -19,7 +19,7 @@ public class PosEditor : EditorBase } private int _value; - private RadioGroup? _posRadioGroup; + private OptionSelector? _posOptionSelector; private TextField? _valueEdit; protected override void OnUpdateLayoutSettings () @@ -44,7 +44,7 @@ public class PosEditor : EditorBase try { - _posRadioGroup!.SelectedItem = _posNames.IndexOf (_posNames.First (s => pos.ToString ().Contains (s))); + _posOptionSelector!.Value = _posNames.IndexOf (_posNames.First (s => pos.ToString ().Contains (s))); } catch (InvalidOperationException e) { @@ -91,14 +91,14 @@ public class PosEditor : EditorBase Text = $"{Title}:" }; Add (label); - _posRadioGroup = new () { X = 0, Y = Pos.Bottom (label), RadioLabels = _radioItems }; - _posRadioGroup.SelectedItemChanged += OnRadioGroupOnSelectedItemChanged; + _posOptionSelector = new () { X = 0, Y = Pos.Bottom (label), Labels = _optionLabels }; + _posOptionSelector.ValueChanged += OnOptionSelectorOnValueChanged; _valueEdit = new () { X = Pos.Right (label) + 1, Y = 0, - Width = Dim.Func (_ => _radioItems.Max (i => i.GetColumns ()) - label.Frame.Width + 1), + Width = Dim.Func (_ => _optionLabels.Max (i => i.GetColumns ()) - label.Frame.Width + 1), Text = $"{_value}" }; @@ -118,14 +118,14 @@ public class PosEditor : EditorBase }; Add (_valueEdit); - Add (_posRadioGroup); + Add (_posOptionSelector); } - private void OnRadioGroupOnSelectedItemChanged (object? s, SelectedItemChangedArgs selected) { PosChanged (); } + private void OnOptionSelectorOnValueChanged (object? s, EventArgs selected) { PosChanged (); } // These need to have same order private readonly List _posNames = ["Absolute", "Align", "AnchorEnd", "Center", "Func", "Percent"]; - private readonly string [] _radioItems = ["Absolute(n)", "Align", "AnchorEnd", "Center", "Func(()=>n)", "Percent(n)"]; + private readonly string [] _optionLabels = ["Absolute(n)", "Align", "AnchorEnd", "Center", "Func(()=>n)", "Percent(n)"]; private void PosChanged () { @@ -136,7 +136,7 @@ public class PosEditor : EditorBase try { - Pos? pos = _posRadioGroup!.SelectedItem switch + Pos? pos = _posOptionSelector!.Value switch { 0 => Pos.Absolute (_value), 1 => Pos.Align (Alignment.Start), diff --git a/Examples/UICatalog/Scenarios/EditorsAndHelpers/ViewPropertiesEditor.cs b/Examples/UICatalog/Scenarios/EditorsAndHelpers/ViewPropertiesEditor.cs index f8e77afaa..cfca9f433 100644 --- a/Examples/UICatalog/Scenarios/EditorsAndHelpers/ViewPropertiesEditor.cs +++ b/Examples/UICatalog/Scenarios/EditorsAndHelpers/ViewPropertiesEditor.cs @@ -6,7 +6,7 @@ public class ViewPropertiesEditor : EditorBase { private CheckBox? _canFocusCheckBox; private CheckBox? _enabledCheckBox; - private RadioGroup? _orientation; + private OptionSelector? _orientationOptionSelector; private TextView? _text; /// @@ -48,24 +48,23 @@ public class ViewPropertiesEditor : EditorBase Label label = new () { X = Pos.Right (_enabledCheckBox) + 1, Y = Pos.Top (_enabledCheckBox), Text = "Orientation:" }; - _orientation = new () + _orientationOptionSelector = new () { X = Pos.Right (label) + 1, Y = Pos.Top (label), - RadioLabels = new [] { "Horizontal", "Vertical" }, Orientation = Orientation.Horizontal }; - _orientation.SelectedItemChanged += (s, selected) => + _orientationOptionSelector.ValueChanged += (s, selected) => { if (ViewToEdit is IOrientation orientatedView) { - orientatedView.Orientation = (Orientation)_orientation.SelectedItem!; + orientatedView.Orientation = _orientationOptionSelector.Value!.Value; } }; - Add (label, _orientation); + Add (label, _orientationOptionSelector); - label = new () { X = 0, Y = Pos.Bottom (_orientation), Text = "Text:" }; + label = new () { X = 0, Y = Pos.Bottom (_orientationOptionSelector), Text = "Text:" }; _text = new () { @@ -114,12 +113,12 @@ public class ViewPropertiesEditor : EditorBase if (ViewToEdit is IOrientation orientatedView) { - _orientation!.SelectedItem = (int)orientatedView.Orientation; - _orientation.Enabled = true; + _orientationOptionSelector!.Value = orientatedView.Orientation; + _orientationOptionSelector.Enabled = true; } else { - _orientation!.Enabled = false; + _orientationOptionSelector!.Enabled = false; } } } diff --git a/Examples/UICatalog/Scenarios/FileDialogExamples.cs b/Examples/UICatalog/Scenarios/FileDialogExamples.cs index 49df84740..290e4a432 100644 --- a/Examples/UICatalog/Scenarios/FileDialogExamples.cs +++ b/Examples/UICatalog/Scenarios/FileDialogExamples.cs @@ -1,8 +1,4 @@ -using System; -using System.IO; -using System.IO.Abstractions; -using System.Linq; -using System.Text; +using System.IO.Abstractions; namespace UICatalog.Scenarios; @@ -20,10 +16,10 @@ public class FileDialogExamples : Scenario private CheckBox _cbMustExist; private CheckBox _cbShowTreeBranchLines; private CheckBox _cbUseColors; - private RadioGroup _rgAllowedTypes; - private RadioGroup _rgCaption; - private RadioGroup _rgIcons; - private RadioGroup _rgOpenMode; + private OptionSelector _osAllowedTypes; + private OptionSelector _osCaption; + private OptionSelector _osIcons; + private OptionSelector _osOpenMode; private TextField _tbCancelButton; private TextField _tbOkButton; @@ -34,28 +30,29 @@ public class FileDialogExamples : Scenario var x = 1; var win = new Window { Title = GetQuitKeyAndName () }; - _cbMustExist = new CheckBox { CheckedState = CheckState.Checked, Y = y++, X = x, Text = "Must E_xist" }; + _cbMustExist = new () { CheckedState = CheckState.Checked, Y = y++, X = x, Text = "Must E_xist" }; win.Add (_cbMustExist); - _cbUseColors = new CheckBox { CheckedState = FileDialogStyle.DefaultUseColors ? CheckState.Checked : CheckState.UnChecked, Y = y++, X = x, Text = "_Use Colors" }; + _cbUseColors = new () + { CheckedState = FileDialogStyle.DefaultUseColors ? CheckState.Checked : CheckState.UnChecked, Y = y++, X = x, Text = "_Use Colors" }; win.Add (_cbUseColors); - _cbCaseSensitive = new CheckBox { CheckedState = CheckState.UnChecked, Y = y++, X = x, Text = "_Case Sensitive Search" }; + _cbCaseSensitive = new () { CheckedState = CheckState.UnChecked, Y = y++, X = x, Text = "_Case Sensitive Search" }; win.Add (_cbCaseSensitive); - _cbAllowMultipleSelection = new CheckBox { CheckedState = CheckState.UnChecked, Y = y++, X = x, Text = "_Multiple" }; + _cbAllowMultipleSelection = new () { CheckedState = CheckState.UnChecked, Y = y++, X = x, Text = "_Multiple" }; win.Add (_cbAllowMultipleSelection); - _cbShowTreeBranchLines = new CheckBox { CheckedState = CheckState.Checked, Y = y++, X = x, Text = "Tree Branch _Lines" }; + _cbShowTreeBranchLines = new () { CheckedState = CheckState.Checked, Y = y++, X = x, Text = "Tree Branch _Lines" }; win.Add (_cbShowTreeBranchLines); - _cbAlwaysTableShowHeaders = new CheckBox { CheckedState = CheckState.Checked, Y = y++, X = x, Text = "Always Show _Headers" }; + _cbAlwaysTableShowHeaders = new () { CheckedState = CheckState.Checked, Y = y++, X = x, Text = "Always Show _Headers" }; win.Add (_cbAlwaysTableShowHeaders); - _cbDrivesOnlyInTree = new CheckBox { CheckedState = CheckState.UnChecked, Y = y++, X = x, Text = "Only Show _Drives" }; + _cbDrivesOnlyInTree = new () { CheckedState = CheckState.UnChecked, Y = y++, X = x, Text = "Only Show _Drives" }; win.Add (_cbDrivesOnlyInTree); - _cbPreserveFilenameOnDirectoryChanges = new CheckBox { CheckedState = CheckState.UnChecked, Y = y++, X = x, Text = "Preserve Filename" }; + _cbPreserveFilenameOnDirectoryChanges = new () { CheckedState = CheckState.UnChecked, Y = y++, X = x, Text = "Preserve Filename" }; win.Add (_cbPreserveFilenameOnDirectoryChanges); y = 0; @@ -66,9 +63,9 @@ public class FileDialogExamples : Scenario ); win.Add (new Label { X = x++, Y = y++, Text = "Caption" }); - _rgCaption = new RadioGroup { X = x, Y = y }; - _rgCaption.RadioLabels = new [] { "_Ok", "O_pen", "_Save" }; - win.Add (_rgCaption); + _osCaption = new () { X = x, Y = y }; + _osCaption.Labels = ["_Ok", "O_pen", "_Save"]; + win.Add (_osCaption); y = 0; x = 34; @@ -78,9 +75,9 @@ public class FileDialogExamples : Scenario ); win.Add (new Label { X = x++, Y = y++, Text = "OpenMode" }); - _rgOpenMode = new RadioGroup { X = x, Y = y }; - _rgOpenMode.RadioLabels = new [] { "_File", "D_irectory", "_Mixed" }; - win.Add (_rgOpenMode); + _osOpenMode = new () { X = x, Y = y }; + _osOpenMode.Labels = ["_File", "D_irectory", "_Mixed"]; + win.Add (_osOpenMode); y = 0; x = 48; @@ -90,9 +87,9 @@ public class FileDialogExamples : Scenario ); win.Add (new Label { X = x++, Y = y++, Text = "Icons" }); - _rgIcons = new RadioGroup { X = x, Y = y }; - _rgIcons.RadioLabels = new [] { "_None", "_Unicode", "Nerd_*" }; - win.Add (_rgIcons); + _osIcons = new () { X = x, Y = y }; + _osIcons.Labels = ["_None", "_Unicode", "Nerd_*"]; + win.Add (_osIcons); win.Add (new Label { Y = Pos.AnchorEnd (2), Text = "* Requires installing Nerd fonts" }); win.Add (new Label { Y = Pos.AnchorEnd (1), Text = " (see: https://github.com/devblackops/Terminal-Icons)" }); @@ -105,9 +102,9 @@ public class FileDialogExamples : Scenario ); win.Add (new Label { X = x++, Y = y++, Text = "Allowed" }); - _rgAllowedTypes = new RadioGroup { X = x, Y = y }; - _rgAllowedTypes.RadioLabels = new [] { "An_y", "Cs_v (Recommended)", "Csv (S_trict)" }; - win.Add (_rgAllowedTypes); + _osAllowedTypes = new () { X = x, Y = y }; + _osAllowedTypes.Labels = ["An_y", "Cs_v (Recommended)", "Csv (S_trict)"]; + win.Add (_osAllowedTypes); y = 5; x = 45; @@ -118,31 +115,31 @@ public class FileDialogExamples : Scenario win.Add (new Label { X = x++, Y = y++, Text = "Buttons" }); win.Add (new Label { X = x, Y = y++, Text = "O_k Text:" }); - _tbOkButton = new TextField { X = x, Y = y++, Width = 12 }; + _tbOkButton = new () { X = x, Y = y++, Width = 12 }; win.Add (_tbOkButton); win.Add (new Label { X = x, Y = y++, Text = "_Cancel Text:" }); - _tbCancelButton = new TextField { X = x, Y = y++, Width = 12 }; + _tbCancelButton = new () { X = x, Y = y++, Width = 12 }; win.Add (_tbCancelButton); - _cbFlipButtonOrder = new CheckBox { X = x, Y = y++, Text = "Flip Ord_er" }; + _cbFlipButtonOrder = new () { X = x, Y = y++, Text = "Flip Ord_er" }; win.Add (_cbFlipButtonOrder); var btn = new Button { X = 1, Y = 9, IsDefault = true, Text = "Run Dialog" }; win.Accepting += (s, e) => - { - try - { - CreateDialog (); - } - catch (Exception ex) - { - MessageBox.ErrorQuery ("Error", ex.ToString (), "_Ok"); - } - finally - { - e.Handled = true; - } - }; + { + try + { + CreateDialog (); + } + catch (Exception ex) + { + MessageBox.ErrorQuery ("Error", ex.ToString (), "_Ok"); + } + finally + { + e.Handled = true; + } + }; win.Add (btn); Application.Run (win); @@ -164,112 +161,115 @@ public class FileDialogExamples : Scenario private void CreateDialog () { - var fd = new FileDialog + if (_osOpenMode.Value is { }) { - OpenMode = Enum.Parse ( - _rgOpenMode.RadioLabels - .Select (l => TextFormatter.FindHotKey (l, _rgOpenMode.HotKeySpecifier, out int hotPos, out Key _) - - // Remove the hotkey specifier at the found position - ? TextFormatter.RemoveHotKeySpecifier (l, hotPos, _rgOpenMode.HotKeySpecifier) - - // No hotkey found, return the label as is - : l) - .ToArray () [_rgOpenMode.SelectedItem] - ), - MustExist = _cbMustExist.CheckedState == CheckState.Checked, - AllowsMultipleSelection = _cbAllowMultipleSelection.CheckedState == CheckState.Checked - }; - - fd.Style.OkButtonText = _rgCaption.RadioLabels.Select (l => TextFormatter.RemoveHotKeySpecifier(l, 0, _rgCaption.HotKeySpecifier)).ToArray() [_rgCaption.SelectedItem]; - - // If Save style dialog then give them an overwrite prompt - if (_rgCaption.SelectedItem == 2) - { - fd.FilesSelected += ConfirmOverwrite; - } - - fd.Style.IconProvider.UseUnicodeCharacters = _rgIcons.SelectedItem == 1; - fd.Style.IconProvider.UseNerdIcons = _rgIcons.SelectedItem == 2; - - if (_cbCaseSensitive.CheckedState == CheckState.Checked) - { - fd.SearchMatcher = new CaseSensitiveSearchMatcher (); - } - - fd.Style.UseColors = _cbUseColors.CheckedState == CheckState.Checked; - - fd.Style.TreeStyle.ShowBranchLines = _cbShowTreeBranchLines.CheckedState == CheckState.Checked; - fd.Style.TableStyle.AlwaysShowHeaders = _cbAlwaysTableShowHeaders.CheckedState == CheckState.Checked; - - IDirectoryInfoFactory dirInfoFactory = new FileSystem ().DirectoryInfo; - - if (_cbDrivesOnlyInTree.CheckedState == CheckState.Checked) - { - fd.Style.TreeRootGetter = () => { return Environment.GetLogicalDrives ().ToDictionary (dirInfoFactory.New, k => k); }; - } - - fd.Style.PreserveFilenameOnDirectoryChanges = _cbPreserveFilenameOnDirectoryChanges.CheckedState == CheckState.Checked; - - - if (_rgAllowedTypes.SelectedItem > 0) - { - fd.AllowedTypes.Add (new AllowedType ("Data File", ".csv", ".tsv")); - - if (_rgAllowedTypes.SelectedItem == 1) + var fd = new FileDialog { - fd.AllowedTypes.Insert (1, new AllowedTypeAny ()); + OpenMode = Enum.Parse ( + _osOpenMode.Labels + .Select (l => TextFormatter.FindHotKey (l, _osOpenMode.HotKeySpecifier, out int hotPos, out Key _) + + // Remove the hotkey specifier at the found position + ? TextFormatter.RemoveHotKeySpecifier (l, hotPos, _osOpenMode.HotKeySpecifier) + + // No hotkey found, return the label as is + : l) + .ToArray () [_osOpenMode.Value.Value] + ), + MustExist = _cbMustExist.CheckedState == CheckState.Checked, + AllowsMultipleSelection = _cbAllowMultipleSelection.CheckedState == CheckState.Checked + }; + + fd.Style.OkButtonText = + _osCaption.Labels.Select (l => TextFormatter.RemoveHotKeySpecifier (l, 0, _osCaption.HotKeySpecifier)).ToArray () + [_osCaption.Value!.Value]; + + // If Save style dialog then give them an overwrite prompt + if (_osCaption.Value == 2) + { + fd.FilesSelected += ConfirmOverwrite; } - } - if (!string.IsNullOrWhiteSpace (_tbOkButton.Text)) - { - fd.Style.OkButtonText = _tbOkButton.Text; - } + fd.Style.IconProvider.UseUnicodeCharacters = _osIcons.Value == 1; + fd.Style.IconProvider.UseNerdIcons = _osIcons.Value == 2; - if (!string.IsNullOrWhiteSpace (_tbCancelButton.Text)) - { - fd.Style.CancelButtonText = _tbCancelButton.Text; - } + if (_cbCaseSensitive.CheckedState == CheckState.Checked) + { + fd.SearchMatcher = new CaseSensitiveSearchMatcher (); + } - if (_cbFlipButtonOrder.CheckedState == CheckState.Checked) - { - fd.Style.FlipOkCancelButtonLayoutOrder = true; - } + fd.Style.UseColors = _cbUseColors.CheckedState == CheckState.Checked; - Application.Run (fd); + fd.Style.TreeStyle.ShowBranchLines = _cbShowTreeBranchLines.CheckedState == CheckState.Checked; + fd.Style.TableStyle.AlwaysShowHeaders = _cbAlwaysTableShowHeaders.CheckedState == CheckState.Checked; - var canceled = fd.Canceled; - var multiSelected = fd.MultiSelected; - var path = fd.Path; + IDirectoryInfoFactory dirInfoFactory = new FileSystem ().DirectoryInfo; - // This needs to be disposed before opening other toplevel - fd.Dispose (); + if (_cbDrivesOnlyInTree.CheckedState == CheckState.Checked) + { + fd.Style.TreeRootGetter = () => { return Environment.GetLogicalDrives ().ToDictionary (dirInfoFactory.New, k => k); }; + } - if (canceled) - { - MessageBox.Query ( - "Canceled", - "You canceled navigation and did not pick anything", - "Ok" - ); + fd.Style.PreserveFilenameOnDirectoryChanges = _cbPreserveFilenameOnDirectoryChanges.CheckedState == CheckState.Checked; - } - else if (_cbAllowMultipleSelection.CheckedState == CheckState.Checked) - { - MessageBox.Query ( - "Chosen!", - "You chose:" + Environment.NewLine + string.Join (Environment.NewLine, multiSelected.Select (m => m)), - "Ok" - ); - } - else - { - MessageBox.Query ( - "Chosen!", - "You chose:" + Environment.NewLine + path, - "Ok" - ); + if (_osAllowedTypes.Value > 0) + { + fd.AllowedTypes.Add (new AllowedType ("Data File", ".csv", ".tsv")); + + if (_osAllowedTypes.Value == 1) + { + fd.AllowedTypes.Insert (1, new AllowedTypeAny ()); + } + } + + if (!string.IsNullOrWhiteSpace (_tbOkButton.Text)) + { + fd.Style.OkButtonText = _tbOkButton.Text; + } + + if (!string.IsNullOrWhiteSpace (_tbCancelButton.Text)) + { + fd.Style.CancelButtonText = _tbCancelButton.Text; + } + + if (_cbFlipButtonOrder.CheckedState == CheckState.Checked) + { + fd.Style.FlipOkCancelButtonLayoutOrder = true; + } + + Application.Run (fd); + + bool canceled = fd.Canceled; + IReadOnlyList multiSelected = fd.MultiSelected; + string path = fd.Path; + + // This needs to be disposed before opening other toplevel + fd.Dispose (); + + if (canceled) + { + MessageBox.Query ( + "Canceled", + "You canceled navigation and did not pick anything", + "Ok" + ); + } + else if (_cbAllowMultipleSelection.CheckedState == CheckState.Checked) + { + MessageBox.Query ( + "Chosen!", + "You chose:" + Environment.NewLine + string.Join (Environment.NewLine, multiSelected.Select (m => m)), + "Ok" + ); + } + else + { + MessageBox.Query ( + "Chosen!", + "You chose:" + Environment.NewLine + path, + "Ok" + ); + } } } diff --git a/Examples/UICatalog/Scenarios/Images.cs b/Examples/UICatalog/Scenarios/Images.cs index 138e18eef..488f595a7 100644 --- a/Examples/UICatalog/Scenarios/Images.cs +++ b/Examples/UICatalog/Scenarios/Images.cs @@ -50,8 +50,8 @@ public class Images : Scenario private SixelToRender _fireSixel; private int _fireFrameCounter; private bool _isDisposed; - private RadioGroup _rgPaletteBuilder; - private RadioGroup _rgDistanceAlgorithm; + private OptionSelector _osPaletteBuilder; + private OptionSelector _osDistanceAlgorithm; private NumericUpDown _popularityThreshold; private SixelToRender _sixelImage; @@ -408,22 +408,22 @@ public class Images : Scenario Y = Pos.Bottom (_pxY) + 1 }; - _rgPaletteBuilder = new () + _osPaletteBuilder = new () { - RadioLabels = new [] - { + Labels = + [ "Popularity", "Median Cut" - }, + ], X = Pos.Right (_sixelView) + 2, Y = Pos.Bottom (l1), - SelectedItem = 1 + Value = 1 }; _popularityThreshold = new () { - X = Pos.Right (_rgPaletteBuilder) + 1, - Y = Pos.Top (_rgPaletteBuilder), + X = Pos.Right (_osPaletteBuilder) + 1, + Y = Pos.Top (_osPaletteBuilder), Value = 8 }; @@ -439,12 +439,12 @@ public class Images : Scenario Text = "Color Distance Algorithm", Width = Dim.Auto (), X = Pos.Right (_sixelView), - Y = Pos.Bottom (_rgPaletteBuilder) + 1 + Y = Pos.Bottom (_osPaletteBuilder) + 1 }; - _rgDistanceAlgorithm = new () + _osDistanceAlgorithm = new () { - RadioLabels = new [] + Labels = new [] { "Euclidian", "CIE76" @@ -458,10 +458,10 @@ public class Images : Scenario _sixelSupported.Add (lblPxY); _sixelSupported.Add (_pxY); _sixelSupported.Add (l1); - _sixelSupported.Add (_rgPaletteBuilder); + _sixelSupported.Add (_osPaletteBuilder); _sixelSupported.Add (l2); - _sixelSupported.Add (_rgDistanceAlgorithm); + _sixelSupported.Add (_osDistanceAlgorithm); _sixelSupported.Add (_popularityThreshold); _sixelSupported.Add (lblPopThreshold); @@ -470,7 +470,7 @@ public class Images : Scenario private IPaletteBuilder GetPaletteBuilder () { - switch (_rgPaletteBuilder.SelectedItem) + switch (_osPaletteBuilder.Value) { case 0: return new PopularityPaletteWithThreshold (GetDistanceAlgorithm (), _popularityThreshold.Value); case 1: return new MedianCutPaletteBuilder (GetDistanceAlgorithm ()); @@ -480,7 +480,7 @@ public class Images : Scenario private IColorDistance GetDistanceAlgorithm () { - switch (_rgDistanceAlgorithm.SelectedItem) + switch (_osDistanceAlgorithm.Value) { case 0: return new EuclideanColorDistance (); case 1: return new CIE76ColorDistance (); diff --git a/Examples/UICatalog/Scenarios/LineDrawing.cs b/Examples/UICatalog/Scenarios/LineDrawing.cs index 46f51dda7..cbc8dd27b 100644 --- a/Examples/UICatalog/Scenarios/LineDrawing.cs +++ b/Examples/UICatalog/Scenarios/LineDrawing.cs @@ -210,7 +210,7 @@ public class ToolsView : Window { private Button _addLayerBtn; private readonly AttributeView _colors; - private RadioGroup _stylePicker; + private OptionSelector _stylePicker; public Attribute CurrentColor { @@ -236,10 +236,16 @@ public class ToolsView : Window _stylePicker = new () { - X = 0, Y = Pos.Bottom (_colors), RadioLabels = Enum.GetNames (typeof (LineStyle)).ToArray () + X = 0, Y = Pos.Bottom (_colors), AssignHotKeys = true }; - _stylePicker.SelectedItemChanged += (s, a) => { SetStyle?.Invoke ((LineStyle)a.SelectedItem); }; - _stylePicker.SelectedItem = 1; + _stylePicker.ValueChanged += (s, a) => + { + if (a.Value is { }) + { + SetStyle?.Invoke ((LineStyle)a.Value); + } + }; + _stylePicker.Value = LineStyle.Single; _addLayerBtn = new () { Text = "New Layer", X = Pos.Center (), Y = Pos.Bottom (_stylePicker) }; diff --git a/Examples/UICatalog/Scenarios/MessageBoxes.cs b/Examples/UICatalog/Scenarios/MessageBoxes.cs index 71dde85e2..c8356a86a 100644 --- a/Examples/UICatalog/Scenarios/MessageBoxes.cs +++ b/Examples/UICatalog/Scenarios/MessageBoxes.cs @@ -182,18 +182,19 @@ public class MessageBoxes : Scenario }; frame.Add (label); - var styleRadioGroup = new RadioGroup + var styleOptionSelector = new OptionSelector () { - X = Pos.Right (label) + 1, - Y = Pos.Top (label), - RadioLabels = ["_Query", "_Error"], + X = Pos.Right (label) + 1, + Y = Pos.Top (label), + Labels = ["_Query", "_Error"], + Title = "Sty_le" }; - frame.Add (styleRadioGroup); + frame.Add (styleOptionSelector); label = new () { X = 0, - Y = Pos.Bottom (styleRadioGroup), + Y = Pos.Bottom (styleOptionSelector), Width = Dim.Width (label), Height = 1, @@ -202,7 +203,7 @@ public class MessageBoxes : Scenario }; var ckbWrapMessage = new CheckBox { - X = Pos.Right (label) + 1, Y = Pos.Bottom (styleRadioGroup), + X = Pos.Right (label) + 1, Y = Pos.Bottom (styleOptionSelector), CheckedState = CheckState.Checked, Text = "_Wrap Message", }; @@ -246,7 +247,7 @@ public class MessageBoxes : Scenario btns.Add ($"_{NumberToWords.Convert (i)}"); } - if (styleRadioGroup.SelectedItem == 0) + if (styleOptionSelector.Value == 0) { buttonPressedLabel.Text = $"{MessageBox.Query ( diff --git a/Examples/UICatalog/Scenarios/PosAlignDemo.cs b/Examples/UICatalog/Scenarios/PosAlignDemo.cs index 205a3c535..714155bff 100644 --- a/Examples/UICatalog/Scenarios/PosAlignDemo.cs +++ b/Examples/UICatalog/Scenarios/PosAlignDemo.cs @@ -1,14 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; - namespace UICatalog.Scenarios; [ScenarioMetadata ("Pos.Align", "Demonstrates Pos.Align")] [ScenarioCategory ("Layout")] public sealed class PosAlignDemo : Scenario { - private readonly Aligner _horizAligner = new () { AlignmentModes = AlignmentModes.StartToEnd | AlignmentModes.AddSpaceBetweenItems}; + private readonly Aligner _horizAligner = new () { AlignmentModes = AlignmentModes.StartToEnd | AlignmentModes.AddSpaceBetweenItems }; private int _leftMargin; private readonly Aligner _vertAligner = new () { AlignmentModes = AlignmentModes.StartToEnd | AlignmentModes.AddSpaceBetweenItems }; private int _topMargin; @@ -40,43 +36,42 @@ public sealed class PosAlignDemo : Scenario private void SetupControls (Window appWindow, Dimension dimension, Schemes scheme) { - RadioGroup alignRadioGroup = new () + OptionSelector alignOptionSelector = new () { - RadioLabels = Enum.GetNames (), - SchemeName = SchemeManager.SchemesToSchemeName (scheme), + SchemeName = SchemeManager.SchemesToSchemeName (scheme) }; if (dimension == Dimension.Width) { - alignRadioGroup.X = Pos.Align (_horizAligner.Alignment); - alignRadioGroup.Y = Pos.Center (); + alignOptionSelector.X = Pos.Align (_horizAligner.Alignment); + alignOptionSelector.Y = Pos.Center (); } else { - alignRadioGroup.X = Pos.Center (); - alignRadioGroup.Y = Pos.Align (_vertAligner.Alignment); + alignOptionSelector.X = Pos.Center (); + alignOptionSelector.Y = Pos.Align (_vertAligner.Alignment); } - alignRadioGroup.SelectedItemChanged += (s, e) => - { - if (dimension == Dimension.Width) - { - _horizAligner.Alignment = - (Alignment)Enum.Parse ( - typeof (Alignment), - alignRadioGroup.RadioLabels [alignRadioGroup.SelectedItem]); - UpdatePosAlignObjects (appWindow, dimension, _horizAligner); - } - else - { - _vertAligner.Alignment = - (Alignment)Enum.Parse ( - typeof (Alignment), - alignRadioGroup.RadioLabels [alignRadioGroup.SelectedItem]); - UpdatePosAlignObjects (appWindow, dimension, _vertAligner); - } - }; - appWindow.Add (alignRadioGroup); + alignOptionSelector.ValueChanged += (s, e) => + { + if (alignOptionSelector.Value is null) + { + return; + } + + if (dimension == Dimension.Width) + { + _horizAligner.Alignment = alignOptionSelector.Value.Value; + + UpdatePosAlignObjects (appWindow, dimension, _horizAligner); + } + else + { + _vertAligner.Alignment = alignOptionSelector.Value.Value; + UpdatePosAlignObjects (appWindow, dimension, _vertAligner); + } + }; + appWindow.Add (alignOptionSelector); CheckBox endToStartCheckBox = new () { @@ -88,32 +83,32 @@ public sealed class PosAlignDemo : Scenario { endToStartCheckBox.CheckedState = _horizAligner.AlignmentModes.HasFlag (AlignmentModes.EndToStart) ? CheckState.Checked : CheckState.UnChecked; endToStartCheckBox.X = Pos.Align (_horizAligner.Alignment); - endToStartCheckBox.Y = Pos.Top (alignRadioGroup); + endToStartCheckBox.Y = Pos.Top (alignOptionSelector); } else { endToStartCheckBox.CheckedState = _vertAligner.AlignmentModes.HasFlag (AlignmentModes.EndToStart) ? CheckState.Checked : CheckState.UnChecked; - endToStartCheckBox.X = Pos.Left (alignRadioGroup); + endToStartCheckBox.X = Pos.Left (alignOptionSelector); endToStartCheckBox.Y = Pos.Align (_vertAligner.Alignment); } endToStartCheckBox.CheckedStateChanging += (s, e) => - { - if (dimension == Dimension.Width) - { - _horizAligner.AlignmentModes = e.Result == CheckState.Checked - ? _horizAligner.AlignmentModes | AlignmentModes.EndToStart - : _horizAligner.AlignmentModes & ~AlignmentModes.EndToStart; - UpdatePosAlignObjects (appWindow, dimension, _horizAligner); - } - else - { - _vertAligner.AlignmentModes = e.Result == CheckState.Checked - ? _vertAligner.AlignmentModes | AlignmentModes.EndToStart - : _vertAligner.AlignmentModes & ~AlignmentModes.EndToStart; - UpdatePosAlignObjects (appWindow, dimension, _vertAligner); - } - }; + { + if (dimension == Dimension.Width) + { + _horizAligner.AlignmentModes = e.Result == CheckState.Checked + ? _horizAligner.AlignmentModes | AlignmentModes.EndToStart + : _horizAligner.AlignmentModes & ~AlignmentModes.EndToStart; + UpdatePosAlignObjects (appWindow, dimension, _horizAligner); + } + else + { + _vertAligner.AlignmentModes = e.Result == CheckState.Checked + ? _vertAligner.AlignmentModes | AlignmentModes.EndToStart + : _vertAligner.AlignmentModes & ~AlignmentModes.EndToStart; + UpdatePosAlignObjects (appWindow, dimension, _vertAligner); + } + }; appWindow.Add (endToStartCheckBox); CheckBox ignoreFirstOrLast = new () @@ -124,34 +119,35 @@ public sealed class PosAlignDemo : Scenario if (dimension == Dimension.Width) { - ignoreFirstOrLast.CheckedState = _horizAligner.AlignmentModes.HasFlag (AlignmentModes.IgnoreFirstOrLast) ? CheckState.Checked : CheckState.UnChecked; + ignoreFirstOrLast.CheckedState = + _horizAligner.AlignmentModes.HasFlag (AlignmentModes.IgnoreFirstOrLast) ? CheckState.Checked : CheckState.UnChecked; ignoreFirstOrLast.X = Pos.Align (_horizAligner.Alignment); - ignoreFirstOrLast.Y = Pos.Top (alignRadioGroup); + ignoreFirstOrLast.Y = Pos.Top (alignOptionSelector); } else { ignoreFirstOrLast.CheckedState = _vertAligner.AlignmentModes.HasFlag (AlignmentModes.IgnoreFirstOrLast) ? CheckState.Checked : CheckState.UnChecked; - ignoreFirstOrLast.X = Pos.Left (alignRadioGroup); + ignoreFirstOrLast.X = Pos.Left (alignOptionSelector); ignoreFirstOrLast.Y = Pos.Align (_vertAligner.Alignment); } ignoreFirstOrLast.CheckedStateChanging += (s, e) => - { - if (dimension == Dimension.Width) - { - _horizAligner.AlignmentModes = e.Result == CheckState.Checked - ? _horizAligner.AlignmentModes | AlignmentModes.IgnoreFirstOrLast - : _horizAligner.AlignmentModes & ~AlignmentModes.IgnoreFirstOrLast; - UpdatePosAlignObjects (appWindow, dimension, _horizAligner); - } - else - { - _vertAligner.AlignmentModes = e.Result == CheckState.Checked - ? _vertAligner.AlignmentModes | AlignmentModes.IgnoreFirstOrLast - : _vertAligner.AlignmentModes & ~AlignmentModes.IgnoreFirstOrLast; - UpdatePosAlignObjects (appWindow, dimension, _vertAligner); - } - }; + { + if (dimension == Dimension.Width) + { + _horizAligner.AlignmentModes = e.Result == CheckState.Checked + ? _horizAligner.AlignmentModes | AlignmentModes.IgnoreFirstOrLast + : _horizAligner.AlignmentModes & ~AlignmentModes.IgnoreFirstOrLast; + UpdatePosAlignObjects (appWindow, dimension, _horizAligner); + } + else + { + _vertAligner.AlignmentModes = e.Result == CheckState.Checked + ? _vertAligner.AlignmentModes | AlignmentModes.IgnoreFirstOrLast + : _vertAligner.AlignmentModes & ~AlignmentModes.IgnoreFirstOrLast; + UpdatePosAlignObjects (appWindow, dimension, _vertAligner); + } + }; appWindow.Add (ignoreFirstOrLast); CheckBox addSpacesBetweenItems = new () @@ -162,34 +158,40 @@ public sealed class PosAlignDemo : Scenario if (dimension == Dimension.Width) { - addSpacesBetweenItems.CheckedState = _horizAligner.AlignmentModes.HasFlag (AlignmentModes.AddSpaceBetweenItems) ? CheckState.Checked : CheckState.UnChecked; + addSpacesBetweenItems.CheckedState = + _horizAligner.AlignmentModes.HasFlag (AlignmentModes.AddSpaceBetweenItems) ? CheckState.Checked : CheckState.UnChecked; addSpacesBetweenItems.X = Pos.Align (_horizAligner.Alignment); - addSpacesBetweenItems.Y = Pos.Top (alignRadioGroup); + addSpacesBetweenItems.Y = Pos.Top (alignOptionSelector); } else { - addSpacesBetweenItems.CheckedState = _vertAligner.AlignmentModes.HasFlag (AlignmentModes.AddSpaceBetweenItems) ? CheckState.Checked : CheckState.UnChecked; - addSpacesBetweenItems.X = Pos.Left (alignRadioGroup); + addSpacesBetweenItems.CheckedState = + _vertAligner.AlignmentModes.HasFlag (AlignmentModes.AddSpaceBetweenItems) ? CheckState.Checked : CheckState.UnChecked; + addSpacesBetweenItems.X = Pos.Left (alignOptionSelector); addSpacesBetweenItems.Y = Pos.Align (_vertAligner.Alignment); } addSpacesBetweenItems.CheckedStateChanging += (s, e) => - { - if (dimension == Dimension.Width) - { - _horizAligner.AlignmentModes = e.Result == CheckState.Checked - ? _horizAligner.AlignmentModes | AlignmentModes.AddSpaceBetweenItems - : _horizAligner.AlignmentModes & ~AlignmentModes.AddSpaceBetweenItems; - UpdatePosAlignObjects (appWindow, dimension, _horizAligner); - } - else - { - _vertAligner.AlignmentModes = e.Result == CheckState.Checked - ? _vertAligner.AlignmentModes | AlignmentModes.AddSpaceBetweenItems - : _vertAligner.AlignmentModes & ~AlignmentModes.AddSpaceBetweenItems; - UpdatePosAlignObjects (appWindow, dimension, _vertAligner); - } - }; + { + if (dimension == Dimension.Width) + { + _horizAligner.AlignmentModes = e.Result == CheckState.Checked + ? _horizAligner.AlignmentModes + | AlignmentModes.AddSpaceBetweenItems + : _horizAligner.AlignmentModes + & ~AlignmentModes.AddSpaceBetweenItems; + UpdatePosAlignObjects (appWindow, dimension, _horizAligner); + } + else + { + _vertAligner.AlignmentModes = e.Result == CheckState.Checked + ? _vertAligner.AlignmentModes + | AlignmentModes.AddSpaceBetweenItems + : _vertAligner.AlignmentModes + & ~AlignmentModes.AddSpaceBetweenItems; + UpdatePosAlignObjects (appWindow, dimension, _vertAligner); + } + }; appWindow.Add (addSpacesBetweenItems); @@ -202,7 +204,7 @@ public sealed class PosAlignDemo : Scenario if (dimension == Dimension.Width) { margin.X = Pos.Align (_horizAligner.Alignment); - margin.Y = Pos.Top (alignRadioGroup); + margin.Y = Pos.Top (alignOptionSelector); } else { @@ -211,31 +213,31 @@ public sealed class PosAlignDemo : Scenario } margin.CheckedStateChanging += (s, e) => - { - if (dimension == Dimension.Width) - { - _leftMargin = e.Result == CheckState.Checked ? 1 : 0; - UpdatePosAlignObjects (appWindow, dimension, _horizAligner); - } - else - { - _topMargin = e.Result == CheckState.Checked ? 1 : 0; - UpdatePosAlignObjects (appWindow, dimension, _vertAligner); - } - }; + { + if (dimension == Dimension.Width) + { + _leftMargin = e.Result == CheckState.Checked ? 1 : 0; + UpdatePosAlignObjects (appWindow, dimension, _horizAligner); + } + else + { + _topMargin = e.Result == CheckState.Checked ? 1 : 0; + UpdatePosAlignObjects (appWindow, dimension, _vertAligner); + } + }; appWindow.Add (margin); List