From 34bef2c839b212f247c52d935ed35f7bea815675 Mon Sep 17 00:00:00 2001 From: dodexahedron Date: Fri, 16 Feb 2024 16:46:25 -0700 Subject: [PATCH] Fixes #3242 - Replaces simple null checks (#3248) * Replace all 342 `== null` with `is null` * Replace 354 `!= null` with `is { }` * Wrap these in conditionals since they break tests against Release configuration The members they depend on do not exist in Release configuration * Split these up and dispose properly This test needs to be revisited for several reasons at some point. * Fix release configuration tests * Declare interface these already support * Annotate constructor properly and use throw helper * Move class to its own file * Rename these files so they nest in the solution explorer * Make this a record type and remove now-redundant/illegal members * Reference passing to avoid some struct copies * Simplify this * Carry reference passing through as appropriate * Turn this into a record struct * Remove unused internal constructor and its test It was only used by that test. * Simplify this constructor * This should be a property * Simplify constructor * Simplify GetHashCode * Mark this ignored just in case * Missed a couple of opportunities for reference passing * record struct already does this by value * Remove unused class * Simplify the type initializer and Reset method * Implement INotifyCollectionChanged and IDictionary by delegating to ColorSchemes * Fix for reflection-based configuration * Make CI build happy by disambiguiating this attribute --- Terminal.Gui/Application.cs | 86 ++++----- Terminal.Gui/Clipboard/Clipboard.cs | 4 +- Terminal.Gui/Clipboard/ClipboardBase.cs | 4 +- .../Configuration/AttributeJsonConverter.cs | 4 +- .../Configuration/ColorJsonConverter.cs | 2 +- .../Configuration/ColorSchemeJsonConverter.cs | 2 +- Terminal.Gui/Configuration/ConfigProperty.cs | 12 +- .../Configuration/ConfigurationManager.cs | 16 +- .../Configuration/KeyCodeJsonConverter.cs | 2 +- Terminal.Gui/Configuration/Scope.cs | 2 +- .../Configuration/ScopeJsonConverter.cs | 10 +- Terminal.Gui/Configuration/SettingsScope.cs | 4 +- Terminal.Gui/Configuration/ThemeManager.cs | 2 +- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 4 +- .../ConsoleDrivers/ConsoleKeyMapping.cs | 24 +-- .../CursesDriver/CursesDriver.cs | 4 +- .../CursesDriver/UnixMainLoop.cs | 4 +- .../ConsoleDrivers/EscSeqUtils/EscSeqReq.cs | 14 +- .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 18 +- .../ConsoleDrivers/FakeDriver/FakeDriver.cs | 6 +- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 10 +- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 28 +-- Terminal.Gui/Drawing/Attribute.cs | 73 ++------ ...Extensions.cs => Color.ColorExtensions.cs} | 0 .../{ColorName.cs => Color.ColorName.cs} | 0 ...eption.cs => Color.ColorParseException.cs} | 0 Terminal.Gui/Drawing/ColorScheme.Colors.cs | 176 ++++++++++++++++++ Terminal.Gui/Drawing/ColorScheme.cs | 136 +------------- Terminal.Gui/Drawing/LineCanvas.cs | 10 +- Terminal.Gui/Drawing/Thickness.cs | 4 +- .../FileServices/DefaultFileOperations.cs | 2 +- .../FileServices/FileDialogHistory.cs | 8 +- Terminal.Gui/FileServices/FileDialogState.cs | 4 +- Terminal.Gui/Input/KeyBinding.cs | 2 +- Terminal.Gui/Input/Responder.cs | 2 +- Terminal.Gui/MainLoop.cs | 2 +- Terminal.Gui/RunState.cs | 2 +- Terminal.Gui/Terminal.Gui.csproj | 3 + .../Text/Autocomplete/PopupAutocomplete.cs | 16 +- Terminal.Gui/Text/StringExtensions.cs | 2 +- Terminal.Gui/Text/TextFormatter.cs | 16 +- Terminal.Gui/View/Adornment/Adornment.cs | 2 +- Terminal.Gui/View/Adornment/Border.cs | 6 +- Terminal.Gui/View/Adornment/Margin.cs | 2 +- Terminal.Gui/View/Adornment/Padding.cs | 2 +- Terminal.Gui/View/Layout/PosDim.cs | 6 +- Terminal.Gui/View/Layout/ViewLayout.cs | 38 ++-- Terminal.Gui/View/View.cs | 10 +- Terminal.Gui/View/ViewDrawing.cs | 28 +-- Terminal.Gui/View/ViewKeyboard.cs | 14 +- Terminal.Gui/View/ViewMouse.cs | 2 +- Terminal.Gui/View/ViewSubViews.cs | 62 +++--- Terminal.Gui/View/ViewText.cs | 8 +- .../Views/AutocompleteFilepathContext.cs | 2 +- Terminal.Gui/Views/CheckBox.cs | 2 +- Terminal.Gui/Views/ComboBox.cs | 18 +- Terminal.Gui/Views/Dialog.cs | 4 +- Terminal.Gui/Views/FileDialog.cs | 42 ++--- Terminal.Gui/Views/FileDialogTableSource.cs | 2 +- Terminal.Gui/Views/GraphView/Series.cs | 4 +- Terminal.Gui/Views/HexView.cs | 4 +- Terminal.Gui/Views/Label.cs | 2 +- Terminal.Gui/Views/ListView.cs | 30 +-- Terminal.Gui/Views/Menu/ContextMenu.cs | 10 +- Terminal.Gui/Views/Menu/Menu.cs | 74 ++++---- Terminal.Gui/Views/Menu/MenuBar.cs | 112 +++++------ Terminal.Gui/Views/MessageBox.cs | 2 +- Terminal.Gui/Views/ProgressBar.cs | 2 +- Terminal.Gui/Views/RadioGroup.cs | 2 +- Terminal.Gui/Views/ScrollBarView.cs | 60 +++--- Terminal.Gui/Views/ScrollView.cs | 6 +- Terminal.Gui/Views/Slider.cs | 8 +- Terminal.Gui/Views/SpinnerView/SpinnerView.cs | 4 +- Terminal.Gui/Views/StatusBar.cs | 6 +- Terminal.Gui/Views/TabView.cs | 34 ++-- Terminal.Gui/Views/TableView/ColumnStyle.cs | 4 +- .../Views/TableView/ListTableSource.cs | 2 +- Terminal.Gui/Views/TableView/TableView.cs | 24 +-- .../Views/TableView/TreeTableSource.cs | 4 +- Terminal.Gui/Views/TextField.cs | 30 +-- Terminal.Gui/Views/TextValidateField.cs | 12 +- Terminal.Gui/Views/TextView.cs | 94 +++++----- Terminal.Gui/Views/TileView.cs | 6 +- Terminal.Gui/Views/Toplevel.cs | 64 +++---- Terminal.Gui/Views/ToplevelOverlapped.cs | 24 +-- Terminal.Gui/Views/TreeView/Branch.cs | 24 +-- Terminal.Gui/Views/TreeView/TreeView.cs | 46 ++--- Terminal.Gui/Views/Wizard/Wizard.cs | 24 +-- Terminal.Gui/Views/Wizard/WizardStep.cs | 4 +- UnitTests/Drawing/AttributeTests.cs | 13 -- UnitTests/Input/ResponderTests.cs | 15 +- UnitTests/View/Layout/DimTests.cs | 103 +++++----- UnitTests/View/ViewTests.cs | 8 + UnitTests/Views/WindowTests.cs | 155 ++++++++------- 94 files changed, 1020 insertions(+), 966 deletions(-) rename Terminal.Gui/Drawing/{ColorExtensions.cs => Color.ColorExtensions.cs} (100%) rename Terminal.Gui/Drawing/{ColorName.cs => Color.ColorName.cs} (100%) rename Terminal.Gui/Drawing/{ColorParseException.cs => Color.ColorParseException.cs} (100%) create mode 100644 Terminal.Gui/Drawing/ColorScheme.Colors.cs diff --git a/Terminal.Gui/Application.cs b/Terminal.Gui/Application.cs index cc39f6f03..46f2bc9ff 100644 --- a/Terminal.Gui/Application.cs +++ b/Terminal.Gui/Application.cs @@ -103,7 +103,7 @@ public static partial class Application EndAfterFirstIteration = false; // Driver stuff - if (Driver != null) + if (Driver is { }) { Driver.SizeChanged -= Driver_SizeChanged; Driver.KeyDown -= Driver_KeyDown; @@ -199,7 +199,7 @@ public static partial class Application bool calledViaRunT = false ) { - if (_initialized && driver == null) + if (_initialized && driver is null) { return; } @@ -216,7 +216,7 @@ public static partial class Application } // For UnitTests - if (driver != null) + if (driver is { }) { Driver = driver; } @@ -235,7 +235,7 @@ public static partial class Application ForceDriver = driverName; } - if (Driver == null) + if (Driver is null) { PlatformID p = Environment.OSVersion.Platform; @@ -255,7 +255,7 @@ public static partial class Application List drivers = GetDriverTypes (); Type driverType = drivers.FirstOrDefault (t => t.Name.ToLower () == ForceDriver.ToLower ()); - if (driverType != null) + if (driverType is { }) { Driver = (ConsoleDriver)Activator.CreateInstance (driverType); } @@ -377,12 +377,12 @@ public static partial class Application /// public static RunState Begin (Toplevel Toplevel) { - if (Toplevel == null) + if (Toplevel is null) { throw new ArgumentNullException (nameof (Toplevel)); } - if (Toplevel.IsOverlappedContainer && OverlappedTop != Toplevel && OverlappedTop != null) + if (Toplevel.IsOverlappedContainer && OverlappedTop != Toplevel && OverlappedTop is { }) { throw new InvalidOperationException ("Only one Overlapped Container is allowed."); } @@ -404,12 +404,12 @@ public static partial class Application // If Top was already initialized with Init, and Begin has never been called // Top was not added to the Toplevels Stack. It will thus never get disposed. // Clean it up here: - if (Top != null && Toplevel != Top && !_topLevels.Contains (Top)) + if (Top is { } && Toplevel != Top && !_topLevels.Contains (Top)) { Top.Dispose (); Top = null; } - else if (Top != null && Toplevel != Top && _topLevels.Contains (Top)) + else if (Top is { } && Toplevel != Top && _topLevels.Contains (Top)) { Top.OnLeave (Toplevel); } @@ -421,7 +421,7 @@ public static partial class Application var count = 1; var id = (_topLevels.Count + count).ToString (); - while (_topLevels.Count > 0 && _topLevels.FirstOrDefault (x => x.Id == id) != null) + while (_topLevels.Count > 0 && _topLevels.FirstOrDefault (x => x.Id == id) is { }) { count++; id = (_topLevels.Count + count).ToString (); @@ -435,7 +435,7 @@ public static partial class Application { Toplevel dup = _topLevels.FirstOrDefault (x => x.Id == Toplevel.Id); - if (dup == null) + if (dup is null) { _topLevels.Push (Toplevel); } @@ -447,7 +447,7 @@ public static partial class Application } } - if (Top == null || Toplevel.IsOverlappedContainer) + if (Top is null || Toplevel.IsOverlappedContainer) { Top = Toplevel; } @@ -474,7 +474,7 @@ public static partial class Application && Toplevel != OverlappedTop && Current?.Modal == true && !_topLevels.Peek ().Modal) - || (OverlappedTop != null && Toplevel != OverlappedTop && Current?.Running == false)) + || (OverlappedTop is { } && Toplevel != OverlappedTop && Current?.Running == false)) { refreshDriver = false; MoveCurrent (Toplevel); @@ -536,7 +536,7 @@ public static partial class Application { if (_initialized) { - if (Driver != null) + if (Driver is { }) { // Init() has been called and we have a driver, so just run the app. var top = new T (); @@ -629,7 +629,7 @@ public static partial class Application } catch (Exception error) { - if (errorHandler == null) + if (errorHandler is null) { throw; } @@ -767,12 +767,12 @@ public static partial class Application /// The state returned by the method. public static void RunLoop (RunState state) { - if (state == null) + if (state is null) { throw new ArgumentNullException (nameof (state)); } - if (state.Toplevel == null) + if (state.Toplevel is null) { throw new ObjectDisposedException ("state"); } @@ -885,7 +885,7 @@ public static partial class Application /// public static void RequestStop (Toplevel top = null) { - if (OverlappedTop == null || top == null || (OverlappedTop == null && top != null)) + if (OverlappedTop is null || top is null || (OverlappedTop is null && top is { })) { top = Current; } @@ -1011,12 +1011,12 @@ public static partial class Application /// The returned by the method. public static void End (RunState runState) { - if (runState == null) + if (runState is null) { throw new ArgumentNullException (nameof (runState)); } - if (OverlappedTop != null) + if (OverlappedTop is { }) { OverlappedTop.OnChildUnloaded (runState.Toplevel); } @@ -1044,7 +1044,7 @@ public static partial class Application // If there is a OverlappedTop that is not the RunState.Toplevel then runstate.TopLevel // is a child of MidTop and we should notify the OverlappedTop that it is closing - if (OverlappedTop != null && !runState.Toplevel.Modal && runState.Toplevel != OverlappedTop) + if (OverlappedTop is { } && !runState.Toplevel.Modal && runState.Toplevel != OverlappedTop) { OverlappedTop.OnChildClosed (runState.Toplevel); } @@ -1137,7 +1137,7 @@ public static partial class Application return null; } - if (_topLevels != null) + if (_topLevels is { }) { int count = _topLevels.Count; @@ -1169,11 +1169,11 @@ public static partial class Application private static View FindTopFromView (View view) { - View top = view?.SuperView != null && view?.SuperView != Top + View top = view?.SuperView is { } && view?.SuperView != Top ? view.SuperView : view; - while (top?.SuperView != null && top?.SuperView != Top) + while (top?.SuperView is { } && top?.SuperView != Top) { top = top.SuperView; } @@ -1247,10 +1247,10 @@ public static partial class Application return false; } - if ((OverlappedTop != null && top?.Modal == true && _topLevels.Peek () != top) - || (OverlappedTop != null && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop) - || (OverlappedTop != null && Current?.Modal == false && top != Current) - || (OverlappedTop != null && Current?.Modal == true && top == OverlappedTop)) + if ((OverlappedTop is { } && top?.Modal == true && _topLevels.Peek () != top) + || (OverlappedTop is { } && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop) + || (OverlappedTop is { } && Current?.Modal == false && top != Current) + || (OverlappedTop is { } && Current?.Modal == true && top == OverlappedTop)) { lock (_topLevels) { @@ -1333,7 +1333,7 @@ public static partial class Application /// View that will receive all mouse events until is invoked. public static void GrabMouse (View view) { - if (view == null) + if (view is null) { return; } @@ -1348,7 +1348,7 @@ public static partial class Application /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is. public static void UngrabMouse () { - if (MouseGrabView == null) + if (MouseGrabView is null) { return; } @@ -1362,7 +1362,7 @@ public static partial class Application private static bool OnGrabbingMouse (View view) { - if (view == null) + if (view is null) { return false; } @@ -1375,7 +1375,7 @@ public static partial class Application private static bool OnUnGrabbingMouse (View view) { - if (view == null) + if (view is null) { return false; } @@ -1388,7 +1388,7 @@ public static partial class Application private static void OnGrabbedMouse (View view) { - if (view == null) + if (view is null) { return; } @@ -1398,7 +1398,7 @@ public static partial class Application private static void OnUnGrabbedMouse (View view) { - if (view == null) + if (view is null) { return; } @@ -1433,7 +1433,7 @@ public static partial class Application var view = View.FindDeepestView (Current, a.MouseEvent.X, a.MouseEvent.Y, out int screenX, out int screenY); - if (view != null && view.WantContinuousButtonPressed) + if (view is { } && view.WantContinuousButtonPressed) { WantContinuousButtonPressedView = view; } @@ -1442,7 +1442,7 @@ public static partial class Application WantContinuousButtonPressedView = null; } - if (view != null) + if (view is { }) { a.MouseEvent.View = view; } @@ -1454,7 +1454,7 @@ public static partial class Application return; } - if (MouseGrabView != null) + if (MouseGrabView is { }) { // If the mouse is grabbed, send the event to the view that grabbed it. // The coordinates are relative to the Bounds of the view that grabbed the mouse. @@ -1487,7 +1487,7 @@ public static partial class Application } } - if ((view == null || view == OverlappedTop) + if ((view is null || view == OverlappedTop) && Current is { Modal: false } && OverlappedTop != null && a.MouseEvent.Flags != MouseFlags.ReportMousePosition @@ -1496,7 +1496,7 @@ public static partial class Application View top = FindDeepestTop (Top, a.MouseEvent.X, a.MouseEvent.Y, out _, out _); view = View.FindDeepestView (top, a.MouseEvent.X, a.MouseEvent.Y, out screenX, out screenY); - if (view != null && view != OverlappedTop && top != Current) + if (view is { } && view != OverlappedTop && top != Current) { MoveCurrent ((Toplevel)top); } @@ -1525,7 +1525,7 @@ public static partial class Application return false; } - if (view != null) + if (view is { }) { // Work inside-out (Padding, Border, Margin) // TODO: Debate whether inside-out or outside-in is the right strategy @@ -1551,7 +1551,7 @@ public static partial class Application View = view }; - if (_mouseEnteredView == null) + if (_mouseEnteredView is null) { _mouseEnteredView = view; view.OnMouseEnter (me); @@ -1603,7 +1603,7 @@ public static partial class Application View = view }; - if (_mouseEnteredView == null) + if (_mouseEnteredView is null) { _mouseEnteredView = view; view.OnMouseEnter (me); @@ -1784,7 +1784,7 @@ public static partial class Application keyEvent.Scope = KeyBindingScope.Application; bool? handled = view.OnInvokingKeyBindings (keyEvent); - if (handled != null && (bool)handled) + if (handled is { } && (bool)handled) { return true; } diff --git a/Terminal.Gui/Clipboard/Clipboard.cs b/Terminal.Gui/Clipboard/Clipboard.cs index 259663f3c..63c1cc40a 100644 --- a/Terminal.Gui/Clipboard/Clipboard.cs +++ b/Terminal.Gui/Clipboard/Clipboard.cs @@ -33,7 +33,7 @@ public static class Clipboard { string clipData = Application.Driver.Clipboard.GetClipboardData (); - if (clipData == null) + if (clipData is null) { // throw new InvalidOperationException ($"{Application.Driver.GetType ().Name}.GetClipboardData returned null instead of string.Empty"); clipData = string.Empty; @@ -55,7 +55,7 @@ public static class Clipboard { if (IsSupported) { - if (value == null) + if (value is null) { value = string.Empty; } diff --git a/Terminal.Gui/Clipboard/ClipboardBase.cs b/Terminal.Gui/Clipboard/ClipboardBase.cs index f5a26c641..8c01e9c43 100644 --- a/Terminal.Gui/Clipboard/ClipboardBase.cs +++ b/Terminal.Gui/Clipboard/ClipboardBase.cs @@ -17,7 +17,7 @@ public abstract class ClipboardBase : IClipboard { string result = GetClipboardDataImpl (); - if (result == null) + if (result is null) { return string.Empty; } @@ -35,7 +35,7 @@ public abstract class ClipboardBase : IClipboard /// Thrown if it was not possible to paste to the OS clipboard. public void SetClipboardData (string text) { - if (text == null) + if (text is null) { throw new ArgumentNullException (nameof (text)); } diff --git a/Terminal.Gui/Configuration/AttributeJsonConverter.cs b/Terminal.Gui/Configuration/AttributeJsonConverter.cs index 668dc0935..d1e922a64 100644 --- a/Terminal.Gui/Configuration/AttributeJsonConverter.cs +++ b/Terminal.Gui/Configuration/AttributeJsonConverter.cs @@ -13,7 +13,7 @@ internal class AttributeJsonConverter : JsonConverter { get { - if (_instance == null) + if (_instance is null) { _instance = new AttributeJsonConverter (); } @@ -37,7 +37,7 @@ internal class AttributeJsonConverter : JsonConverter { if (reader.TokenType == JsonTokenType.EndObject) { - if (foreground == null || background == null) + if (foreground is null || background is null) { throw new JsonException ("Both Foreground and Background colors must be provided."); } diff --git a/Terminal.Gui/Configuration/ColorJsonConverter.cs b/Terminal.Gui/Configuration/ColorJsonConverter.cs index e4b6551cd..91f77040c 100644 --- a/Terminal.Gui/Configuration/ColorJsonConverter.cs +++ b/Terminal.Gui/Configuration/ColorJsonConverter.cs @@ -13,7 +13,7 @@ internal class ColorJsonConverter : JsonConverter { get { - if (_instance == null) + if (_instance is null) { _instance = new ColorJsonConverter (); } diff --git a/Terminal.Gui/Configuration/ColorSchemeJsonConverter.cs b/Terminal.Gui/Configuration/ColorSchemeJsonConverter.cs index 6d28eb662..86f4a5f29 100644 --- a/Terminal.Gui/Configuration/ColorSchemeJsonConverter.cs +++ b/Terminal.Gui/Configuration/ColorSchemeJsonConverter.cs @@ -13,7 +13,7 @@ internal class ColorSchemeJsonConverter : JsonConverter { get { - if (instance == null) + if (instance is null) { instance = new ColorSchemeJsonConverter (); } diff --git a/Terminal.Gui/Configuration/ConfigProperty.cs b/Terminal.Gui/Configuration/ConfigProperty.cs index 717bf786c..2418268cf 100644 --- a/Terminal.Gui/Configuration/ConfigProperty.cs +++ b/Terminal.Gui/Configuration/ConfigProperty.cs @@ -35,11 +35,11 @@ public class ConfigProperty /// public bool Apply () { - if (PropertyValue != null) + if (PropertyValue is { }) { try { - if (PropertyInfo?.GetValue (null) != null) + if (PropertyInfo?.GetValue (null) is { }) { PropertyInfo?.SetValue (null, DeepMemberwiseCopy (PropertyValue, PropertyInfo?.GetValue (null))); } @@ -47,7 +47,7 @@ public class ConfigProperty catch (TargetInvocationException tie) { // Check if there is an inner exception - if (tie.InnerException != null) + if (tie.InnerException is { }) { // Handle the inner exception separately without catching the outer exception Exception? innerException = tie.InnerException; @@ -96,14 +96,14 @@ public class ConfigProperty internal object? UpdateValueFrom (object source) { - if (source == null) + if (source is null) { return PropertyValue; } Type? ut = Nullable.GetUnderlyingType (PropertyInfo!.PropertyType); - if (source.GetType () != PropertyInfo!.PropertyType && ut != null && source.GetType () != ut) + if (source.GetType () != PropertyInfo!.PropertyType && ut is { } && source.GetType () != ut) { throw new ArgumentException ( $"The source object ({ @@ -116,7 +116,7 @@ public class ConfigProperty ); } - if (PropertyValue != null) + if (PropertyValue is { }) { PropertyValue = DeepMemberwiseCopy (source, PropertyValue); } diff --git a/Terminal.Gui/Configuration/ConfigurationManager.cs b/Terminal.Gui/Configuration/ConfigurationManager.cs index 7a4946fa1..ae001d787 100644 --- a/Terminal.Gui/Configuration/ConfigurationManager.cs +++ b/Terminal.Gui/Configuration/ConfigurationManager.cs @@ -145,7 +145,7 @@ public static class ConfigurationManager { get { - if (_settings == null) + if (_settings is null) { throw new InvalidOperationException ( "ConfigurationManager has not been initialized. Call ConfigurationManager.Reset() before accessing the Settings property." @@ -320,7 +320,7 @@ public static class ConfigurationManager { Debug.WriteLine (@"ConfigurationManager.Reset()"); - if (_allConfigProperties == null) + if (_allConfigProperties is null) { Initialize (); } @@ -364,12 +364,12 @@ public static class ConfigurationManager /// updated from internal static object? DeepMemberwiseCopy (object? source, object? destination) { - if (destination == null) + if (destination is null) { throw new ArgumentNullException (nameof (destination)); } - if (source == null) + if (source is null) { return null!; } @@ -432,11 +432,11 @@ public static class ConfigurationManager object? sourceVal = sourceProp.GetValue (source); object? destVal = destProp.GetValue (destination); - if (sourceVal != null) + if (sourceVal is { }) { try { - if (destVal != null) + if (destVal is { }) { // Recurse destProp.SetValue (destination, DeepMemberwiseCopy (sourceVal, destVal)); @@ -474,7 +474,7 @@ public static class ConfigurationManager /// internal static void GetHardCodedDefaults () { - if (_allConfigProperties == null) + if (_allConfigProperties is null) { throw new InvalidOperationException ("Initialize must be called first."); } @@ -483,7 +483,7 @@ public static class ConfigurationManager ThemeManager.GetHardCodedDefaults (); AppSettings?.RetrieveValues (); - foreach (KeyValuePair p in Settings!.Where (cp => cp.Value.PropertyInfo != null)) + foreach (KeyValuePair p in Settings!.Where (cp => cp.Value.PropertyInfo is { })) { Settings! [p.Key].PropertyValue = p.Value.PropertyInfo?.GetValue (null); } diff --git a/Terminal.Gui/Configuration/KeyCodeJsonConverter.cs b/Terminal.Gui/Configuration/KeyCodeJsonConverter.cs index 38f5a2f6f..c7b705311 100644 --- a/Terminal.Gui/Configuration/KeyCodeJsonConverter.cs +++ b/Terminal.Gui/Configuration/KeyCodeJsonConverter.cs @@ -126,7 +126,7 @@ internal class KeyCodeJsonConverter : JsonConverter var keyName = (value & ~KeyCode.CtrlMask & ~KeyCode.ShiftMask & ~KeyCode.AltMask).ToString (); - if (keyName != null) + if (keyName is { }) { writer.WriteString ("Key", keyName); } diff --git a/Terminal.Gui/Configuration/Scope.cs b/Terminal.Gui/Configuration/Scope.cs index 3faf9fea4..718c5d512 100644 --- a/Terminal.Gui/Configuration/Scope.cs +++ b/Terminal.Gui/Configuration/Scope.cs @@ -21,7 +21,7 @@ public class Scope : Dictionary /// Retrieves the values of the properties of this scope from their corresponding static properties. public void RetrieveValues () { - foreach (KeyValuePair p in this.Where (cp => cp.Value.PropertyInfo != null)) + foreach (KeyValuePair p in this.Where (cp => cp.Value.PropertyInfo is { })) { p.Value.RetrieveValue (); } diff --git a/Terminal.Gui/Configuration/ScopeJsonConverter.cs b/Terminal.Gui/Configuration/ScopeJsonConverter.cs index 680ee56e8..5419619e2 100644 --- a/Terminal.Gui/Configuration/ScopeJsonConverter.cs +++ b/Terminal.Gui/Configuration/ScopeJsonConverter.cs @@ -39,7 +39,7 @@ internal class ScopeJsonConverter : JsonConverter where scopeT : string? propertyName = reader.GetString (); reader.Read (); - if (propertyName != null && scope!.TryGetValue (propertyName, out ConfigProperty? configProp)) + if (propertyName is { } && scope!.TryGetValue (propertyName, out ConfigProperty? configProp)) { // This property name was found in the Scope's ScopeProperties dictionary // Figure out if it needs a JsonConverter and if so, create one @@ -54,7 +54,7 @@ internal class ScopeJsonConverter : JsonConverter where scopeT : { var factory = (JsonConverterFactory)converter; - if (propertyType != null && factory.CanConvert (propertyType)) + if (propertyType is { } && factory.CanConvert (propertyType)) { converter = factory.CreateConverter (propertyType, options); } @@ -106,7 +106,7 @@ internal class ScopeJsonConverter : JsonConverter where scopeT : p.GetCustomAttribute (typeof (JsonIncludeAttribute)) as JsonIncludeAttribute; - if (jia != null) + if (jia is { }) { var jpna = p.GetCustomAttribute ( @@ -130,7 +130,7 @@ internal class ScopeJsonConverter : JsonConverter where scopeT : ) .FirstOrDefault (); - if (property != null) + if (property is { }) { PropertyInfo prop = scope.GetType ().GetProperty (propertyName!)!; prop.SetValue (scope, JsonSerializer.Deserialize (ref reader, prop.PropertyType, options)); @@ -196,7 +196,7 @@ internal class ScopeJsonConverter : JsonConverter where scopeT : } } - if (p.Value.PropertyValue != null) + if (p.Value.PropertyValue is { }) { converter.GetType () .GetMethod ("Write") diff --git a/Terminal.Gui/Configuration/SettingsScope.cs b/Terminal.Gui/Configuration/SettingsScope.cs index 3362ca4a8..87e1b02dc 100644 --- a/Terminal.Gui/Configuration/SettingsScope.cs +++ b/Terminal.Gui/Configuration/SettingsScope.cs @@ -102,7 +102,7 @@ public class SettingsScope : Scope /// public SettingsScope? UpdateFromResource (Assembly assembly, string resourceName) { - if (resourceName == null || string.IsNullOrEmpty (resourceName)) + if (resourceName is null || string.IsNullOrEmpty (resourceName)) { Debug.WriteLine ( $"ConfigurationManager: Resource \"{resourceName}\" does not exist in \"{assembly.GetName ().Name}\"." @@ -113,7 +113,7 @@ public class SettingsScope : Scope using Stream? stream = assembly.GetManifestResourceStream (resourceName)!; - if (stream == null) + if (stream is null) { Debug.WriteLine ( $"ConfigurationManager: Failed to read resource \"{resourceName}\" from \"{assembly.GetName ().Name}\"." diff --git a/Terminal.Gui/Configuration/ThemeManager.cs b/Terminal.Gui/Configuration/ThemeManager.cs index 372b85dd4..9bde9a416 100644 --- a/Terminal.Gui/Configuration/ThemeManager.cs +++ b/Terminal.Gui/Configuration/ThemeManager.cs @@ -78,7 +78,7 @@ public class ThemeManager : IDictionary Dictionary; // themes ?? new Dictionary (); set => - //if (themes == null || value == null) { + //if (themes is null || value is null) { // themes = value; //} else { // themes = (Dictionary)DeepMemberwiseCopy (value!, themes!)!; diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index bf473c1c9..f09767dba 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -488,7 +488,7 @@ public abstract class ConsoleDriver get => _currentAttribute; set { - if (Application.Driver != null) + if (Application.Driver is { }) { _currentAttribute = new Attribute (value.Foreground, value.Background); @@ -520,7 +520,7 @@ public abstract class ConsoleDriver /// The foreground color. /// The background color. /// The attribute for the foreground and background colors. - public virtual Attribute MakeColor (Color foreground, Color background) + public virtual Attribute MakeColor (in Color foreground, in Color background) { // Encode the colors into the int value. return new Attribute ( diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs b/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs index 41d2eb663..331580083 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs @@ -155,7 +155,7 @@ public static class ConsoleKeyMapping ScanCodeMapping sCode = _scanCodes.FirstOrDefault (e => e.UnicodeChar == keyValue && e.Modifiers == modifiers); - if (sCode == null && modifiers == (ConsoleModifiers.Alt | ConsoleModifiers.Control)) + if (sCode is null && modifiers == (ConsoleModifiers.Alt | ConsoleModifiers.Control)) { return _scanCodes.FirstOrDefault (e => e.UnicodeChar == keyValue && e.Modifiers == 0); } @@ -164,7 +164,7 @@ public static class ConsoleKeyMapping case "VirtualKey": sCode = _scanCodes.FirstOrDefault (e => e.VirtualKey == (VK)keyValue && e.Modifiers == modifiers); - if (sCode == null && modifiers == (ConsoleModifiers.Alt | ConsoleModifiers.Control)) + if (sCode is null && modifiers == (ConsoleModifiers.Alt | ConsoleModifiers.Control)) { return _scanCodes.FirstOrDefault (e => e.VirtualKey == (VK)keyValue && e.Modifiers == 0); } @@ -184,7 +184,7 @@ public static class ConsoleKeyMapping ConsoleModifiers mod = GetModifiers (consoleKeyInfo.Modifiers); ScanCodeMapping scode = GetScanCode ("VirtualKey", (uint)consoleKeyInfo.Key, mod); - if (scode != null) + if (scode is { }) { return scode.ScanCode; } @@ -206,7 +206,7 @@ public static class ConsoleKeyMapping ConsoleModifiers mod = GetModifiers (modifiers); ScanCodeMapping scode = GetScanCode ("VirtualKey", keyValue, mod); - if (scode != null) + if (scode is { }) { return new ConsoleKeyInfo ( (char)scode.UnicodeChar, @@ -328,12 +328,12 @@ public static class ConsoleKeyMapping { ScanCodeMapping sCode = _scanCodes.FirstOrDefault (e => e.UnicodeChar == keyValue); - if (sCode == null) + if (sCode is null) { consoleKey = (byte)(keyValue & byte.MaxValue); sCode = _scanCodes.FirstOrDefault (e => e.VirtualKey == (VK)consoleKey); - if (sCode == null) + if (sCode is null) { consoleKey = 0; outputChar = keyValue; @@ -561,18 +561,18 @@ public static class ConsoleKeyMapping scode = GetScanCode ("VirtualKey", decodedChar, mod); } - if (isConsoleKey && scode != null) + if (isConsoleKey && scode is { }) { consoleKey = (uint)scode.VirtualKey; keyChar = scode.UnicodeChar; scanCode = scode.ScanCode; } - if (scode == null) + if (scode is null) { scode = unicodeChar != 0 ? GetScanCode ("UnicodeChar", decodedChar, mod) : null; - if (scode != null) + if (scode is { }) { consoleKey = (uint)scode.VirtualKey; keyChar = scode.UnicodeChar; @@ -593,7 +593,7 @@ public static class ConsoleKeyMapping consoleKey = char.ToUpper (stFormD [i]); scode = GetScanCode ("VirtualKey", char.ToUpper (stFormD [i]), 0); - if (scode != null) + if (scode is { }) { scanCode = scode.ScanCode; } @@ -605,7 +605,7 @@ public static class ConsoleKeyMapping { scode = GetScanCode ("VirtualKey", keyChar, mod); - if (scode != null) + if (scode is { }) { consoleKey = (uint)scode.VirtualKey; keyChar = scode.UnicodeChar; @@ -2520,7 +2520,7 @@ public static class ConsoleKeyMapping // try to get the ConsoleKey ScanCodeMapping scode = _scanCodes.FirstOrDefault (e => e.UnicodeChar == keyChar); - if (scode != null) + if (scode is { }) { consoleKey = (ConsoleKey)scode.VirtualKey; } diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index 7f7350ae2..2dc72d167 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -282,7 +282,7 @@ internal class CursesDriver : ConsoleDriver StopReportingMouseMoves (); SetCursorVisibility (CursorVisibility.Default); - if (_mainLoopDriver != null) + if (_mainLoopDriver is { }) { _mainLoopDriver.RemoveWatch (_processInputToken); } @@ -835,7 +835,7 @@ internal class CursesDriver : ConsoleDriver /// bits, and the background color is stored in the least significant 4 bits. The Terminal.GUi Color values are /// converted to curses color encoding before being encoded. /// - public override Attribute MakeColor (Color foreground, Color background) + public override Attribute MakeColor (in Color foreground, in Color background) { if (!RunningUnitTests) { diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs index 2f1cbdf53..34139815c 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs @@ -118,7 +118,7 @@ internal class UnixMainLoop : IMainLoopDriver _cursesDriver.ProcessWinChange (); } - if (_pollMap == null) + if (_pollMap is null) { return; } @@ -159,7 +159,7 @@ internal class UnixMainLoop : IMainLoopDriver /// internal object AddWatch (int fileDescriptor, Condition condition, Func callback) { - if (callback == null) + if (callback is null) { throw new ArgumentNullException (nameof (callback)); } diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs index 64ef39204..2d5e28acf 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs @@ -48,11 +48,11 @@ public class EscSeqRequests { EscSeqReqStatus found = Statuses.Find (x => x.Terminator == terminator); - if (found == null) + if (found is null) { Statuses.Add (new EscSeqReqStatus (terminator, numReq)); } - else if (found != null && found.NumOutstanding < found.NumRequests) + else if (found is { } && found.NumOutstanding < found.NumRequests) { found.NumOutstanding = Math.Min (found.NumOutstanding + numReq, found.NumRequests); } @@ -71,12 +71,12 @@ public class EscSeqRequests { EscSeqReqStatus found = Statuses.Find (x => x.Terminator == terminator); - if (found == null) + if (found is null) { return false; } - if (found != null && found.NumOutstanding > 0) + if (found is { } && found.NumOutstanding > 0) { return true; } @@ -102,16 +102,16 @@ public class EscSeqRequests { EscSeqReqStatus found = Statuses.Find (x => x.Terminator == terminator); - if (found == null) + if (found is null) { return; } - if (found != null && found.NumOutstanding == 0) + if (found is { } && found.NumOutstanding == 0) { Statuses.Remove (found); } - else if (found != null && found.NumOutstanding > 0) + else if (found is { } && found.NumOutstanding > 0) { found.NumOutstanding--; diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index 01c87f472..c308891cc 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -200,7 +200,7 @@ public static class EscSeqUtils switch (c1Control) { case "ESC": - if (values == null && string.IsNullOrEmpty (terminator)) + if (values is null && string.IsNullOrEmpty (terminator)) { key = ConsoleKey.Escape; @@ -262,7 +262,7 @@ public static class EscSeqUtils return; } - if (escSeqRequests != null && escSeqRequests.HasResponse (terminator)) + if (escSeqRequests is { } && escSeqRequests.HasResponse (terminator)) { isResponse = true; escSeqRequests.Remove (terminator); @@ -515,7 +515,7 @@ public static class EscSeqUtils /// public static (string c1Control, string code, string [] values, string terminating) GetEscapeResult (char [] kChar) { - if (kChar == null || kChar.Length == 0) + if (kChar is null || kChar.Length == 0) { return (null, null, null, null); } @@ -866,8 +866,8 @@ public static class EscSeqUtils || buttonState == MouseFlags.Button2Pressed || buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed) - && lastMouseButtonPressed == null) - || (isButtonPressed && lastMouseButtonPressed != null && buttonState.HasFlag (MouseFlags.ReportMousePosition))) + && lastMouseButtonPressed is null) + || (isButtonPressed && lastMouseButtonPressed is { } && buttonState.HasFlag (MouseFlags.ReportMousePosition))) { mouseFlags [0] = buttonState; lastMouseButtonPressed = buttonState; @@ -1038,7 +1038,7 @@ public static class EscSeqUtils { foreach (ManagementObject mo in mos.Get ()) { - if (mo ["ParentProcessId"] != null) + if (mo ["ParentProcessId"] is { }) { try { @@ -1131,7 +1131,7 @@ public static class EscSeqUtils /// The resized. public static ConsoleKeyInfo [] ResizeArray (ConsoleKeyInfo consoleKeyInfo, ConsoleKeyInfo [] cki) { - Array.Resize (ref cki, cki == null ? 1 : cki.Length + 1); + Array.Resize (ref cki, cki is null ? 1 : cki.Length + 1); cki [cki.Length - 1] = consoleKeyInfo; return cki; @@ -1232,12 +1232,12 @@ public static class EscSeqUtils View view = Application.WantContinuousButtonPressedView; - if (view == null) + if (view is null) { break; } - if (isButtonPressed && lastMouseButtonPressed != null && (mouseFlag & MouseFlags.ReportMousePosition) == 0) + if (isButtonPressed && lastMouseButtonPressed is { } && (mouseFlag & MouseFlags.ReportMousePosition) == 0) { Application.Invoke (() => continuousButtonPressedHandler (mouseFlag, point ?? Point.Empty)); } diff --git a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs index cd78d7995..90527a263 100644 --- a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs @@ -513,7 +513,7 @@ public class FakeDriver : ConsoleDriver protected override string GetClipboardDataImpl () { - if (FakeException != null) + if (FakeException is { }) { throw FakeException; } @@ -523,12 +523,12 @@ public class FakeDriver : ConsoleDriver protected override void SetClipboardDataImpl (string text) { - if (text == null) + if (text is null) { throw new ArgumentNullException (nameof (text)); } - if (FakeException != null) + if (FakeException is { }) { throw FakeException; } diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index d3e25a1f6..afcb112ec 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -262,7 +262,7 @@ internal class NetEvents : IDisposable if ((consoleKeyInfo.KeyChar == (char)KeyCode.Esc && !_isEscSeq) || (consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq)) { - if (_cki == null && consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq) + if (_cki is null && consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq) { _cki = EscSeqUtils.ResizeArray ( new ConsoleKeyInfo ( @@ -292,7 +292,7 @@ internal class NetEvents : IDisposable break; } - if (consoleKeyInfo.KeyChar == (char)KeyCode.Esc && _isEscSeq && _cki != null) + if (consoleKeyInfo.KeyChar == (char)KeyCode.Esc && _isEscSeq && _cki is { }) { ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); _cki = null; @@ -1646,7 +1646,7 @@ internal class NetMainLoop : IMainLoopDriver /// public NetMainLoop (ConsoleDriver consoleDriver = null) { - if (consoleDriver == null) + if (consoleDriver is null) { throw new ArgumentNullException (nameof (consoleDriver)); } @@ -1727,7 +1727,7 @@ internal class NetMainLoop : IMainLoopDriver private void NetInputHandler () { - while (_mainLoop != null) + while (_mainLoop is { }) { try { @@ -1760,7 +1760,7 @@ internal class NetMainLoop : IMainLoopDriver try { - while (_resultQueue.Peek () == null) + while (_resultQueue.Peek () is null) { _resultQueue.Dequeue (); } diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index aa4b03669..bb90b68ea 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -985,7 +985,7 @@ internal class WindowsDriver : ConsoleDriver // TODO: if some other Windows-based terminal supports true color, update this logic to not // force 16color mode (.e.g ConEmu which really doesn't work well at all). _isWindowsTerminal = _isWindowsTerminal = - Environment.GetEnvironmentVariable ("WT_SESSION") != null || Environment.GetEnvironmentVariable ("VSAPPIDNAME") != null; + Environment.GetEnvironmentVariable ("WT_SESSION") is { } || Environment.GetEnvironmentVariable ("VSAPPIDNAME") != null; if (!_isWindowsTerminal) { @@ -998,7 +998,7 @@ internal class WindowsDriver : ConsoleDriver public WindowsConsole WinConsole { get; private set; } /// - public override bool EnsureCursorVisibility () { return WinConsole == null || WinConsole.EnsureCursorVisibility (); } + public override bool EnsureCursorVisibility () { return WinConsole is null || WinConsole.EnsureCursorVisibility (); } public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent) { @@ -1049,7 +1049,7 @@ internal class WindowsDriver : ConsoleDriver /// public override bool GetCursorVisibility (out CursorVisibility visibility) { - if (WinConsole != null) + if (WinConsole is { }) { return WinConsole.GetCursorVisibility (out visibility); } @@ -1143,7 +1143,7 @@ internal class WindowsDriver : ConsoleDriver { _cachedCursorVisibility = visibility; - return WinConsole == null || WinConsole.SetCursorVisibility (visibility); + return WinConsole is null || WinConsole.SetCursorVisibility (visibility); } #region Not Implemented @@ -1274,7 +1274,7 @@ internal class WindowsDriver : ConsoleDriver internal override void End () { - if (_mainLoopDriver != null) + if (_mainLoopDriver is { }) { #if HACK_CHECK_WINCHANGED @@ -1302,7 +1302,7 @@ internal class WindowsDriver : ConsoleDriver { try { - if (WinConsole != null) + if (WinConsole is { }) { // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED @@ -1709,7 +1709,7 @@ internal class WindowsDriver : ConsoleDriver View view = Application.WantContinuousButtonPressedView; - if (view == null) + if (view is null) { break; } @@ -1783,7 +1783,7 @@ internal class WindowsDriver : ConsoleDriver // be fired with it's bit set to 0. So when the button is up ButtonState will be 0. // To map to the correct driver events we save the last pressed mouse button so we can // map to the correct clicked event. - if ((_lastMouseButtonPressed != null || _isButtonReleased) && mouseEvent.ButtonState != 0) + if ((_lastMouseButtonPressed is { } || _isButtonReleased) && mouseEvent.ButtonState != 0) { _lastMouseButtonPressed = null; @@ -1797,7 +1797,7 @@ internal class WindowsDriver : ConsoleDriver Y = mouseEvent.MousePosition.Y }; - if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed == null && !_isButtonDoubleClicked) + if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed is null && !_isButtonDoubleClicked) || (_lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) && mouseEvent.ButtonState != 0 @@ -1876,7 +1876,7 @@ internal class WindowsDriver : ConsoleDriver _isButtonPressed = false; _isButtonReleased = true; - if (_point != null && ((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y) + if (_point is { } && ((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y) { _processButtonClick = true; } @@ -1998,7 +1998,7 @@ internal class WindowsDriver : ConsoleDriver mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag); //System.Diagnostics.Debug.WriteLine ( - // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}"); + // $"point.X:{(point is { } ? ((Point)point).X : -1)};point.Y:{(point is { } ? ((Point)point).Y : -1)}"); return new MouseEvent { @@ -2137,7 +2137,7 @@ internal class WindowsMainLoop : IMainLoopDriver private void WindowsInputHandler () { - while (_mainLoop != null) + while (_mainLoop is { }) { try { @@ -2170,14 +2170,14 @@ internal class WindowsMainLoop : IMainLoopDriver private Size _windowSize; private void CheckWinChange () { - while (_mainLoop != null) + while (_mainLoop is { }) { _winChange.Wait (); _winChange.Reset (); // Check if the window size changed every half second. // We do this to minimize the weird tearing seen on Windows when resizing the console - while (_mainLoop != null) + while (_mainLoop is { }) { Task.Delay (500).Wait (); _windowSize = _winConsole.GetConsoleBufferWindow (out _); diff --git a/Terminal.Gui/Drawing/Attribute.cs b/Terminal.Gui/Drawing/Attribute.cs index 4da1642df..00b64f9a3 100644 --- a/Terminal.Gui/Drawing/Attribute.cs +++ b/Terminal.Gui/Drawing/Attribute.cs @@ -1,4 +1,5 @@ #nullable enable +using System.Numerics; using System.Text.Json.Serialization; namespace Terminal.Gui; @@ -10,14 +11,15 @@ namespace Terminal.Gui; /// class to define color schemes that can be used in an application. /// [JsonConverter (typeof (AttributeJsonConverter))] -public readonly struct Attribute : IEquatable +public readonly record struct Attribute : IEqualityOperators { /// Default empty attribute. - public static readonly Attribute Default = new (Color.White, ColorName.Black); + [JsonIgnore] + public static Attribute Default => new (Color.White, ColorName.Black); /// The -specific color value. [JsonIgnore (Condition = JsonIgnoreCondition.Always)] - internal int PlatformColor { get; } + internal int PlatformColor { get; init; } /// The foreground color. [JsonConverter (typeof (ColorJsonConverter))] @@ -30,33 +32,20 @@ public readonly struct Attribute : IEquatable /// Initializes a new instance with default values. public Attribute () { - PlatformColor = -1; - Foreground = Default.Foreground; - Background = Default.Background; + this = Default with { PlatformColor = -1 }; } /// Initializes a new instance from an existing instance. public Attribute (in Attribute attr) { - PlatformColor = -1; - Foreground = attr.Foreground; - Background = attr.Background; - } - - /// Initializes a new instance with platform specific color value. - /// Value. - internal Attribute (int platformColor) - { - PlatformColor = platformColor; - Foreground = Default.Foreground; - Background = Default.Background; + this = attr with { PlatformColor = -1 }; } /// Initializes a new instance of the struct. /// platform-dependent color value. /// Foreground /// Background - internal Attribute (int platformColor, in Color foreground, in Color background) + internal Attribute (int platformColor, Color foreground, Color background) { Foreground = foreground; Background = background; @@ -66,21 +55,13 @@ public readonly struct Attribute : IEquatable /// Initializes a new instance of the struct. /// Foreground /// Background - public Attribute (Color foreground, Color background) + public Attribute (in Color foreground, in Color background) { Foreground = foreground; Background = background; - // TODO: Once CursesDriver supports truecolor all the PlatformColor stuff goes away - if (Application.Driver == null) - { - PlatformColor = -1; - - return; - } - - Attribute make = Application.Driver.MakeColor (foreground, background); - PlatformColor = make.PlatformColor; + // TODO: Once CursesDriver supports true color all the PlatformColor stuff goes away + PlatformColor = Application.Driver?.MakeColor(in foreground, in background).PlatformColor ?? -1; } /// @@ -88,51 +69,31 @@ public readonly struct Attribute : IEquatable /// will be set to the specified color. /// /// Value. - internal Attribute (ColorName colorName) : this (colorName, colorName) { } + internal Attribute (in ColorName colorName) : this (in colorName, in colorName) { } /// Initializes a new instance of the struct. /// Foreground /// Background - public Attribute (in ColorName foregroundName, in ColorName backgroundName) : this ( - new Color (foregroundName), - new Color (backgroundName) - ) + public Attribute (in ColorName foregroundName, in ColorName backgroundName) + : this (new Color (in foregroundName), new Color (in backgroundName)) { } /// Initializes a new instance of the struct. /// Foreground /// Background - public Attribute (ColorName foregroundName, Color background) : this (new Color (foregroundName), background) { } + public Attribute (in ColorName foregroundName, in Color background) : this (new Color (in foregroundName), in background) { } /// Initializes a new instance of the struct. /// Foreground /// Background - public Attribute (Color foreground, ColorName backgroundName) : this (foreground, new Color (backgroundName)) { } + public Attribute (in Color foreground, in ColorName backgroundName) : this (in foreground, new Color (in backgroundName)) { } /// /// Initializes a new instance of the struct with the same colors for the foreground and /// background. /// /// The color. - public Attribute (Color color) : this (color, color) { } - - /// Compares two attributes for equality. - /// - /// - /// - public static bool operator == (Attribute left, Attribute right) { return left.Equals (right); } - - /// Compares two attributes for inequality. - /// - /// - /// - public static bool operator != (Attribute left, Attribute right) { return !(left == right); } - - /// - public override bool Equals (object? obj) { return obj is Attribute other && Equals (other); } - - /// - public bool Equals (Attribute other) { return PlatformColor == other.PlatformColor && Foreground == other.Foreground && Background == other.Background; } + public Attribute (in Color color) : this (color, color) { } /// public override int GetHashCode () { return HashCode.Combine (PlatformColor, Foreground, Background); } diff --git a/Terminal.Gui/Drawing/ColorExtensions.cs b/Terminal.Gui/Drawing/Color.ColorExtensions.cs similarity index 100% rename from Terminal.Gui/Drawing/ColorExtensions.cs rename to Terminal.Gui/Drawing/Color.ColorExtensions.cs diff --git a/Terminal.Gui/Drawing/ColorName.cs b/Terminal.Gui/Drawing/Color.ColorName.cs similarity index 100% rename from Terminal.Gui/Drawing/ColorName.cs rename to Terminal.Gui/Drawing/Color.ColorName.cs diff --git a/Terminal.Gui/Drawing/ColorParseException.cs b/Terminal.Gui/Drawing/Color.ColorParseException.cs similarity index 100% rename from Terminal.Gui/Drawing/ColorParseException.cs rename to Terminal.Gui/Drawing/Color.ColorParseException.cs diff --git a/Terminal.Gui/Drawing/ColorScheme.Colors.cs b/Terminal.Gui/Drawing/ColorScheme.Colors.cs new file mode 100644 index 000000000..ca14a4986 --- /dev/null +++ b/Terminal.Gui/Drawing/ColorScheme.Colors.cs @@ -0,0 +1,176 @@ +#nullable enable +using System.Collections; +using System.Collections.Specialized; +using System.Text.Json.Serialization; + +namespace Terminal.Gui; + +/// +/// Holds the s that define the s that are used by views to render +/// themselves. +/// +public sealed class Colors : INotifyCollectionChanged, IDictionary +{ + static Colors () + { + ColorSchemes = new (5, StringComparer.InvariantCultureIgnoreCase); + Reset (); + } + + /// Gets a dictionary of defined objects. + /// + /// + /// The dictionary includes the following keys, by default: + /// + /// + /// Built-in Color Scheme Description + /// + /// + /// Base The base color scheme used for most Views. + /// + /// + /// TopLevel + /// The application Toplevel color scheme; used for the View. + /// + /// + /// Dialog + /// + /// The dialog color scheme; used for , , and + /// other views dialog-like views. + /// + /// + /// + /// Menu + /// + /// The menu color scheme; used for , , and + /// . + /// + /// + /// + /// Error + /// + /// The color scheme for showing errors, such as in + /// . + /// + /// + /// + /// + /// Changing the values of an entry in this dictionary will affect all views that use the scheme. + /// + /// can be used to override the default values for these schemes and add + /// additional schemes. See . + /// + /// + [SerializableConfigurationProperty (Scope = typeof (ThemeScope), OmitClassName = true)] + [JsonConverter (typeof (DictionaryJsonConverter))] + [UsedImplicitly] + public static Dictionary ColorSchemes { get; private set; } + + /// + public IEnumerator> GetEnumerator () { return ColorSchemes.GetEnumerator (); } + + /// + IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } + + /// + public void Add (KeyValuePair item) + { + ColorSchemes.Add (item.Key, item.Value); + CollectionChanged?.Invoke (this, new (NotifyCollectionChangedAction.Add, item)); + } + + /// + public void Clear () + { + ColorSchemes.Clear (); + CollectionChanged?.Invoke (this, new (NotifyCollectionChangedAction.Reset)); + } + + /// + public bool Contains (KeyValuePair item) { return ColorSchemes.Contains (item); } + + /// + public void CopyTo (KeyValuePair [] array, int arrayIndex) { ((ICollection)ColorSchemes).CopyTo (array, arrayIndex); } + + /// + public bool Remove (KeyValuePair item) + { + if (ColorSchemes.Remove (item.Key)) + { + CollectionChanged?.Invoke (this, new (NotifyCollectionChangedAction.Remove, item)); + + return true; + } + + return false; + } + + /// + public int Count => ColorSchemes.Count; + + /// + public bool IsReadOnly => false; + + /// + public void Add (string key, ColorScheme? value) { Add (new (key, value)); } + + /// + public bool ContainsKey (string key) { return ColorSchemes.ContainsKey (key); } + + /// + public bool Remove (string key) + { + if (ColorSchemes.Remove (key)) + { + CollectionChanged?.Invoke (this, new (NotifyCollectionChangedAction.Remove, key)); + + return true; + } + + return false; + } + + /// + public bool TryGetValue (string key, out ColorScheme? value) { return ColorSchemes.TryGetValue (key, out value); } + + /// + public ColorScheme? this [string key] + { + get => ColorSchemes [key]; + set + { + if (ColorSchemes.TryAdd (key, value)) + { + CollectionChanged?.Invoke (this, new (NotifyCollectionChangedAction.Add, new KeyValuePair (key, value))); + } + else + { + ColorScheme? oldValue = ColorSchemes [key]; + ColorSchemes [key] = value; + CollectionChanged?.Invoke (this, new (NotifyCollectionChangedAction.Replace, value, oldValue)); + } + } + } + + /// + public ICollection Keys => ColorSchemes.Keys; + + /// + public ICollection Values => ColorSchemes.Values; + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged; + + /// Resets the dictionary to the default values. + public static Dictionary Reset () + { + ColorSchemes.Clear (); + ColorSchemes.Add ("TopLevel", new ()); + ColorSchemes.Add ("Base", new ()); + ColorSchemes.Add ("Dialog", new ()); + ColorSchemes.Add ("Menu", new ()); + ColorSchemes.Add ("Error", new ()); + + return ColorSchemes; + } +} diff --git a/Terminal.Gui/Drawing/ColorScheme.cs b/Terminal.Gui/Drawing/ColorScheme.cs index 8846af1ad..8ced1bdea 100644 --- a/Terminal.Gui/Drawing/ColorScheme.cs +++ b/Terminal.Gui/Drawing/ColorScheme.cs @@ -1,5 +1,5 @@ -#nullable enable -using System.Globalization; +#nullable enable +using System.Numerics; using System.Text.Json.Serialization; namespace Terminal.Gui; @@ -13,7 +13,7 @@ namespace Terminal.Gui; /// /// [JsonConverter (typeof (ColorSchemeJsonConverter))] -public class ColorScheme : IEquatable +public record ColorScheme : IEqualityOperators { private readonly Attribute _disabled; private readonly Attribute _focus; @@ -26,12 +26,9 @@ public class ColorScheme : IEquatable /// Creates a new instance, initialized with the values from . /// The scheme to initialize the new instance with. - public ColorScheme (ColorScheme scheme) + public ColorScheme (ColorScheme? scheme) { - if (scheme is null) - { - throw new ArgumentNullException (nameof (scheme)); - } + ArgumentNullException.ThrowIfNull (scheme); _normal = scheme.Normal; _focus = scheme.Focus; @@ -89,7 +86,7 @@ public class ColorScheme : IEquatable /// Compares two objects for equality. /// /// true if the two objects are equal - public bool Equals (ColorScheme? other) + public virtual bool Equals (ColorScheme? other) { return other is { } && EqualityComparer.Default.Equals (_normal, other._normal) @@ -99,130 +96,13 @@ public class ColorScheme : IEquatable && EqualityComparer.Default.Equals (_disabled, other._disabled); } - /// Compares two objects for equality. - /// - /// true if the two objects are equal - public override bool Equals (object? obj) { return Equals (obj as ColorScheme); } - /// Returns a hashcode for this instance. /// hashcode for this instance public override int GetHashCode () { - int hashCode = -1242460230; - hashCode = hashCode * -1521134295 + _normal.GetHashCode (); - hashCode = hashCode * -1521134295 + _focus.GetHashCode (); - hashCode = hashCode * -1521134295 + _hotNormal.GetHashCode (); - hashCode = hashCode * -1521134295 + _hotFocus.GetHashCode (); - hashCode = hashCode * -1521134295 + _disabled.GetHashCode (); - - return hashCode; + return HashCode.Combine (_normal, _focus, _hotNormal, _hotFocus, _disabled); } - /// Compares two objects for equality. - /// - /// - /// true if the two objects are equivalent - public static bool operator == (ColorScheme left, ColorScheme right) { return EqualityComparer.Default.Equals (left, right); } - - /// Compares two objects for inequality. - /// - /// - /// true if the two objects are not equivalent - public static bool operator != (ColorScheme left, ColorScheme right) { return !(left == right); } - /// public override string ToString () { return $"Normal: {Normal}; Focus: {Focus}; HotNormal: {HotNormal}; HotFocus: {HotFocus}; Disabled: {Disabled}"; } -} - -/// -/// Holds the s that define the s that are used by views to render -/// themselves. -/// -public static class Colors -{ - static Colors () { Reset (); } - - /// Gets a dictionary of defined objects. - /// - /// - /// The dictionary includes the following keys, by default: - /// - /// - /// Built-in Color Scheme Description - /// - /// - /// Base The base color scheme used for most Views. - /// - /// - /// TopLevel - /// The application Toplevel color scheme; used for the View. - /// - /// - /// Dialog - /// - /// The dialog color scheme; used for , , and - /// other views dialog-like views. - /// - /// - /// - /// Menu - /// - /// The menu color scheme; used for , , and - /// . - /// - /// - /// - /// Error - /// - /// The color scheme for showing errors, such as in - /// . - /// - /// - /// - /// - /// Changing the values of an entry in this dictionary will affect all views that use the scheme. - /// - /// can be used to override the default values for these schemes and add - /// additional schemes. See . - /// - /// - [SerializableConfigurationProperty (Scope = typeof (ThemeScope), OmitClassName = true)] - [JsonConverter (typeof (DictionaryJsonConverter))] - public static Dictionary - ColorSchemes { get; private set; } // Serialization requires this to have a setter (private set;) - - /// Resets the dictionary to the default values. - public static Dictionary Reset () - { - ColorSchemes ??= new Dictionary ( - 5, - CultureInfo.InvariantCulture.CompareInfo - .GetStringComparer ( - CompareOptions.IgnoreCase - ) - ); - ColorSchemes.Clear (); - ColorSchemes.Add ("TopLevel", new ColorScheme ()); - ColorSchemes.Add ("Base", new ColorScheme ()); - ColorSchemes.Add ("Dialog", new ColorScheme ()); - ColorSchemes.Add ("Menu", new ColorScheme ()); - ColorSchemes.Add ("Error", new ColorScheme ()); - - return ColorSchemes; - } - - private class SchemeNameComparerIgnoreCase : IEqualityComparer - { - public bool Equals (string x, string y) - { - if (x != null && y != null) - { - return string.Equals (x, y, StringComparison.InvariantCultureIgnoreCase); - } - - return false; - } - - public int GetHashCode (string obj) { return obj.ToLowerInvariant ().GetHashCode (); } - } -} +} \ No newline at end of file diff --git a/Terminal.Gui/Drawing/LineCanvas.cs b/Terminal.Gui/Drawing/LineCanvas.cs index 70f1ff7a2..3a452a232 100644 --- a/Terminal.Gui/Drawing/LineCanvas.cs +++ b/Terminal.Gui/Drawing/LineCanvas.cs @@ -225,12 +225,12 @@ public class LineCanvas : IDisposable { IntersectionDefinition? [] intersects = _lines .Select (l => l.Intersects (x, y)) - .Where (i => i != null) + .Where (i => i is { }) .ToArray (); Cell? cell = GetCellForIntersects (Application.Driver, intersects); - if (cell != null) + if (cell is { }) { map.Add (new Point (x, y), cell); } @@ -260,12 +260,12 @@ public class LineCanvas : IDisposable { IntersectionDefinition? [] intersects = _lines .Select (l => l.Intersects (x, y)) - .Where (i => i != null) + .Where (i => i is { }) .ToArray (); Rune? rune = GetRuneForIntersects (Application.Driver, intersects); - if (rune != null) + if (rune is { }) { map.Add (new Point (x, y), rune.Value); } @@ -299,7 +299,7 @@ public class LineCanvas : IDisposable { StraightLine? l = _lines.LastOrDefault (); - if (l != null) + if (l is { }) { _lines.Remove (l); } diff --git a/Terminal.Gui/Drawing/Thickness.cs b/Terminal.Gui/Drawing/Thickness.cs index d4ddacf19..c5275b34b 100644 --- a/Terminal.Gui/Drawing/Thickness.cs +++ b/Terminal.Gui/Drawing/Thickness.cs @@ -217,7 +217,7 @@ public class Thickness : IEquatable // Draw the diagnostics label on the bottom var tf = new TextFormatter { - Text = label == null ? string.Empty : $"{label} {this}", + Text = label is null ? string.Empty : $"{label} {this}", Alignment = TextAlignment.Centered, VerticalAlignment = VerticalTextAlignment.Bottom }; @@ -233,7 +233,7 @@ public class Thickness : IEquatable public override bool Equals (object obj) { //Check for null and compare run-time types. - if (obj == null || !GetType ().Equals (obj.GetType ())) + if (obj is null || !GetType ().Equals (obj.GetType ())) { return false; } diff --git a/Terminal.Gui/FileServices/DefaultFileOperations.cs b/Terminal.Gui/FileServices/DefaultFileOperations.cs index e00946b41..25f5c2369 100644 --- a/Terminal.Gui/FileServices/DefaultFileOperations.cs +++ b/Terminal.Gui/FileServices/DefaultFileOperations.cs @@ -53,7 +53,7 @@ public class DefaultFileOperations : IFileOperations public IFileSystemInfo Rename (IFileSystem fileSystem, IFileSystemInfo toRename) { // Don't allow renaming C: or D: or / (on linux) etc - if (toRename is IDirectoryInfo dir && dir.Parent == null) + if (toRename is IDirectoryInfo dir && dir.Parent is null) { return null; } diff --git a/Terminal.Gui/FileServices/FileDialogHistory.cs b/Terminal.Gui/FileServices/FileDialogHistory.cs index ff71bc316..ddb019d27 100644 --- a/Terminal.Gui/FileServices/FileDialogHistory.cs +++ b/Terminal.Gui/FileServices/FileDialogHistory.cs @@ -28,7 +28,7 @@ internal class FileDialogHistory } // nowhere to go - if (goTo == null) + if (goTo is null) { return false; } @@ -36,7 +36,7 @@ internal class FileDialogHistory forward.Push (dlg.State); dlg.PushState (goTo, false, true, false, restorePath); - if (restoreSelection != null) + if (restoreSelection is { }) { dlg.RestoreSelection (restoreSelection.FileSystemInfo); } @@ -63,7 +63,7 @@ internal class FileDialogHistory internal void Push (FileDialogState state, bool clearForward) { - if (state == null) + if (state is null) { return; } @@ -84,7 +84,7 @@ internal class FileDialogHistory { IDirectoryInfo parent = dlg.State?.Directory.Parent; - if (parent != null) + if (parent is { }) { back.Push (new FileDialogState (parent, dlg)); dlg.PushState (parent, false); diff --git a/Terminal.Gui/FileServices/FileDialogState.cs b/Terminal.Gui/FileServices/FileDialogState.cs index 42741e978..ece6d2428 100644 --- a/Terminal.Gui/FileServices/FileDialogState.cs +++ b/Terminal.Gui/FileServices/FileDialogState.cs @@ -55,13 +55,13 @@ internal class FileDialogState } // if theres a UI filter in place too - if (Parent.CurrentFilter != null) + if (Parent.CurrentFilter is { }) { children = children.Where (MatchesApiFilter).ToList (); } // allow navigating up as '..' - if (dir.Parent != null) + if (dir.Parent is { }) { children.Add (new FileSystemInfoStats (dir.Parent, Parent.Style.Culture) { IsParent = true }); } diff --git a/Terminal.Gui/Input/KeyBinding.cs b/Terminal.Gui/Input/KeyBinding.cs index d36273bdf..105dd2efb 100644 --- a/Terminal.Gui/Input/KeyBinding.cs +++ b/Terminal.Gui/Input/KeyBinding.cs @@ -97,7 +97,7 @@ public class KeyBindings throw new ArgumentException (@"At least one command must be specified", nameof (commands)); } - if (key == null || !key.IsValid) + if (key is null || !key.IsValid) { //throw new ArgumentException ("Invalid Key", nameof (commands)); return; diff --git a/Terminal.Gui/Input/Responder.cs b/Terminal.Gui/Input/Responder.cs index 3414b1382..9f38757fa 100644 --- a/Terminal.Gui/Input/Responder.cs +++ b/Terminal.Gui/Input/Responder.cs @@ -132,7 +132,7 @@ public class Responder : IDisposable | BindingFlags.DeclaredOnly ); - if (m == null) + if (m is null) { return false; } diff --git a/Terminal.Gui/MainLoop.cs b/Terminal.Gui/MainLoop.cs index 4e8306dc4..2c7b7ef85 100644 --- a/Terminal.Gui/MainLoop.cs +++ b/Terminal.Gui/MainLoop.cs @@ -125,7 +125,7 @@ internal class MainLoop : IDisposable /// internal object AddTimeout (TimeSpan time, Func callback) { - if (callback == null) + if (callback is null) { throw new ArgumentNullException (nameof (callback)); } diff --git a/Terminal.Gui/RunState.cs b/Terminal.Gui/RunState.cs index d6afc194a..ebfb32b30 100644 --- a/Terminal.Gui/RunState.cs +++ b/Terminal.Gui/RunState.cs @@ -30,7 +30,7 @@ public class RunState : IDisposable /// If set to we are disposing and should dispose held objects. protected virtual void Dispose (bool disposing) { - if (Toplevel != null && disposing) + if (Toplevel is { } && disposing) { throw new InvalidOperationException ( "You must clean up (Dispose) the Toplevel before calling Application.RunState.Dispose" diff --git a/Terminal.Gui/Terminal.Gui.csproj b/Terminal.Gui/Terminal.Gui.csproj index be870e054..f4558ea42 100644 --- a/Terminal.Gui/Terminal.Gui.csproj +++ b/Terminal.Gui/Terminal.Gui.csproj @@ -38,6 +38,7 @@ + @@ -83,6 +84,8 @@ + + diff --git a/Terminal.Gui/Text/Autocomplete/PopupAutocomplete.cs b/Terminal.Gui/Text/Autocomplete/PopupAutocomplete.cs index b58aa37a2..b3a637b44 100644 --- a/Terminal.Gui/Text/Autocomplete/PopupAutocomplete.cs +++ b/Terminal.Gui/Text/Autocomplete/PopupAutocomplete.cs @@ -23,7 +23,7 @@ public abstract class PopupAutocomplete : AutocompleteBase { get { - if (colorScheme == null) + if (colorScheme is null) { colorScheme = Colors.ColorSchemes ["Menu"]; } @@ -42,7 +42,7 @@ public abstract class PopupAutocomplete : AutocompleteBase hostControl = value; top = hostControl.SuperView; - if (top != null) + if (top is { }) { top.DrawContent += Top_DrawContent; top.DrawContentComplete += Top_DrawContentComplete; @@ -114,7 +114,7 @@ public abstract class PopupAutocomplete : AutocompleteBase } // not in the popup - if (Visible && HostControl != null) + if (Visible && HostControl is { }) { Visible = false; closed = false; @@ -125,7 +125,7 @@ public abstract class PopupAutocomplete : AutocompleteBase return false; } - if (popup == null || Suggestions.Count == 0) + if (popup is null || Suggestions.Count == 0) { ManipulatePopup (); @@ -467,7 +467,7 @@ public abstract class PopupAutocomplete : AutocompleteBase { SelectedIdx = me.Y - ScrollOffset; - if (LastPopupPos != null) + if (LastPopupPos is { }) { RenderOverlay ((Point)LastPopupPos); } @@ -516,13 +516,13 @@ public abstract class PopupAutocomplete : AutocompleteBase private void ManipulatePopup () { - if (Visible && popup == null) + if (Visible && popup is null) { popup = new Popup (this) { Frame = Rect.Empty }; top?.Add (popup); } - if (!Visible && popup != null) + if (!Visible && popup is { }) { top?.Remove (popup); popup.Dispose (); @@ -568,7 +568,7 @@ public abstract class PopupAutocomplete : AutocompleteBase public override void OnDrawContent (Rect contentArea) { - if (autocomplete.LastPopupPos == null) + if (autocomplete.LastPopupPos is null) { return; } diff --git a/Terminal.Gui/Text/StringExtensions.cs b/Terminal.Gui/Text/StringExtensions.cs index 5bac516f4..538b63975 100644 --- a/Terminal.Gui/Text/StringExtensions.cs +++ b/Terminal.Gui/Text/StringExtensions.cs @@ -55,7 +55,7 @@ public static class StringExtensions /// This is a Terminal.Gui extension method to to support TUI text manipulation. /// The string to measure. /// - public static int GetColumns (this string str) { return str == null ? 0 : str.EnumerateRunes ().Sum (r => Math.Max (r.GetColumns (), 0)); } + public static int GetColumns (this string str) { return str is null ? 0 : str.EnumerateRunes ().Sum (r => Math.Max (r.GetColumns (), 0)); } /// Gets the number of runes in the string. /// This is a Terminal.Gui extension method to to support TUI text manipulation. diff --git a/Terminal.Gui/Text/TextFormatter.cs b/Terminal.Gui/Text/TextFormatter.cs index b9abff066..5dffabf2b 100644 --- a/Terminal.Gui/Text/TextFormatter.cs +++ b/Terminal.Gui/Text/TextFormatter.cs @@ -270,7 +270,7 @@ public class TextFormatter get => _text; set { - bool textWasNull = _text == null && value != null; + bool textWasNull = _text is null && value != null; _text = EnableNeedsFormat (value); if ((AutoSize && Alignment != TextAlignment.Justified && VerticalAlignment != VerticalTextAlignment.Justified) || (textWasNull && Size.IsEmpty)) @@ -340,7 +340,7 @@ public class TextFormatter bool isVertical = IsVerticalDirection (Direction); Rect maxBounds = bounds; - if (driver != null) + if (driver is { }) { maxBounds = containerBounds == default (Rect) ? bounds @@ -505,7 +505,7 @@ public class TextFormatter { Rune lastRuneUsed = rune; - if (lastZeroWidthPos == null) + if (lastZeroWidthPos is null) { if (idx < 0 || x + current + colOffset < 0) { @@ -540,7 +540,7 @@ public class TextFormatter rune = runes [idx]; } - if (lastZeroWidthPos == null) + if (lastZeroWidthPos is null) { driver?.Move (x, current); } @@ -548,7 +548,7 @@ public class TextFormatter { int foundIdx = lastZeroWidthPos.IndexOf ( p => - p != null && p.Value.Y == current + p is { } && p.Value.Y == current ); if (foundIdx > -1) @@ -611,14 +611,14 @@ public class TextFormatter { if (runeWidth == 0) { - if (lastZeroWidthPos == null) + if (lastZeroWidthPos is null) { lastZeroWidthPos = new List (); } int foundIdx = lastZeroWidthPos.IndexOf ( p => - p != null && p.Value.Y == current + p is { } && p.Value.Y == current ); if (foundIdx == -1) @@ -1764,7 +1764,7 @@ public class TextFormatter /// The index of the last Rune in that fit in . public static int GetLengthThatFits (List runes, int columns, int tabWidth = 0) { - if (runes == null || runes.Count == 0) + if (runes is null || runes.Count == 0) { return 0; } diff --git a/Terminal.Gui/View/Adornment/Adornment.cs b/Terminal.Gui/View/Adornment/Adornment.cs index 551f58df3..37616ae50 100644 --- a/Terminal.Gui/View/Adornment/Adornment.cs +++ b/Terminal.Gui/View/Adornment/Adornment.cs @@ -134,7 +134,7 @@ public class Adornment : View if (!string.IsNullOrEmpty (TextFormatter.Text)) { - if (TextFormatter != null) + if (TextFormatter is { }) { TextFormatter.Size = Frame.Size; TextFormatter.NeedsFormat = true; diff --git a/Terminal.Gui/View/Adornment/Border.cs b/Terminal.Gui/View/Adornment/Border.cs index c93f25d29..cc5973fa1 100644 --- a/Terminal.Gui/View/Adornment/Border.cs +++ b/Terminal.Gui/View/Adornment/Border.cs @@ -63,7 +63,7 @@ public class Border : Adornment { get { - if (base.ColorScheme != null) + if (base.ColorScheme is { }) { return base.ColorScheme; } @@ -317,7 +317,7 @@ public class Border : Adornment Attribute prevAttr = Driver.GetAttribute (); - if (ColorScheme != null) + if (ColorScheme is { }) { Driver.SetAttribute (GetNormalColor ()); } @@ -482,7 +482,7 @@ public class Border : Adornment { prevAttr = Driver.GetAttribute (); - if (ColorScheme != null) + if (ColorScheme is { }) { Driver.SetAttribute (HasFocus ? GetHotNormalColor () : GetNormalColor ()); } diff --git a/Terminal.Gui/View/Adornment/Margin.cs b/Terminal.Gui/View/Adornment/Margin.cs index 0e7d9e6e2..ca2142fc0 100644 --- a/Terminal.Gui/View/Adornment/Margin.cs +++ b/Terminal.Gui/View/Adornment/Margin.cs @@ -25,7 +25,7 @@ public class Margin : Adornment { get { - if (base.ColorScheme != null) + if (base.ColorScheme is { }) { return base.ColorScheme; } diff --git a/Terminal.Gui/View/Adornment/Padding.cs b/Terminal.Gui/View/Adornment/Padding.cs index 7f3a0058f..7909ff77e 100644 --- a/Terminal.Gui/View/Adornment/Padding.cs +++ b/Terminal.Gui/View/Adornment/Padding.cs @@ -25,7 +25,7 @@ public class Padding : Adornment { get { - if (base.ColorScheme != null) + if (base.ColorScheme is { }) { return base.ColorScheme; } diff --git a/Terminal.Gui/View/Layout/PosDim.cs b/Terminal.Gui/View/Layout/PosDim.cs index 25ccf93c7..6da3a0a03 100644 --- a/Terminal.Gui/View/Layout/PosDim.cs +++ b/Terminal.Gui/View/Layout/PosDim.cs @@ -298,7 +298,7 @@ public class Pos { var view = left as PosView; - if (view != null) + if (view is { }) { view.Target.SetNeedsLayout (); } @@ -422,7 +422,7 @@ public class Pos break; } - if (Target == null) + if (Target is null) { throw new NullReferenceException (nameof (Target)); } @@ -726,7 +726,7 @@ public class Dim public override string ToString () { - if (Target == null) + if (Target is null) { throw new NullReferenceException (); } diff --git a/Terminal.Gui/View/Layout/ViewLayout.cs b/Terminal.Gui/View/Layout/ViewLayout.cs index 0ae24ece4..82fc68745 100644 --- a/Terminal.Gui/View/Layout/ViewLayout.cs +++ b/Terminal.Gui/View/Layout/ViewLayout.cs @@ -177,7 +177,7 @@ public partial class View #endif // DEBUG // BUGBUG: I think there's a bug here. This should be && not || - if (Margin == null || Border == null || Padding == null) + if (Margin is null || Border is null || Padding is null) { return new Rect (default (Point), Frame.Size); } @@ -526,7 +526,7 @@ public partial class View View super = SuperView; - while (super != null) + while (super is { }) { boundsOffset = super.GetBoundsOffset (); rx += super.Frame.X + boundsOffset.X; @@ -556,14 +556,14 @@ public partial class View { resy = resx = 0; - if (start == null || !start.Frame.Contains (x, y)) + if (start is null || !start.Frame.Contains (x, y)) { return null; } Rect startFrame = start.Frame; - if (start.InternalSubviews != null) + if (start.InternalSubviews is { }) { int count = start.InternalSubviews.Count; @@ -581,7 +581,7 @@ public partial class View { View deep = FindDeepestView (v, rx, ry, out resx, out resy); - if (deep == null) + if (deep is null) { return v; } @@ -605,7 +605,7 @@ public partial class View Rect ret = Frame; View super = SuperView; - while (super != null) + while (super is { }) { Point boundsOffset = super.GetBoundsOffset (); ret.X += super.Frame.X + boundsOffset.X; @@ -701,7 +701,7 @@ public partial class View // If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case. // Use LayoutSubview with the Frame of the 'from' - if (SuperView != null && GetTopSuperView () != null && LayoutNeeded && edges.Count > 0) + if (SuperView is { } && GetTopSuperView () is { } && LayoutNeeded && edges.Count > 0) { foreach ((View from, View to) in edges) { @@ -738,7 +738,7 @@ public partial class View Point superViewBoundsOffset = SuperView?.GetBoundsOffset () ?? Point.Empty; var ret = new Point (x - Frame.X - superViewBoundsOffset.X, y - Frame.Y - superViewBoundsOffset.Y); - if (SuperView != null) + if (SuperView is { }) { Point superFrame = SuperView.ScreenToFrame (x - superViewBoundsOffset.X, y - superViewBoundsOffset.Y); ret = new Point (superFrame.X - Frame.X, superFrame.Y - Frame.Y); @@ -846,7 +846,7 @@ public partial class View /// Overriden by to do nothing, as the does not have adornments. internal virtual void LayoutAdornments () { - if (Margin == null) + if (Margin is null) { return; // CreateAdornments () has not been called yet } @@ -918,7 +918,7 @@ public partial class View // First try SuperView.Bounds, then Application.Top, then Driver.Bounds. // Finally, if none of those are valid, use int.MaxValue (for Unit tests). Rect relativeBounds = SuperView is { IsInitialized: true } ? SuperView.Bounds : - Application.Top != null && Application.Top.IsInitialized ? Application.Top.Bounds : + Application.Top is { } && Application.Top.IsInitialized ? Application.Top.Bounds : Application.Driver?.Bounds ?? new Rect (0, 0, int.MaxValue, int.MaxValue); SetRelativeLayout (relativeBounds); @@ -970,10 +970,10 @@ public partial class View /// internal void SetRelativeLayout (Rect superviewBounds) { - Debug.Assert (_x != null); - Debug.Assert (_y != null); - Debug.Assert (_width != null); - Debug.Assert (_height != null); + Debug.Assert (_x is { }); + Debug.Assert (_y is { }); + Debug.Assert (_width is { }); + Debug.Assert (_height is { }); int newX, newW, newY, newH; var autosize = Size.Empty; @@ -1248,7 +1248,7 @@ public partial class View if (from == to) { // if not yet added to the result, add it and remove from edge - if (result.Find (v => v == from) == null) + if (result.Find (v => v == from) is null) { result.Add (from); } @@ -1258,13 +1258,13 @@ public partial class View else if (from.SuperView == to.SuperView) { // if 'from' is not yet added to the result, add it - if (result.Find (v => v == from) == null) + if (result.Find (v => v == from) is null) { result.Add (from); } // if 'to' is not yet added to the result, add it - if (result.Find (v => v == to) == null) + if (result.Find (v => v == to) is null) { result.Add (to); } @@ -1319,7 +1319,7 @@ public partial class View break; case Dim.DimFactor factor: // Tries to get the SuperView height otherwise the view height. - int sh = SuperView != null ? SuperView.Frame.Height : h; + int sh = SuperView is { } ? SuperView.Frame.Height : h; if (factor.IsFromRemaining ()) { @@ -1369,7 +1369,7 @@ public partial class View break; case Dim.DimFactor factor: // Tries to get the SuperView Width otherwise the view Width. - int sw = SuperView != null ? SuperView.Frame.Width : w; + int sw = SuperView is { } ? SuperView.Frame.Width : w; if (factor.IsFromRemaining ()) { diff --git a/Terminal.Gui/View/View.cs b/Terminal.Gui/View/View.cs index d04a87461..1ec8d19b6 100644 --- a/Terminal.Gui/View/View.cs +++ b/Terminal.Gui/View/View.cs @@ -139,7 +139,7 @@ public partial class View : Responder, ISupportInitializeNotification { if (value) { - if (SuperView == null || SuperView?.Enabled == true) + if (SuperView is null || SuperView?.Enabled == true) { base.Enabled = value; } @@ -157,7 +157,7 @@ public partial class View : Responder, ISupportInitializeNotification OnEnabledChanged (); SetNeedsDisplay (); - if (_subviews != null) + if (_subviews is { }) { foreach (View view in _subviews) { @@ -198,11 +198,11 @@ public partial class View : Responder, ISupportInitializeNotification _title = value; SetNeedsDisplay (); #if DEBUG - if (_title != null && string.IsNullOrEmpty (Id)) + if (_title is { } && string.IsNullOrEmpty (Id)) { Id = _title; } -#endif // DEBUG +#endif OnTitleChanged (old, _title); } } @@ -438,7 +438,7 @@ public partial class View : Responder, ISupportInitializeNotification OnResizeNeeded (); - if (_subviews != null) + if (_subviews is { }) { foreach (View view in _subviews) { diff --git a/Terminal.Gui/View/ViewDrawing.cs b/Terminal.Gui/View/ViewDrawing.cs index a5d3984f5..0aceac855 100644 --- a/Terminal.Gui/View/ViewDrawing.cs +++ b/Terminal.Gui/View/ViewDrawing.cs @@ -11,7 +11,7 @@ public partial class View { get { - if (_colorScheme == null) + if (_colorScheme is null) { return SuperView?.ColorScheme; } @@ -100,7 +100,7 @@ public partial class View /// The screen-relative rectangle to clear. public void Clear (Rect regionScreen) { - if (Driver == null) + if (Driver is null) { return; } @@ -123,7 +123,7 @@ public partial class View /// public Rect ClipToBounds () { - if (Driver == null) + if (Driver is null) { return Rect.Empty; } @@ -163,7 +163,7 @@ public partial class View Rect prevClip = ClipToBounds (); - if (ColorScheme != null) + if (ColorScheme is { }) { //Driver.SetAttribute (HasFocus ? GetFocusColor () : GetNormalColor ()); Driver?.SetAttribute (GetNormalColor ()); @@ -178,7 +178,7 @@ public partial class View OnDrawContent (Bounds); } - if (Driver != null) + if (Driver is { }) { Driver.Clip = prevClip; } @@ -279,7 +279,7 @@ public partial class View { ColorScheme cs = ColorScheme; - if (ColorScheme == null) + if (ColorScheme is null) { cs = new ColorScheme (); } @@ -297,7 +297,7 @@ public partial class View { ColorScheme cs = ColorScheme; - if (ColorScheme == null) + if (ColorScheme is null) { cs = new ColorScheme (); } @@ -315,7 +315,7 @@ public partial class View { ColorScheme cs = ColorScheme; - if (ColorScheme == null) + if (ColorScheme is null) { cs = new ColorScheme (); } @@ -329,7 +329,7 @@ public partial class View /// the row to move to, in view-relative coordinates. public void Move (int col, int row) { - if (Driver == null || Driver?.Rows == 0) + if (Driver is null || Driver?.Rows == 0) { return; } @@ -371,14 +371,14 @@ public partial class View { if (NeedsDisplay) { - if (SuperView != null) + if (SuperView is { }) { Clear (BoundsToScreen (contentArea)); } if (!string.IsNullOrEmpty (TextFormatter.Text)) { - if (TextFormatter != null) + if (TextFormatter is { }) { TextFormatter.NeedsFormat = true; } @@ -396,7 +396,7 @@ public partial class View // Draw subviews // TODO: Implement OnDrawSubviews (cancelable); - if (_subviews != null && SubViewNeedsDisplay) + if (_subviews is { } && SubViewNeedsDisplay) { IEnumerable subviewsNeedingDraw = _subviews.Where ( view => view.Visible @@ -544,7 +544,7 @@ public partial class View Padding?.SetNeedsDisplay (Padding.Bounds); } - if (_subviews == null) + if (_subviews is null) { return; } @@ -566,7 +566,7 @@ public partial class View { SubViewNeedsDisplay = true; - if (_superView != null && !_superView.SubViewNeedsDisplay) + if (_superView is { } && !_superView.SubViewNeedsDisplay) { _superView.SetSubViewNeedsDisplay (); } diff --git a/Terminal.Gui/View/ViewKeyboard.cs b/Terminal.Gui/View/ViewKeyboard.cs index 7d5efa27e..bac9ea093 100644 --- a/Terminal.Gui/View/ViewKeyboard.cs +++ b/Terminal.Gui/View/ViewKeyboard.cs @@ -199,7 +199,7 @@ public partial class View { get { - if (TextFormatter != null) + if (TextFormatter is { }) { return TextFormatter.HotKeySpecifier; } @@ -215,7 +215,7 @@ public partial class View private void SetHotKey () { - if (TextFormatter == null || HotKeySpecifier == new Rune ('\xFFFF')) + if (TextFormatter is null || HotKeySpecifier == new Rune ('\xFFFF')) { return; // throw new InvalidOperationException ("Can't set HotKey unless a TextFormatter has been created"); } @@ -263,7 +263,7 @@ public partial class View return; } - if (SuperView?._tabIndexes == null || SuperView?._tabIndexes.Count == 1) + if (SuperView?._tabIndexes is null || SuperView?._tabIndexes.Count == 1) { _tabIndex = 0; @@ -401,7 +401,7 @@ public partial class View bool? handled = OnInvokingKeyBindings (keyEvent); - if (handled != null && (bool)handled) + if (handled is { } && (bool)handled) { return true; } @@ -643,7 +643,7 @@ public partial class View // `InvokeKeyBindings` returns `true`. Continue passing the event (return `false` from `OnInvokeKeyBindings`). bool? handled = InvokeKeyBindings (keyEvent); - if (handled != null && (bool)handled) + if (handled is { } && (bool)handled) { // Stop processing if any key binding handled the key. // DO NOT stop processing if there are no matching key bindings or none of the key bindings handled the key @@ -665,7 +665,7 @@ public partial class View keyEvent.Scope = KeyBindingScope.HotKey; handled = view.OnInvokingKeyBindings (keyEvent); - if (handled != null && (bool)handled) + if (handled is { } && (bool)handled) { return true; } @@ -765,7 +765,7 @@ public partial class View // if there is already an implementation of this command // replace that implementation // else record how to perform the action (this should be the normal case) - if (CommandImplementations != null) + if (CommandImplementations is { }) { CommandImplementations [command] = f; } diff --git a/Terminal.Gui/View/ViewMouse.cs b/Terminal.Gui/View/ViewMouse.cs index 2c7df21c1..f0f03f72f 100644 --- a/Terminal.Gui/View/ViewMouse.cs +++ b/Terminal.Gui/View/ViewMouse.cs @@ -61,7 +61,7 @@ public partial class View if (mouseEvent.Flags == MouseFlags.Button1Clicked) { - if (CanFocus && !HasFocus && SuperView != null) + if (CanFocus && !HasFocus && SuperView is { }) { SuperView.SetFocus (this); SetNeedsDisplay (); diff --git a/Terminal.Gui/View/ViewSubViews.cs b/Terminal.Gui/View/ViewSubViews.cs index ad79b96e7..31cf5176f 100644 --- a/Terminal.Gui/View/ViewSubViews.cs +++ b/Terminal.Gui/View/ViewSubViews.cs @@ -36,17 +36,17 @@ public partial class View /// public virtual void Add (View view) { - if (view == null) + if (view is null) { return; } - if (_subviews == null) + if (_subviews is null) { _subviews = new List (); } - if (_tabIndexes == null) + if (_tabIndexes is null) { _tabIndexes = new List (); } @@ -97,7 +97,7 @@ public partial class View /// public void Add (params View [] views) { - if (views == null) + if (views is null) { return; } @@ -188,7 +188,7 @@ public partial class View /// public virtual void Remove (View view) { - if (view == null || _subviews == null) + if (view is null || _subviews is null) { return; } @@ -220,7 +220,7 @@ public partial class View /// Removes all subviews (children) added via or from this View. public virtual void RemoveAll () { - if (_subviews == null) + if (_subviews is null) { return; } @@ -305,7 +305,7 @@ public partial class View get => SuperView?.FocusDirection ?? _focusDirection; set { - if (SuperView != null) + if (SuperView is { }) { SuperView.FocusDirection = value; } @@ -341,7 +341,7 @@ public partial class View } // Remove focus down the chain of subviews if focus is removed - if (!value && Focused != null) + if (!value && Focused is { }) { View f = Focused; f.OnLeave (view); @@ -387,7 +387,7 @@ public partial class View if (value && _tabIndex == -1) { - TabIndex = SuperView != null ? SuperView._tabIndexes.IndexOf (this) : -1; + TabIndex = SuperView is { } ? SuperView._tabIndexes.IndexOf (this) : -1; } TabStop = value; @@ -402,11 +402,11 @@ public partial class View SetHasFocus (false, this); SuperView?.EnsureFocus (); - if (SuperView != null && SuperView.Focused == null) + if (SuperView is { } && SuperView.Focused is null) { SuperView.FocusNext (); - if (SuperView.Focused == null && Application.Current != null) + if (SuperView.Focused is null && Application.Current is { }) { Application.Current.FocusNext (); } @@ -415,7 +415,7 @@ public partial class View } } - if (_subviews != null && IsInitialized) + if (_subviews is { } && IsInitialized) { foreach (View view in _subviews) { @@ -499,14 +499,14 @@ public partial class View { get { - if (Focused == null) + if (Focused is null) { return null; } View most = Focused.MostFocused; - if (most != null) + if (most is { }) { return most; } @@ -519,7 +519,7 @@ public partial class View /// View. private void SetFocus (View view) { - if (view == null) + if (view is null) { return; } @@ -556,12 +556,12 @@ public partial class View } } - if (c == null) + if (c is null) { throw new ArgumentException ("the specified view is not part of the hierarchy of this view"); } - if (Focused != null) + if (Focused is { }) { Focused.SetHasFocus (false, view); } @@ -572,7 +572,7 @@ public partial class View Focused.EnsureFocus (); // Send focus upwards - if (SuperView != null) + if (SuperView is { }) { SuperView.SetFocus (this); } @@ -595,7 +595,7 @@ public partial class View return; } - if (SuperView != null) + if (SuperView is { }) { SuperView.SetFocus (this); } @@ -611,7 +611,7 @@ public partial class View /// public void EnsureFocus () { - if (Focused == null && _subviews?.Count > 0) + if (Focused is null && _subviews?.Count > 0) { if (FocusDirection == NavigationDirection.Forward) { @@ -632,7 +632,7 @@ public partial class View return; } - if (_tabIndexes == null) + if (_tabIndexes is null) { SuperView?.SetFocus (this); @@ -658,7 +658,7 @@ public partial class View return; } - if (_tabIndexes == null) + if (_tabIndexes is null) { SuperView?.SetFocus (this); @@ -691,12 +691,12 @@ public partial class View FocusDirection = NavigationDirection.Backward; - if (_tabIndexes == null || _tabIndexes.Count == 0) + if (_tabIndexes is null || _tabIndexes.Count == 0) { return false; } - if (Focused == null) + if (Focused is null) { FocusLast (); @@ -737,7 +737,7 @@ public partial class View } } - if (Focused != null) + if (Focused is { }) { Focused.SetHasFocus (false, this); Focused = null; @@ -757,12 +757,12 @@ public partial class View FocusDirection = NavigationDirection.Forward; - if (_tabIndexes == null || _tabIndexes.Count == 0) + if (_tabIndexes is null || _tabIndexes.Count == 0) { return false; } - if (Focused == null) + if (Focused is null) { FocusFirst (); @@ -802,7 +802,7 @@ public partial class View } } - if (Focused != null) + if (Focused is { }) { Focused.SetHasFocus (false, this); Focused = null; @@ -813,12 +813,12 @@ public partial class View private View GetMostFocused (View view) { - if (view == null) + if (view is null) { return null; } - return view.Focused != null ? GetMostFocused (view.Focused) : view; + return view.Focused is { } ? GetMostFocused (view.Focused) : view; } /// Positions the cursor in the right position based on the currently focused view in the chain. @@ -838,7 +838,7 @@ public partial class View // BUGBUG: v2 - This needs to support children of Frames too - if (Focused == null && SuperView != null) + if (Focused is null && SuperView is { }) { SuperView.EnsureFocus (); } diff --git a/Terminal.Gui/View/ViewText.cs b/Terminal.Gui/View/ViewText.cs index e620b0008..d1d8e7cfd 100644 --- a/Terminal.Gui/View/ViewText.cs +++ b/Terminal.Gui/View/ViewText.cs @@ -50,7 +50,7 @@ public partial class View OnResizeNeeded (); #if DEBUG - if (_text != null && string.IsNullOrEmpty (Id)) + if (_text is { } && string.IsNullOrEmpty (Id)) { Id = _text; } @@ -183,7 +183,7 @@ public partial class View /// Can be overridden if the has different format than the default. protected virtual void UpdateTextFormatterText () { - if (TextFormatter != null) + if (TextFormatter is { }) { TextFormatter.Text = _text; } @@ -313,7 +313,7 @@ public partial class View // TODO: v2 - This uses frame.Width; it should only use Bounds if (_frame.Width < colWidth - && (Width == null || (Bounds.Width >= 0 && Width is Dim.DimAbsolute && Width.Anchor (0) >= 0 && Width.Anchor (0) < colWidth))) + && (Width is null || (Bounds.Width >= 0 && Width is Dim.DimAbsolute && Width.Anchor (0) >= 0 && Width.Anchor (0) < colWidth))) { sizeRequired = new Size (colWidth, Bounds.Height); @@ -322,7 +322,7 @@ public partial class View break; default: - if (_frame.Height < 1 && (Height == null || (Height is Dim.DimAbsolute && Height.Anchor (0) == 0))) + if (_frame.Height < 1 && (Height is null || (Height is Dim.DimAbsolute && Height.Anchor (0) == 0))) { sizeRequired = new Size (Bounds.Width, 1); diff --git a/Terminal.Gui/Views/AutocompleteFilepathContext.cs b/Terminal.Gui/Views/AutocompleteFilepathContext.cs index aeae12aa7..f577e554f 100644 --- a/Terminal.Gui/Views/AutocompleteFilepathContext.cs +++ b/Terminal.Gui/Views/AutocompleteFilepathContext.cs @@ -25,7 +25,7 @@ internal class FilepathSuggestionGenerator : ISuggestionGenerator state = fileState.State; } - if (state == null) + if (state is null) { return Enumerable.Empty (); } diff --git a/Terminal.Gui/Views/CheckBox.cs b/Terminal.Gui/Views/CheckBox.cs index 334758d45..eca870370 100644 --- a/Terminal.Gui/Views/CheckBox.cs +++ b/Terminal.Gui/Views/CheckBox.cs @@ -68,7 +68,7 @@ public class CheckBox : View get => _checked; set { - if (value == null && !AllowNullChecked) + if (value is null && !AllowNullChecked) { return; } diff --git a/Terminal.Gui/Views/ComboBox.cs b/Terminal.Gui/Views/ComboBox.cs index 322bc32d0..d7251ccce 100644 --- a/Terminal.Gui/Views/ComboBox.cs +++ b/Terminal.Gui/Views/ComboBox.cs @@ -56,7 +56,7 @@ public class ComboBox : View // Determine if this view is hosted inside a dialog and is the only control for (View view = SuperView; view != null; view = view.SuperView) { - if (view is Dialog && SuperView != null && SuperView.Subviews.Count == 1 && SuperView.Subviews [0] == this) + if (view is Dialog && SuperView is { } && SuperView.Subviews.Count == 1 && SuperView.Subviews [0] == this) { _autoHide = false; @@ -128,7 +128,7 @@ public class ComboBox : View if (_search.ReadOnly) { - if (_search.ColorScheme != null) + if (_search.ColorScheme is { }) { _search.ColorScheme = new ColorScheme (_search.ColorScheme) { Normal = _search.ColorScheme.Focus }; } @@ -152,7 +152,7 @@ public class ComboBox : View { if (_selectedItem != value && (value == -1 - || (_source != null && value > -1 && value < _source.Count))) + || (_source is { } && value > -1 && value < _source.Count))) { _selectedItem = _lastSelectedItem = value; @@ -181,7 +181,7 @@ public class ComboBox : View _source = value; // Only need to refresh list if its been added to a container view - if (SuperView != null && SuperView.Subviews.Contains (this)) + if (SuperView is { } && SuperView.Subviews.Contains (this)) { SelectedItem = -1; _search.Text = ""; @@ -372,7 +372,7 @@ public class ComboBox : View /// public void SetSource (IList source) { - if (source == null) + if (source is null) { Source = null; } @@ -605,7 +605,7 @@ public class ComboBox : View private void ProcessLayout () { - if (Bounds.Height < _minimumHeight && (Height == null || Height is Dim.DimAbsolute)) + if (Bounds.Height < _minimumHeight && (Height is null || Height is Dim.DimAbsolute)) { Height = _minimumHeight; } @@ -723,7 +723,7 @@ public class ComboBox : View private void SetSearchSet () { - if (Source == null) + if (Source is null) { return; } @@ -873,7 +873,7 @@ public class ComboBox : View Move (0, row); - if (Source == null || item >= Source.Count) + if (Source is null || item >= Source.Count) { for (var c = 0; c < f.Width; c++) { @@ -885,7 +885,7 @@ public class ComboBox : View var rowEventArgs = new ListViewRowEventArgs (item); OnRowRender (rowEventArgs); - if (rowEventArgs.RowAttribute != null && current != rowEventArgs.RowAttribute) + if (rowEventArgs.RowAttribute is { } && current != rowEventArgs.RowAttribute) { current = (Attribute)rowEventArgs.RowAttribute; Driver.SetAttribute (current); diff --git a/Terminal.Gui/Views/Dialog.cs b/Terminal.Gui/Views/Dialog.cs index 9f8df664c..7b821bf13 100644 --- a/Terminal.Gui/Views/Dialog.cs +++ b/Terminal.Gui/Views/Dialog.cs @@ -80,7 +80,7 @@ public class Dialog : Window get => _buttons.ToArray (); init { - if (value == null) + if (value is null) { return; } @@ -105,7 +105,7 @@ public class Dialog : Window /// Button to add. public void AddButton (Button button) { - if (button == null) + if (button is null) { return; } diff --git a/Terminal.Gui/Views/FileDialog.cs b/Terminal.Gui/Views/FileDialog.cs index 01a26ad16..0ec02269d 100644 --- a/Terminal.Gui/Views/FileDialog.cs +++ b/Terminal.Gui/Views/FileDialog.cs @@ -257,7 +257,7 @@ public class FileDialog : Dialog { IFileSystemInfo selected = _treeView.SelectedObject; - if (selected != null) + if (selected is { }) { if (!_treeView.CanExpand (selected) || _treeView.IsExpanded (selected)) { @@ -705,7 +705,7 @@ public class FileDialog : Dialog if (!IsCompatibleWithOpenMode (_tbPath.Text, out string reason)) { - if (reason != null) + if (reason is { }) { _feedback = reason; SetNeedsDisplay (); @@ -746,7 +746,7 @@ public class FileDialog : Dialog _tbPath.ClearAllSelection (); _tbPath.Autocomplete.ClearSuggestions (); - if (State != null) + if (State is { }) { State.RefreshChildren (); WriteStateToTableView (); @@ -842,7 +842,7 @@ public class FileDialog : Dialog { IFileSystemInfo [] toDelete = GetFocusedFiles (); - if (toDelete != null && FileOperationsHandler.Delete (toDelete)) + if (toDelete is { } && FileOperationsHandler.Delete (toDelete)) { RefreshState (); } @@ -876,7 +876,7 @@ public class FileDialog : Dialog private IFileSystemInfo [] GetFocusedFiles () { - if (!_tableView.HasFocus || !_tableView.CanFocus || FileOperationsHandler == null) + if (!_tableView.HasFocus || !_tableView.CanFocus || FileOperationsHandler is null) { return null; } @@ -1025,7 +1025,7 @@ public class FileDialog : Dialog { FileSystemInfoStats add = State?.Children [p.Y]; - if (add != null) + if (add is { }) { toReturn.Add (add); } @@ -1054,11 +1054,11 @@ public class FileDialog : Dialog private void New () { - if (State != null) + if (State is { }) { IFileSystemInfo created = FileOperationsHandler.New (_fileSystem, State.Directory); - if (created != null) + if (created is { }) { RefreshState (); RestoreSelection (created); @@ -1070,7 +1070,7 @@ public class FileDialog : Dialog { Point? clickedCell = _tableView.ScreenToCell (e.MouseEvent.X, e.MouseEvent.Y, out int? clickedCol); - if (clickedCol != null) + if (clickedCol is { }) { if (e.MouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked)) { @@ -1085,7 +1085,7 @@ public class FileDialog : Dialog } else { - if (clickedCell != null && e.MouseEvent.Flags.HasFlag (MouseFlags.Button3Clicked)) + if (clickedCell is { } && e.MouseEvent.Flags.HasFlag (MouseFlags.Button3Clicked)) { // right click in rest of table ShowCellContextMenu (clickedCell, e); @@ -1149,7 +1149,7 @@ public class FileDialog : Dialog _tbPath.Autocomplete.ClearSuggestions (); - if (pathText != null) + if (pathText is { }) { Path = pathText; } @@ -1199,7 +1199,7 @@ public class FileDialog : Dialog { IFileSystemInfo newNamed = FileOperationsHandler.Rename (_fileSystem, toRename.Single ()); - if (newNamed != null) + if (newNamed is { }) { RefreshState (); RestoreSelection (newNamed); @@ -1219,7 +1219,7 @@ public class FileDialog : Dialog // ClearFeedback (); - // if (allowedTypeMenuBar != null && + // if (allowedTypeMenuBar is { } && // keyEvent.ConsoleDriverKey == Key.Tab && // allowedTypeMenuBar.IsMenuOpen) { // allowedTypeMenuBar.CloseMenu (false, false, false); @@ -1229,7 +1229,7 @@ public class FileDialog : Dialog // } private void RestartSearch () { - if (_disposed || State?.Directory == null) + if (_disposed || State?.Directory is null) { return; } @@ -1240,7 +1240,7 @@ public class FileDialog : Dialog } // user is clearing search terms - if (_tbFind.Text == null || _tbFind.Text.Length == 0) + if (_tbFind.Text is null || _tbFind.Text.Length == 0) { // Wait for search cancellation (if any) to finish // then push the current dir state @@ -1259,7 +1259,7 @@ public class FileDialog : Dialog private void ShowCellContextMenu (Point? clickedCell, MouseEventEventArgs e) { - if (clickedCell == null) + if (clickedCell is null) { return; } @@ -1394,7 +1394,7 @@ public class FileDialog : Dialog FileSystemInfoStats stats = RowToStats (obj.NewRow); - if (stats == null) + if (stats is null) { return; } @@ -1439,7 +1439,7 @@ public class FileDialog : Dialog private void TreeView_SelectionChanged (object sender, SelectionChangedEventArgs e) { - if (e.NewValue == null) + if (e.NewValue is null) { return; } @@ -1469,7 +1469,7 @@ public class FileDialog : Dialog return true; } - if (reason != null) + if (reason is { }) { _feedback = reason; SetNeedsDisplay (); @@ -1487,7 +1487,7 @@ public class FileDialog : Dialog private void WriteStateToTableView () { - if (State == null) + if (State is null) { return; } @@ -1511,7 +1511,7 @@ public class FileDialog : Dialog _fileDialog.State?.Children [idx] ); - if (val == null) + if (val is null) { return string.Empty; } diff --git a/Terminal.Gui/Views/FileDialogTableSource.cs b/Terminal.Gui/Views/FileDialogTableSource.cs index 1760e7d7b..c142d3dc8 100644 --- a/Terminal.Gui/Views/FileDialogTableSource.cs +++ b/Terminal.Gui/Views/FileDialogTableSource.cs @@ -65,7 +65,7 @@ internal class FileDialogTableSource : ITableSource case 1: return stats?.HumanReadableLength ?? string.Empty; case 2: - if (stats == null || stats.IsParent || stats.LastWriteTime == null) + if (stats is null || stats.IsParent || stats.LastWriteTime is null) { return string.Empty; } diff --git a/Terminal.Gui/Views/GraphView/Series.cs b/Terminal.Gui/Views/GraphView/Series.cs index 8099a1f03..94f94c781 100644 --- a/Terminal.Gui/Views/GraphView/Series.cs +++ b/Terminal.Gui/Views/GraphView/Series.cs @@ -64,7 +64,7 @@ public class MultiBarSeries : ISeries { subSeries = new BarSeries [numberOfBarsPerCategory]; - if (colors != null && colors.Length != numberOfBarsPerCategory) + if (colors is { } && colors.Length != numberOfBarsPerCategory) { throw new ArgumentException ( "Number of colors must match the number of bars", @@ -81,7 +81,7 @@ public class MultiBarSeries : ISeries // Only draw labels for the first bar in each category subSeries [i].DrawLabels = i == 0; - if (colors != null) + if (colors is { }) { subSeries [i].OverrideBarColor = colors [i]; } diff --git a/Terminal.Gui/Views/HexView.cs b/Terminal.Gui/Views/HexView.cs index db665e500..d9dfd690f 100644 --- a/Terminal.Gui/Views/HexView.cs +++ b/Terminal.Gui/Views/HexView.cs @@ -173,7 +173,7 @@ public class HexView : View get => source; set { - if (value == null) + if (value is null) { throw new ArgumentNullException ("source"); } @@ -233,7 +233,7 @@ public class HexView : View source.WriteByte (kv.Value); source.Flush (); - if (stream != null) + if (stream is { }) { stream.Position = kv.Key; stream.WriteByte (kv.Value); diff --git a/Terminal.Gui/Views/Label.cs b/Terminal.Gui/Views/Label.cs index 1cce02e4f..82cd9644f 100644 --- a/Terminal.Gui/Views/Label.cs +++ b/Terminal.Gui/Views/Label.cs @@ -77,7 +77,7 @@ public class Label : View if (mouseEvent.Flags == MouseFlags.Button1Clicked) { - if (!HasFocus && SuperView != null) + if (!HasFocus && SuperView is { }) { if (!SuperView.HasFocus) { diff --git a/Terminal.Gui/Views/ListView.cs b/Terminal.Gui/Views/ListView.cs index a559a42d9..a85f8ec6c 100644 --- a/Terminal.Gui/Views/ListView.cs +++ b/Terminal.Gui/Views/ListView.cs @@ -172,7 +172,7 @@ public class ListView : View { _allowsMultipleSelection = value; - if (Source != null && !_allowsMultipleSelection) + if (Source is { } && !_allowsMultipleSelection) { // Clear all selections except selected for (var i = 0; i < Source.Count; i++) @@ -201,7 +201,7 @@ public class ListView : View get => _left; set { - if (_source == null) + if (_source is null) { return; } @@ -226,7 +226,7 @@ public class ListView : View get => _selected; set { - if (_source == null || _source.Count == 0) + if (_source is null || _source.Count == 0) { return; } @@ -265,7 +265,7 @@ public class ListView : View get => _top; set { - if (_source == null) + if (_source is null) { return; } @@ -363,7 +363,7 @@ public class ListView : View SetFocus (); } - if (_source == null) + if (_source is null) { return false; } @@ -643,7 +643,7 @@ public class ListView : View Move (0, row); - if (_source == null || item >= _source.Count) + if (_source is null || item >= _source.Count) { for (var c = 0; c < f.Width; c++) { @@ -655,7 +655,7 @@ public class ListView : View var rowEventArgs = new ListViewRowEventArgs (item); OnRowRender (rowEventArgs); - if (rowEventArgs.RowAttribute != null && current != rowEventArgs.RowAttribute) + if (rowEventArgs.RowAttribute is { } && current != rowEventArgs.RowAttribute) { current = (Attribute)rowEventArgs.RowAttribute; Driver.SetAttribute (current); @@ -695,7 +695,7 @@ public class ListView : View /// public virtual bool OnOpenSelectedItem () { - if (_source.Count <= _selected || _selected < 0 || OpenSelectedItem == null) + if (_source.Count <= _selected || _selected < 0 || OpenSelectedItem is null) { return false; } @@ -819,7 +819,7 @@ public class ListView : View /// public void SetSource (IList source) { - if (source == null && (Source == null || !(Source is ListWrapper))) + if (source is null && (Source is null || !(Source is ListWrapper))) { Source = null; } @@ -840,7 +840,7 @@ public class ListView : View return Task.Factory.StartNew ( () => { - if (source == null && (Source == null || !(Source is ListWrapper))) + if (source is null && (Source is null || !(Source is ListWrapper))) { Source = null; } @@ -873,7 +873,7 @@ public class ListWrapper : IListDataSource /// public ListWrapper (IList source) { - if (source != null) + if (source is { }) { _count = source.Count; _marks = new BitArray (_count); @@ -883,7 +883,7 @@ public class ListWrapper : IListDataSource } /// - public int Count => _source != null ? _source.Count : 0; + public int Count => _source is { } ? _source.Count : 0; /// public int Length { get; } @@ -903,7 +903,7 @@ public class ListWrapper : IListDataSource container.Move (col, line); object t = _source? [item]; - if (t == null) + if (t is null) { RenderUstr (driver, "", col, line, width); } @@ -950,7 +950,7 @@ public class ListWrapper : IListDataSource /// public int StartsWith (string search) { - if (_source == null || _source?.Count == 0) + if (_source is null || _source?.Count == 0) { return -1; } @@ -980,7 +980,7 @@ public class ListWrapper : IListDataSource private int GetMaxLengthItem () { - if (_source == null || _source?.Count == 0) + if (_source is null || _source?.Count == 0) { return 0; } diff --git a/Terminal.Gui/Views/Menu/ContextMenu.cs b/Terminal.Gui/Views/Menu/ContextMenu.cs index cd7d3dad7..2957b5d18 100644 --- a/Terminal.Gui/Views/Menu/ContextMenu.cs +++ b/Terminal.Gui/Views/Menu/ContextMenu.cs @@ -33,7 +33,7 @@ public sealed class ContextMenu : IDisposable { if (IsShow) { - if (_menuBar.SuperView != null) + if (_menuBar.SuperView is { }) { Hide (); } @@ -113,7 +113,7 @@ public sealed class ContextMenu : IDisposable IsShow = false; } - if (_container != null) + if (_container is { }) { _container.Closing -= Container_Closing; } @@ -135,7 +135,7 @@ public sealed class ContextMenu : IDisposable /// Shows (opens) the ContextMenu, displaying the s it contains. public void Show () { - if (_menuBar != null) + if (_menuBar is { }) { Hide (); } @@ -145,7 +145,7 @@ public sealed class ContextMenu : IDisposable Rect frame = Application.Driver.Bounds; Point position = Position; - if (Host != null) + if (Host is { }) { Host.BoundsToScreen (frame.X, frame.Y, out int x, out int y); var pos = new Point (x, y); @@ -179,7 +179,7 @@ public sealed class ContextMenu : IDisposable { if (frame.Bottom - rect.Height - 1 >= 0 || !ForceMinimumPosToZero) { - if (Host == null) + if (Host is null) { position.Y = frame.Bottom - rect.Height - 1; } diff --git a/Terminal.Gui/Views/Menu/Menu.cs b/Terminal.Gui/Views/Menu/Menu.cs index 2b749afa4..60a3134e2 100644 --- a/Terminal.Gui/Views/Menu/Menu.cs +++ b/Terminal.Gui/Views/Menu/Menu.cs @@ -103,7 +103,7 @@ public class MenuItem { _checkType = value; - if (_checkType == MenuItemCheckStyle.Checked && !_allowNullChecked && Checked == null) + if (_checkType == MenuItemCheckStyle.Checked && !_allowNullChecked && Checked is null) { Checked = false; } @@ -300,7 +300,7 @@ internal sealed class Menu : View internal static Rect MakeFrame (int x, int y, MenuItem [] items, Menu parent = null) { - if (items == null || items.Length == 0) + if (items is null || items.Length == 0) { return new Rect (); } @@ -311,7 +311,7 @@ internal sealed class Menu : View int maxW = (items.Max (z => z?.Width) ?? 0) + borderOffset; int maxH = items.Length + borderOffset; - if (parent != null && x + maxW > Driver.Cols) + if (parent is { } && x + maxW > Driver.Cols) { minX = Math.Max (parent.Frame.Right - parent.Frame.Width - maxW, 0); } @@ -411,7 +411,7 @@ internal sealed class Menu : View #if SUPPORT_ALT_TO_ACTIVATE_MENU Initialized += (s, e) => { - if (SuperView != null) + if (SuperView is { }) { SuperView.KeyUp += SuperView_KeyUp; } @@ -421,7 +421,7 @@ internal sealed class Menu : View public Menu () { - if (Application.Current != null) + if (Application.Current is { }) { Application.Current.DrawContentComplete += Current_DrawContentComplete; Application.Current.SizeChanging += Current_TerminalResized; @@ -485,7 +485,7 @@ internal sealed class Menu : View #if SUPPORT_ALT_TO_ACTIVATE_MENU void SuperView_KeyUp (object sender, KeyEventArgs e) { - if (SuperView == null || SuperView.CanFocus == false || SuperView.Visible == false) + if (SuperView is null || SuperView.CanFocus == false || SuperView.Visible == false) { return; } @@ -496,12 +496,12 @@ internal sealed class Menu : View private void AddKeyBindings (MenuBarItem menuBarItem) { - if (menuBarItem == null || menuBarItem.Children == null) + if (menuBarItem is null || menuBarItem.Children is null) { return; } - foreach (MenuItem menuItem in menuBarItem.Children.Where (m => m != null)) + foreach (MenuItem menuItem in menuBarItem.Children.Where (m => m is { })) { KeyBindings.Add ((KeyCode)menuItem.HotKey.Value, Command.ToggleExpandCollapse); @@ -536,7 +536,7 @@ internal sealed class Menu : View { _host.Activate (1, _menuBarItemToActivate); } - else if (_menuItemToSelect != null) + else if (_menuItemToSelect is { }) { var m = _menuItemToSelect as MenuBarItem; @@ -544,12 +544,12 @@ internal sealed class Menu : View { MenuItem item = _barItems.Children [_currentChild]; - if (item == null) + if (item is null) { return true; } - bool disabled = item == null || !item.IsEnabled (); + bool disabled = item is null || !item.IsEnabled (); if (!disabled && (_host.UseSubMenusSingleFrame || !CheckSubMenu ())) { @@ -598,7 +598,7 @@ internal sealed class Menu : View MenuItem [] children = _barItems.Children; - if (children == null) + if (children is null) { return base.OnInvokingKeyBindings (keyEvent); } @@ -656,7 +656,7 @@ internal sealed class Menu : View bool? handled = base.OnInvokingKeyBindings (keyEvent); - if (handled != null && (bool)handled) + if (handled is { } && (bool)handled) { return true; } @@ -667,7 +667,7 @@ internal sealed class Menu : View private bool FindShortcutInChildMenu (KeyCode key, MenuBarItem menuBarItem) { - if (menuBarItem?.Children == null) + if (menuBarItem?.Children is null) { return false; } @@ -721,7 +721,7 @@ internal sealed class Menu : View Point locationOffset = _host.GetScreenOffsetFromCurrent (); - if (SuperView != null && SuperView != Application.Current) + if (SuperView is { } && SuperView != Application.Current) { locationOffset.X += SuperView.Border.Thickness.Left; locationOffset.Y += SuperView.Border.Thickness.Top; @@ -753,7 +753,7 @@ internal sealed class Menu : View internal Attribute DetermineColorSchemeFor (MenuItem item, int index) { - if (item == null) + if (item is null) { return GetNormalColor (); } @@ -768,7 +768,7 @@ internal sealed class Menu : View public override void OnDrawContent (Rect contentArea) { - if (_barItems.Children == null) + if (_barItems.Children is null) { return; } @@ -795,11 +795,11 @@ internal sealed class Menu : View MenuItem item = _barItems.Children [i]; Driver.SetAttribute ( - item == null ? GetNormalColor () : + item is null ? GetNormalColor () : i == _currentChild ? ColorScheme.Focus : GetNormalColor () ); - if (item == null && BorderStyle != LineStyle.None) + if (item is null && BorderStyle != LineStyle.None) { Move (-1, i); Driver.AddRune (Glyphs.LeftTee); @@ -824,17 +824,17 @@ internal sealed class Menu : View break; } - if (item == null) + if (item is null) { Driver.AddRune (Glyphs.HLine); } - else if (i == 0 && p == 0 && _host.UseSubMenusSingleFrame && item.Parent.Parent != null) + else if (i == 0 && p == 0 && _host.UseSubMenusSingleFrame && item.Parent.Parent is { }) { Driver.AddRune (Glyphs.LeftArrow); } // This `- 3` is left border + right border + one row in from right - else if (p == Frame.Width - 3 && _barItems.SubMenu (_barItems.Children [i]) != null) + else if (p == Frame.Width - 3 && _barItems.SubMenu (_barItems.Children [i]) is { }) { Driver.AddRune (Glyphs.RightArrow); } @@ -844,7 +844,7 @@ internal sealed class Menu : View } } - if (item == null) + if (item is null) { if (BorderStyle != LineStyle.None && SuperView?.Frame.Right - Frame.X > Frame.Width) { @@ -867,7 +867,7 @@ internal sealed class Menu : View } // Support Checked even though CheckType wasn't set - if (item.CheckType == MenuItemCheckStyle.Checked && item.Checked == null) + if (item.CheckType == MenuItemCheckStyle.Checked && item.Checked is null) { textToDraw = $"{nullCheckedChar} {item.Title}"; } @@ -894,7 +894,7 @@ internal sealed class Menu : View { DrawHotString (textToDraw, ColorScheme.Disabled, ColorScheme.Disabled); } - else if (i == 0 && _host.UseSubMenusSingleFrame && item.Parent.Parent != null) + else if (i == 0 && _host.UseSubMenusSingleFrame && item.Parent.Parent is { }) { var tf = new TextFormatter { @@ -974,7 +974,7 @@ internal sealed class Menu : View public void Run (Action action) { - if (action == null || _host == null) + if (action is null || _host is null) { return; } @@ -1075,7 +1075,7 @@ internal sealed class Menu : View _host.OpenMenu (_host._selected); } } - while (_barItems.Children [_currentChild] == null || disabled); + while (_barItems.Children [_currentChild] is null || disabled); SetNeedsDisplay (); SetParentSetNeedsDisplay (); @@ -1156,7 +1156,7 @@ internal sealed class Menu : View break; } - while (_barItems.Children [_currentChild] == null || disabled); + while (_barItems.Children [_currentChild] is null || disabled); SetNeedsDisplay (); SetParentSetNeedsDisplay (); @@ -1171,7 +1171,7 @@ internal sealed class Menu : View private void SetParentSetNeedsDisplay () { - if (_host._openSubMenu != null) + if (_host._openSubMenu is { }) { foreach (Menu menu in _host._openSubMenu) { @@ -1192,7 +1192,7 @@ internal sealed class Menu : View _host._handled = false; bool disabled; - int meY = me.Y - (Border == null ? 0 : Border.Thickness.Top); + int meY = me.Y - (Border is null ? 0 : Border.Thickness.Top); if (me.Flags == MouseFlags.Button1Clicked) { @@ -1210,7 +1210,7 @@ internal sealed class Menu : View MenuItem item = _barItems.Children [meY]; - if (item == null || !item.IsEnabled ()) + if (item is null || !item.IsEnabled ()) { disabled = true; } @@ -1245,7 +1245,7 @@ internal sealed class Menu : View MenuItem item = _barItems.Children [meY]; - if (item == null) + if (item is null) { return true; } @@ -1276,18 +1276,18 @@ internal sealed class Menu : View internal bool CheckSubMenu () { - if (_currentChild == -1 || _barItems.Children [_currentChild] == null) + if (_currentChild == -1 || _barItems.Children [_currentChild] is null) { return true; } MenuBarItem subMenu = _barItems.SubMenu (_barItems.Children [_currentChild]); - if (subMenu != null) + if (subMenu is { }) { int pos = -1; - if (_host._openSubMenu != null) + if (_host._openSubMenu is { }) { pos = _host._openSubMenu.FindIndex (o => o?._barItems == subMenu); } @@ -1334,7 +1334,7 @@ internal sealed class Menu : View } } - if (v != null) + if (v is { }) { pos = Subviews.IndexOf (v); } @@ -1352,7 +1352,7 @@ internal sealed class Menu : View protected override void Dispose (bool disposing) { - if (Application.Current != null) + if (Application.Current is { }) { Application.Current.DrawContentComplete -= Current_DrawContentComplete; Application.Current.SizeChanging -= Current_TerminalResized; diff --git a/Terminal.Gui/Views/Menu/MenuBar.cs b/Terminal.Gui/Views/Menu/MenuBar.cs index 0c6b923f2..ace5e588e 100644 --- a/Terminal.Gui/Views/Menu/MenuBar.cs +++ b/Terminal.Gui/Views/Menu/MenuBar.cs @@ -49,7 +49,7 @@ public class MenuBarItem : MenuItem /// The children. public MenuItem [] Children { get; set; } - internal bool IsTopLevel => Parent == null && (Children == null || Children.Length == 0) && Action != null; + internal bool IsTopLevel => Parent is null && (Children is null || Children.Length == 0) && Action != null; /// Get the index of a child . /// @@ -58,7 +58,7 @@ public class MenuBarItem : MenuItem { var i = 0; - if (Children != null) + if (Children is { }) { foreach (MenuItem child in Children) { @@ -97,12 +97,12 @@ public class MenuBarItem : MenuItem internal void AddKeyBindings (MenuBar menuBar) { - if (Children == null) + if (Children is null) { return; } - foreach (MenuItem menuItem in Children.Where (m => m != null)) + foreach (MenuItem menuItem in Children.Where (m => m is { })) { if (menuItem.HotKey != default (Rune)) { @@ -126,7 +126,7 @@ public class MenuBarItem : MenuItem private void SetInitialProperties (string title, object children, MenuItem parent = null, bool isTopLevel = false) { - if (!isTopLevel && children == null) + if (!isTopLevel && children is null) { throw new ArgumentNullException ( nameof (children), @@ -136,7 +136,7 @@ public class MenuBarItem : MenuItem SetTitle (title ?? ""); - if (parent != null) + if (parent is { }) { Parent = parent; } @@ -345,7 +345,7 @@ public class MenuBar : View { _menus = value; - if (Menus == null) + if (Menus is null) { return; } @@ -353,7 +353,7 @@ public class MenuBar : View // TODO: Bindings (esp for hotkey) should be added across and then down. This currently does down then across. // TODO: As a result, _File._Save will have precedence over in "_File _Edit _ScrollbarView" // TODO: Also: Hotkeys should not work for sub-menus if they are not visible! - foreach (MenuBarItem menuBarItem in Menus?.Where (m => m != null)!) + foreach (MenuBarItem menuBarItem in Menus?.Where (m => m is { })!) { if (menuBarItem.HotKey != default (Rune)) { @@ -381,7 +381,7 @@ public class MenuBar : View // Enable the Alt key as a menu activator Initialized += (s, e) => { - if (SuperView != null) + if (SuperView is { }) { SuperView.KeyUp += SuperView_KeyUp; } @@ -445,7 +445,7 @@ public class MenuBar : View { _ocm = value; - if (_ocm != null && _ocm._currentChild > -1) + if (_ocm is { } && _ocm._currentChild > -1) { OnMenuOpened (); } @@ -575,12 +575,12 @@ public class MenuBar : View { MenuBar mbar = GetMouseGrabViewInstance (this); - if (mbar != null) + if (mbar is { }) { mbar.CleanUp (); } - if (!Enabled || _openMenu != null) + if (!Enabled || _openMenu is { }) { return; } @@ -588,7 +588,7 @@ public class MenuBar : View _selected = 0; SetNeedsDisplay (); - _previousFocused = SuperView == null ? Application.Current.Focused : SuperView.Focused; + _previousFocused = SuperView is null ? Application.Current.Focused : SuperView.Focused; OpenMenu (_selected); if (!SelectEnabledItem ( @@ -645,9 +645,9 @@ public class MenuBar : View _selected = idx; _selectedSub = sIdx; - if (_openMenu == null) + if (_openMenu is null) { - _previousFocused = SuperView == null ? Application.Current?.Focused ?? null : SuperView.Focused; + _previousFocused = SuperView is null ? Application.Current?.Focused ?? null : SuperView.Focused; } OpenMenu (idx, sIdx, subMenu); @@ -661,7 +661,7 @@ public class MenuBar : View e.Handled = true; // User pressed Alt - if (!IsMenuOpen && _openMenu == null && !_openedByAltKey) + if (!IsMenuOpen && _openMenu is null && !_openedByAltKey) { // There's no open menu, the first menu item should be highlighted. // The right way to do this is to SetFocus(MenuBar), but for some reason @@ -698,7 +698,7 @@ public class MenuBar : View { _isCleaning = true; - if (_openMenu != null) + if (_openMenu is { }) { CloseAllMenus (); } @@ -709,7 +709,7 @@ public class MenuBar : View _selected = -1; CanFocus = _initialCanFocus; - if (_lastFocused != null) + if (_lastFocused is { }) { _lastFocused.SetFocus (); } @@ -723,7 +723,7 @@ public class MenuBar : View { if (!_isMenuOpening && !_isMenuClosing) { - if (_openSubMenu != null && !CloseMenu (false, true, true)) + if (_openSubMenu is { } && !CloseMenu (false, true, true)) { return; } @@ -733,7 +733,7 @@ public class MenuBar : View return; } - if (LastFocused != null && LastFocused != this) + if (LastFocused is { } && LastFocused != this) { _selected = -1; } @@ -741,7 +741,7 @@ public class MenuBar : View Application.UngrabMouse (); } - if (openCurrentMenu != null) + if (openCurrentMenu is { }) { openCurrentMenu = null; } @@ -756,7 +756,7 @@ public class MenuBar : View { MenuBarItem mbi = isSubMenu ? openCurrentMenu.BarItems : _openMenu?.BarItems; - if (UseSubMenusSingleFrame && mbi != null && !ignoreUseSubMenusSingleFrame && mbi.Parent != null) + if (UseSubMenusSingleFrame && mbi is { } && !ignoreUseSubMenusSingleFrame && mbi.Parent is { }) { return false; } @@ -769,7 +769,7 @@ public class MenuBar : View { _isMenuClosing = false; - if (args.CurrentMenu.Parent != null) + if (args.CurrentMenu.Parent is { }) { _openMenu._currentChild = ((MenuBarItem)args.CurrentMenu.Parent).Children.IndexOf (args.CurrentMenu); @@ -781,14 +781,14 @@ public class MenuBar : View switch (isSubMenu) { case false: - if (_openMenu != null) + if (_openMenu is { }) { Application.Current.Remove (_openMenu); } SetNeedsDisplay (); - if (_previousFocused != null && _previousFocused is Menu && _openMenu != null && _previousFocused.ToString () != openCurrentMenu.ToString ()) + if (_previousFocused is { } && _previousFocused is Menu && _openMenu is { } && _previousFocused.ToString () != openCurrentMenu.ToString ()) { _previousFocused.SetFocus (); } @@ -804,19 +804,19 @@ public class MenuBar : View LastFocused = _lastFocused; _lastFocused = null; - if (LastFocused != null && LastFocused.CanFocus) + if (LastFocused is { } && LastFocused.CanFocus) { if (!reopen) { _selected = -1; } - if (_openSubMenu != null) + if (_openSubMenu is { }) { _openSubMenu = null; } - if (openCurrentMenu != null) + if (openCurrentMenu is { }) { Application.Current.Remove (openCurrentMenu); openCurrentMenu.Dispose (); @@ -825,7 +825,7 @@ public class MenuBar : View LastFocused.SetFocus (); } - else if (_openSubMenu == null || _openSubMenu.Count == 0) + else if (_openSubMenu is null || _openSubMenu.Count == 0) { CloseAllMenus (); } @@ -860,13 +860,13 @@ public class MenuBar : View /// The location offset. internal Point GetScreenOffset () { - if (Driver == null) + if (Driver is null) { return Point.Empty; } - Rect superViewFrame = SuperView == null ? Driver.Bounds : SuperView.Frame; - View sv = SuperView == null ? Application.Current : SuperView; + Rect superViewFrame = SuperView is null ? Driver.Bounds : SuperView.Frame; + View sv = SuperView is null ? Application.Current : SuperView; Point boundsOffset = sv.GetBoundsOffset (); return new Point ( @@ -937,9 +937,9 @@ public class MenuBar : View ) : null; - if ((_selectedSub == -1 || _openSubMenu == null || _openSubMenu?.Count - 1 == _selectedSub) && subMenu == null) + if ((_selectedSub == -1 || _openSubMenu is null || _openSubMenu?.Count - 1 == _selectedSub) && subMenu is null) { - if (_openSubMenu != null && !CloseMenu (false, true)) + if (_openSubMenu is { } && !CloseMenu (false, true)) { return; } @@ -989,7 +989,7 @@ public class MenuBar : View return; } - if (newMenu.NewMenuBarItem != null) + if (newMenu.NewMenuBarItem is { }) { Menus [index] = newMenu.NewMenuBarItem; } @@ -1000,14 +1000,14 @@ public class MenuBar : View { case null: // Open a submenu below a MenuBar - _lastFocused ??= SuperView == null ? Application.Current?.MostFocused : SuperView.MostFocused; + _lastFocused ??= SuperView is null ? Application.Current?.MostFocused : SuperView.MostFocused; - if (_openSubMenu != null && !CloseMenu (false, true)) + if (_openSubMenu is { } && !CloseMenu (false, true)) { return; } - if (_openMenu != null) + if (_openMenu is { }) { Application.Current.Remove (_openMenu); _openMenu.Dispose (); @@ -1024,12 +1024,12 @@ public class MenuBar : View var locationOffset = Point.Empty; // if SuperView is null then it's from a ContextMenu - if (SuperView == null) + if (SuperView is null) { locationOffset = GetScreenOffset (); } - if (SuperView != null && SuperView != Application.Current) + if (SuperView is { } && SuperView != Application.Current) { locationOffset.X += SuperView.Border.Thickness.Left; locationOffset.Y += SuperView.Border.Thickness.Top; @@ -1052,7 +1052,7 @@ public class MenuBar : View break; default: // Opens a submenu next to another submenu (openSubMenu) - if (_openSubMenu == null) + if (_openSubMenu is null) { _openSubMenu = new List (); } @@ -1176,7 +1176,7 @@ public class MenuBar : View internal void RemoveAllOpensSubMenus () { - if (_openSubMenu != null) + if (_openSubMenu is { }) { foreach (Menu item in _openSubMenu) { @@ -1188,7 +1188,7 @@ public class MenuBar : View internal bool Run (Action action) { - if (action == null) + if (action is null) { return false; } @@ -1212,7 +1212,7 @@ public class MenuBar : View bool forward = true ) { - if (chldren == null) + if (chldren is null) { newCurrent = -1; @@ -1258,7 +1258,7 @@ public class MenuBar : View } } - if (child == null || !child.IsEnabled ()) + if (child is null || !child.IsEnabled ()) { if (forward) { @@ -1286,7 +1286,7 @@ public class MenuBar : View /// internal bool SelectItem (MenuItem item) { - if (item?.Action == null) + if (item?.Action is null) { return false; } @@ -1422,7 +1422,7 @@ public class MenuBar : View openCurrentMenu = menu; openCurrentMenu.SetFocus (); - if (_openSubMenu != null) + if (_openSubMenu is { }) { menu = _openSubMenu [i]; Application.Current.Remove (menu); @@ -1534,13 +1534,13 @@ public class MenuBar : View { Activate (_menuBarItemToActivate); } - else if (_menuItemToSelect != null) + else if (_menuItemToSelect is { }) { Run (_menuItemToSelect.Action); } else { - if (IsMenuOpen && _openMenu != null) + if (IsMenuOpen && _openMenu is { }) { CloseAllMenus (); } @@ -1636,7 +1636,7 @@ public class MenuBar : View { menuItemToSelect = null; - if (key == KeyCode.Null || menuBarItem?.Children == null) + if (key == KeyCode.Null || menuBarItem?.Children is null) { return false; } @@ -1654,7 +1654,7 @@ public class MenuBar : View MenuBarItem subMenu = menuBarItem.SubMenu (menuItem); - if (subMenu != null) + if (subMenu is { }) { if (FindShortcutInChildMenu (key, subMenu, out menuItemToSelect)) { @@ -1681,7 +1681,7 @@ public class MenuBar : View /// public override bool OnLeave (View view) { - if (((!(view is MenuBar) && !(view is Menu)) || (!(view is MenuBar) && !(view is Menu) && _openMenu != null)) && !_isCleaning && !_reopen) + if (((!(view is MenuBar) && !(view is Menu)) || (!(view is MenuBar) && !(view is Menu) && _openMenu is { })) && !_isCleaning && !_reopen) { CleanUp (); } @@ -1709,7 +1709,7 @@ public class MenuBar : View int pos = _xOrigin; Point locationOffset = default; - if (SuperView != null) + if (SuperView is { }) { locationOffset.X += SuperView.Border.Thickness.Left; locationOffset.Y += SuperView.Border.Thickness.Top; @@ -1801,13 +1801,13 @@ public class MenuBar : View internal bool HandleGrabView (MouseEvent me, View current) { - if (Application.MouseGrabView != null) + if (Application.MouseGrabView is { }) { if (me.View is MenuBar || me.View is Menu) { MenuBar mbar = GetMouseGrabViewInstance (me.View); - if (mbar != null) + if (mbar is { }) { if (me.Flags == MouseFlags.Button1Clicked) { @@ -1905,7 +1905,7 @@ public class MenuBar : View private MenuBar GetMouseGrabViewInstance (View view) { - if (view == null || Application.MouseGrabView == null) + if (view is null || Application.MouseGrabView is null) { return null; } diff --git a/Terminal.Gui/Views/MessageBox.cs b/Terminal.Gui/Views/MessageBox.cs index 266d77d8e..06eb44ca2 100644 --- a/Terminal.Gui/Views/MessageBox.cs +++ b/Terminal.Gui/Views/MessageBox.cs @@ -316,7 +316,7 @@ public static class MessageBox var count = 0; List