From 76667dbd0d64701c29c53c579f536e9b073bc259 Mon Sep 17 00:00:00 2001 From: Steven Kirk Date: Thu, 16 Dec 2021 22:59:54 +0100 Subject: [PATCH] Finished adding nullable annotations to Avalonia.Base. --- src/Avalonia.Base/AttachedProperty.cs | 2 - src/Avalonia.Base/Avalonia.Base.csproj | 1 + .../AvaloniaInternalException.cs | 2 - src/Avalonia.Base/AvaloniaLocator.cs | 19 +++++---- src/Avalonia.Base/AvaloniaObject.cs | 6 +-- src/Avalonia.Base/AvaloniaObjectExtensions.cs | 2 - src/Avalonia.Base/AvaloniaProperty.cs | 6 +-- .../AvaloniaPropertyChangedEventArgs.cs | 2 - .../AvaloniaPropertyChangedEventArgs`1.cs | 2 - src/Avalonia.Base/AvaloniaPropertyMetadata.cs | 2 - src/Avalonia.Base/AvaloniaPropertyRegistry.cs | 2 - src/Avalonia.Base/AvaloniaProperty`1.cs | 10 ++--- .../Collections/AvaloniaDictionary.cs | 18 ++++----- src/Avalonia.Base/Collections/AvaloniaList.cs | 6 +-- .../Collections/AvaloniaListConverter.cs | 13 ++++--- .../Collections/AvaloniaListExtensions.cs | 16 ++++---- .../Collections/IAvaloniaList.cs | 2 - .../Collections/IAvaloniaReadOnlyList.cs | 2 - .../NotifyCollectionChangedExtensions.cs | 8 ++-- .../Collections/Pooled/ClearMode.cs | 2 - .../Pooled/ICollectionDebugView.cs | 2 - .../Collections/Pooled/IReadOnlyPooledList.cs | 2 - .../Collections/Pooled/PooledList.cs | 17 ++++---- .../Collections/Pooled/PooledStack.cs | 4 +- .../Collections/Pooled/StackDebugView.cs | 2 - .../Collections/Pooled/ThrowHelper.cs | 2 - .../Data/AssignBindingAttribute.cs | 2 - .../Data/BindingChainException.cs | 2 - src/Avalonia.Base/Data/BindingMode.cs | 2 - src/Avalonia.Base/Data/BindingNotification.cs | 8 ++-- src/Avalonia.Base/Data/BindingOperations.cs | 2 - src/Avalonia.Base/Data/BindingPriority.cs | 2 - src/Avalonia.Base/Data/BindingValue.cs | 8 ++-- .../Data/Converters/BoolConverters.cs | 2 - .../Data/Converters/DefaultValueConverter.cs | 4 +- .../Converters/FuncMultiValueConverter.cs | 2 - .../Data/Converters/FuncValueConverter.cs | 2 - .../Data/Converters/IMultiValueConverter.cs | 2 - .../Data/Converters/IValueConverter.cs | 2 - .../Converters/MethodToCommandConverter.cs | 38 +++++++++--------- .../Data/Converters/ObjectConverters.cs | 2 - .../Data/Converters/StringConverters.cs | 2 - .../StringFormatMultiValueConverter.cs | 2 - .../Converters/StringFormatValueConverter.cs | 2 - .../Data/Core/AvaloniaPropertyAccessorNode.cs | 2 - .../Data/Core/BindingExpression.cs | 4 +- .../Data/Core/ClrPropertyInfo.cs | 6 +-- .../Data/Core/CommonPropertyNames.cs | 2 - .../Data/Core/EmptyExpressionNode.cs | 4 +- src/Avalonia.Base/Data/Core/ExpressionNode.cs | 2 - .../Data/Core/ExpressionObserver.cs | 2 - .../Data/Core/ExpressionParseException.cs | 2 - src/Avalonia.Base/Data/Core/IPropertyInfo.cs | 2 - src/Avalonia.Base/Data/Core/ITransformNode.cs | 4 +- .../Data/Core/IndexerExpressionNode.cs | 4 +- .../Data/Core/IndexerNodeBase.cs | 8 ++-- src/Avalonia.Base/Data/Core/LogicalNotNode.cs | 2 - .../Data/Core/MarkupBindingChainException.cs | 2 - .../Data/Core/Parsers/ExpressionTreeParser.cs | 2 - .../Parsers/ExpressionVisitorNodeBuilder.cs | 18 ++++----- .../Plugins/AvaloniaPropertyAccessorPlugin.cs | 9 ++--- .../DataAnnotationsValidationPlugin.cs | 16 ++++---- .../Data/Core/Plugins/DataValidationBase.cs | 2 - .../Core/Plugins/ExceptionValidationPlugin.cs | 4 +- .../Core/Plugins/IDataValidationPlugin.cs | 2 - .../Data/Core/Plugins/IPropertyAccessor.cs | 2 - .../Core/Plugins/IPropertyAccessorPlugin.cs | 2 - .../Data/Core/Plugins/IStreamPlugin.cs | 2 - .../Core/Plugins/IndeiValidationPlugin.cs | 4 +- .../Plugins/InpcPropertyAccessorPlugin.cs | 4 +- .../Data/Core/Plugins/MethodAccessorPlugin.cs | 2 - .../Core/Plugins/ObservableStreamPlugin.cs | 8 ++-- .../Data/Core/Plugins/PropertyAccessorBase.cs | 2 - .../Data/Core/Plugins/PropertyError.cs | 2 - .../Data/Core/Plugins/TaskStreamPlugin.cs | 4 +- .../Data/Core/PropertyAccessorNode.cs | 2 - src/Avalonia.Base/Data/Core/PropertyPath.cs | 2 - src/Avalonia.Base/Data/Core/SettableNode.cs | 2 - .../Data/Core/StreamBindingExtensions.cs | 2 - src/Avalonia.Base/Data/Core/StreamNode.cs | 2 - src/Avalonia.Base/Data/Core/TypeCastNode.cs | 2 - .../Data/DataValidationException.cs | 2 - src/Avalonia.Base/Data/IBinding.cs | 2 - src/Avalonia.Base/Data/IndexerBinding.cs | 4 +- src/Avalonia.Base/Data/IndexerDescriptor.cs | 2 - src/Avalonia.Base/Data/InstancedBinding.cs | 2 - src/Avalonia.Base/Data/Optional.cs | 2 - .../Diagnostics/AvaloniaPropertyValue.cs | 8 ++-- .../Diagnostics/IAvaloniaObjectDebug.cs | 2 - .../INotifyCollectionChangedDebug.cs | 2 +- src/Avalonia.Base/DirectProperty.cs | 2 - src/Avalonia.Base/DirectPropertyBase.cs | 4 +- src/Avalonia.Base/DirectPropertyMetadata`1.cs | 2 - src/Avalonia.Base/EnumExtensions.cs | 2 - src/Avalonia.Base/IAvaloniaObject.cs | 2 - src/Avalonia.Base/IDescription.cs | 2 - src/Avalonia.Base/IDirectPropertyAccessor.cs | 2 - src/Avalonia.Base/IDirectPropertyMetadata.cs | 2 - src/Avalonia.Base/IStyledPropertyAccessor.cs | 2 - src/Avalonia.Base/IStyledPropertyMetadata.cs | 2 - src/Avalonia.Base/Logging/ILogSink.cs | 12 +++--- src/Avalonia.Base/Logging/Logger.cs | 4 +- .../Logging/ParametrizedLogger.cs | 14 +++---- src/Avalonia.Base/Logging/TraceLogSink.cs | 26 ++++++------- src/Avalonia.Base/Metadata/TemplateContent.cs | 2 +- src/Avalonia.Base/Platform/IAssetLoader.cs | 8 ++-- src/Avalonia.Base/Platform/IPlatformHandle.cs | 2 +- .../Platform/Interop/Utf8Buffer.cs | 8 ++-- src/Avalonia.Base/Platform/PlatformHandle.cs | 4 +- .../PropertyStore/BindingEntry.cs | 2 - .../PropertyStore/ConstantValueEntry.cs | 2 - .../PropertyStore/IPriorityValueEntry.cs | 4 +- src/Avalonia.Base/PropertyStore/IValue.cs | 2 - src/Avalonia.Base/PropertyStore/IValueSink.cs | 2 - .../PropertyStore/LocalValueEntry.cs | 2 - .../PropertyStore/PriorityValue.cs | 2 - .../AvaloniaPropertyBindingObservable.cs | 15 ++++--- .../AvaloniaPropertyChangedObservable.cs | 2 +- .../Reactive/AvaloniaPropertyObservable.cs | 19 +++++---- .../Reactive/BindingValueAdapter.cs | 2 - .../Reactive/BindingValueExtensions.cs | 2 - .../Reactive/LightweightObservableBase.cs | 19 ++++----- src/Avalonia.Base/Reactive/ObservableEx.cs | 2 +- .../SingleSubscriberObservableBase.cs | 6 +-- .../Reactive/TypedBindingAdapter.cs | 2 - .../Reactive/UntypedBindingAdapter.cs | 2 - src/Avalonia.Base/StyledProperty.cs | 2 - src/Avalonia.Base/StyledPropertyBase.cs | 4 +- src/Avalonia.Base/StyledPropertyMetadata`1.cs | 2 - .../AvaloniaSynchronizationContext.cs | 4 +- src/Avalonia.Base/Threading/Dispatcher.cs | 20 ++++++---- .../Threading/DispatcherTimer.cs | 12 +++--- src/Avalonia.Base/Threading/JobRunner.cs | 14 +++---- .../Utilities/AvaloniaPropertyValueStore.cs | 2 - .../Utilities/AvaloniaResourcesIndex.cs | 14 +++---- src/Avalonia.Base/Utilities/DisposableLock.cs | 6 +-- .../Utilities/IAvaloniaPropertyVisitor.cs | 4 +- .../Utilities/IWeakSubscriber.cs | 2 +- .../ImmutableReadOnlyListStructEnumerator.cs | 15 +++---- .../Utilities/NonPumpingLockHelper.cs | 4 +- src/Avalonia.Base/Utilities/Ref.cs | 10 ++--- .../Utilities/SingleOrDictionary.cs | 8 ++-- src/Avalonia.Base/Utilities/SingleOrQueue.cs | 6 +-- .../Utilities/StringTokenizer.cs | 13 ++++--- .../SynchronousCompletionAsyncResult.cs | 12 +++--- src/Avalonia.Base/Utilities/TypeUtilities.cs | 26 ++++++------- .../Utilities/ValueSingleOrList.cs | 4 +- .../Utilities/WeakEventHandlerManager.cs | 37 +++++++++--------- src/Avalonia.Base/Utilities/WeakObservable.cs | 6 +-- .../Utilities/WeakSubscriptionManager.cs | 39 +++++++++---------- src/Avalonia.Base/Utilities/WeakTimer.cs | 3 +- src/Avalonia.Base/ValueStore.cs | 2 - .../Avalonia.Build.Tasks.csproj | 1 + src/Avalonia.Controls/Application.cs | 8 ++-- src/Avalonia.Controls/ContextMenu.cs | 2 +- src/Avalonia.Controls/Control.cs | 6 ++- src/Avalonia.Controls/Flyouts/FlyoutBase.cs | 2 +- src/Avalonia.Controls/MaskedTextBox.cs | 9 ++++- src/Avalonia.Controls/MenuItem.cs | 2 +- .../Platform/PlatformManager.cs | 3 -- .../Primitives/SelectingItemsControl.cs | 4 ++ src/Avalonia.Controls/SystemDialog.cs | 13 +++++-- .../Templates/DataTemplateExtensions.cs | 2 +- src/Avalonia.Controls/TrayIcon.cs | 7 +++- .../Utils/CollectionChangedEventManager.cs | 2 +- .../Diagnostics/ViewModels/MainViewModel.cs | 17 ++++---- src/Avalonia.Input/AccessKeyHandler.cs | 2 +- src/Avalonia.Input/FocusManager.cs | 2 +- src/Avalonia.Input/InputElement.cs | 2 +- src/Avalonia.Input/InputManager.cs | 2 +- src/Avalonia.Input/KeyboardDevice.cs | 6 +-- .../KeyboardNavigationHandler.cs | 4 +- src/Avalonia.Input/MouseDevice.cs | 5 ++- .../Media/CombinedGeometry.cs | 3 +- src/Avalonia.Visuals/Media/GeometryGroup.cs | 6 ++- src/Avalonia.X11/X11CursorFactory.cs | 8 +++- .../Markup/Parsers/Nodes/StringIndexerNode.cs | 8 ++-- .../Markup/Parsers/SelectorParser.cs | 2 +- src/Shared/PlatformSupport/AssetLoader.cs | 6 ++- .../Avalonia.Web.Blazor/AvaloniaView.razor.cs | 4 +- .../Avalonia.Web.Blazor/WindowingPlatform.cs | 10 +++-- .../Avalonia.Win32/FramebufferManager.cs | 4 +- 182 files changed, 420 insertions(+), 599 deletions(-) diff --git a/src/Avalonia.Base/AttachedProperty.cs b/src/Avalonia.Base/AttachedProperty.cs index 352104897a..12c569c452 100644 --- a/src/Avalonia.Base/AttachedProperty.cs +++ b/src/Avalonia.Base/AttachedProperty.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/Avalonia.Base.csproj b/src/Avalonia.Base/Avalonia.Base.csproj index e872756a58..07614f31db 100644 --- a/src/Avalonia.Base/Avalonia.Base.csproj +++ b/src/Avalonia.Base/Avalonia.Base.csproj @@ -11,4 +11,5 @@ + diff --git a/src/Avalonia.Base/AvaloniaInternalException.cs b/src/Avalonia.Base/AvaloniaInternalException.cs index 60e3040e01..a536073174 100644 --- a/src/Avalonia.Base/AvaloniaInternalException.cs +++ b/src/Avalonia.Base/AvaloniaInternalException.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/AvaloniaLocator.cs b/src/Avalonia.Base/AvaloniaLocator.cs index 3163d15c1b..0510852ea7 100644 --- a/src/Avalonia.Base/AvaloniaLocator.cs +++ b/src/Avalonia.Base/AvaloniaLocator.cs @@ -7,10 +7,10 @@ namespace Avalonia { public class AvaloniaLocator : IAvaloniaDependencyResolver { - private readonly IAvaloniaDependencyResolver _parentScope; + private readonly IAvaloniaDependencyResolver? _parentScope; public static IAvaloniaDependencyResolver Current { get; set; } public static AvaloniaLocator CurrentMutable { get; set; } - private readonly Dictionary> _registry = new Dictionary>(); + private readonly Dictionary> _registry = new Dictionary>(); static AvaloniaLocator() { @@ -27,10 +27,9 @@ namespace Avalonia _parentScope = parentScope; } - public object GetService(Type t) + public object? GetService(Type t) { - Func rv; - return _registry.TryGetValue(t, out rv) ? rv() : _parentScope?.GetService(t); + return _registry.TryGetValue(t, out var rv) ? rv() : _parentScope?.GetService(t); } public class RegistrationHelper @@ -57,7 +56,7 @@ namespace Avalonia public AvaloniaLocator ToLazy(Func func) where TImlp : TService { var constructed = false; - TImlp instance = default; + TImlp? instance = default; _locator._registry[typeof (TService)] = () => { if (!constructed) @@ -73,7 +72,7 @@ namespace Avalonia public AvaloniaLocator ToSingleton() where TImpl : class, TService, new() { - TImpl instance = null; + TImpl? instance = null; return ToFunc(() => instance ?? (instance = new TImpl())); } @@ -117,14 +116,14 @@ namespace Avalonia public interface IAvaloniaDependencyResolver { - object GetService(Type t); + object? GetService(Type t); } public static class LocatorExtensions { - public static T GetService(this IAvaloniaDependencyResolver resolver) + public static T? GetService(this IAvaloniaDependencyResolver resolver) { - return (T) resolver.GetService(typeof (T)); + return (T?) resolver.GetService(typeof (T)); } } } diff --git a/src/Avalonia.Base/AvaloniaObject.cs b/src/Avalonia.Base/AvaloniaObject.cs index 9a1101e637..437339d3b2 100644 --- a/src/Avalonia.Base/AvaloniaObject.cs +++ b/src/Avalonia.Base/AvaloniaObject.cs @@ -7,8 +7,6 @@ using Avalonia.Logging; using Avalonia.PropertyStore; using Avalonia.Threading; -#nullable enable - namespace Avalonia { /// @@ -47,7 +45,7 @@ namespace Avalonia /// /// Raised when a value changes on this object. /// - event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged + event PropertyChangedEventHandler? INotifyPropertyChanged.PropertyChanged { add { _inpcChanged += value; } remove { _inpcChanged -= value; } @@ -857,7 +855,7 @@ namespace Avalonia private string GetDescription(object o) { var description = o as IDescription; - return description?.Description ?? o.ToString(); + return description?.Description ?? o.ToString() ?? o.GetType().Name; } /// diff --git a/src/Avalonia.Base/AvaloniaObjectExtensions.cs b/src/Avalonia.Base/AvaloniaObjectExtensions.cs index 16f0ca38a7..51237409bf 100644 --- a/src/Avalonia.Base/AvaloniaObjectExtensions.cs +++ b/src/Avalonia.Base/AvaloniaObjectExtensions.cs @@ -6,8 +6,6 @@ using System.Reactive.Subjects; using Avalonia.Data; using Avalonia.Reactive; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/AvaloniaProperty.cs b/src/Avalonia.Base/AvaloniaProperty.cs index 3e5cfb24a2..3d1e898f50 100644 --- a/src/Avalonia.Base/AvaloniaProperty.cs +++ b/src/Avalonia.Base/AvaloniaProperty.cs @@ -4,8 +4,6 @@ using Avalonia.Data; using Avalonia.Data.Core; using Avalonia.Utilities; -#nullable enable - namespace Avalonia { /// @@ -544,12 +542,12 @@ namespace Avalonia throw new ArgumentNullException(nameof(type)); } - if (_metadataCache.TryGetValue(type, out AvaloniaPropertyMetadata result)) + if (_metadataCache.TryGetValue(type, out var result)) { return result; } - Type currentType = type; + Type? currentType = type; while (currentType != null) { diff --git a/src/Avalonia.Base/AvaloniaPropertyChangedEventArgs.cs b/src/Avalonia.Base/AvaloniaPropertyChangedEventArgs.cs index 896d86e29d..445f35aad2 100644 --- a/src/Avalonia.Base/AvaloniaPropertyChangedEventArgs.cs +++ b/src/Avalonia.Base/AvaloniaPropertyChangedEventArgs.cs @@ -1,8 +1,6 @@ using System; using Avalonia.Data; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/AvaloniaPropertyChangedEventArgs`1.cs b/src/Avalonia.Base/AvaloniaPropertyChangedEventArgs`1.cs index 054bf93b3a..734e38596c 100644 --- a/src/Avalonia.Base/AvaloniaPropertyChangedEventArgs`1.cs +++ b/src/Avalonia.Base/AvaloniaPropertyChangedEventArgs`1.cs @@ -1,7 +1,5 @@ using Avalonia.Data; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/AvaloniaPropertyMetadata.cs b/src/Avalonia.Base/AvaloniaPropertyMetadata.cs index 4090aab558..2963567b14 100644 --- a/src/Avalonia.Base/AvaloniaPropertyMetadata.cs +++ b/src/Avalonia.Base/AvaloniaPropertyMetadata.cs @@ -1,7 +1,5 @@ using Avalonia.Data; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/AvaloniaPropertyRegistry.cs b/src/Avalonia.Base/AvaloniaPropertyRegistry.cs index 91db8c16c2..d86e723b38 100644 --- a/src/Avalonia.Base/AvaloniaPropertyRegistry.cs +++ b/src/Avalonia.Base/AvaloniaPropertyRegistry.cs @@ -2,8 +2,6 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/AvaloniaProperty`1.cs b/src/Avalonia.Base/AvaloniaProperty`1.cs index 3485f195c5..3937ee5658 100644 --- a/src/Avalonia.Base/AvaloniaProperty`1.cs +++ b/src/Avalonia.Base/AvaloniaProperty`1.cs @@ -3,8 +3,6 @@ using System.Reactive.Subjects; using Avalonia.Data; using Avalonia.Utilities; -#nullable enable - namespace Avalonia { /// @@ -84,15 +82,15 @@ namespace Avalonia protected override IObservable GetChanged() => Changed; - protected BindingValue TryConvert(object? value) + protected BindingValue TryConvert(object? value) { if (value == UnsetValue) { - return BindingValue.Unset; + return BindingValue.Unset; } else if (value == BindingOperations.DoNothing) { - return BindingValue.DoNothing; + return BindingValue.DoNothing; } if (!TypeUtilities.TryConvertImplicit(PropertyType, value, out var converted)) @@ -102,7 +100,7 @@ namespace Avalonia Name, value, value?.GetType().FullName ?? "(null)")); - return BindingValue.BindingError(error); + return BindingValue.BindingError(error); } return converted; diff --git a/src/Avalonia.Base/Collections/AvaloniaDictionary.cs b/src/Avalonia.Base/Collections/AvaloniaDictionary.cs index e5ee1e1eef..0e027712e0 100644 --- a/src/Avalonia.Base/Collections/AvaloniaDictionary.cs +++ b/src/Avalonia.Base/Collections/AvaloniaDictionary.cs @@ -3,11 +3,10 @@ using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia.Data.Core; -#nullable enable - namespace Avalonia.Collections { /// @@ -19,6 +18,7 @@ namespace Avalonia.Collections IDictionary, INotifyCollectionChanged, INotifyPropertyChanged + where TKey : notnull { private Dictionary _inner; @@ -76,8 +76,7 @@ namespace Avalonia.Collections set { - TValue old; - bool replace = _inner.TryGetValue(key, out old); + bool replace = _inner.TryGetValue(key, out var old); _inner[key] = value; if (replace) @@ -89,7 +88,7 @@ namespace Avalonia.Collections var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, new KeyValuePair(key, value), - new KeyValuePair(key, old)); + new KeyValuePair(key, old!)); CollectionChanged(this, e); } } @@ -100,7 +99,7 @@ namespace Avalonia.Collections } } - object IDictionary.this[object key] { get => ((IDictionary)_inner)[key]; set => ((IDictionary)_inner)[key] = value; } + object? IDictionary.this[object key] { get => ((IDictionary)_inner)[key]; set => ((IDictionary)_inner)[key] = value; } /// public void Add(TKey key, TValue value) @@ -145,7 +144,7 @@ namespace Avalonia.Collections /// public bool Remove(TKey key) { - if (_inner.TryGetValue(key, out TValue value)) + if (_inner.TryGetValue(key, out var value)) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs($"Item[{key}]")); @@ -168,8 +167,7 @@ namespace Avalonia.Collections } /// - public bool TryGetValue(TKey key, out TValue value) => _inner.TryGetValue(key, out value); - + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) => _inner.TryGetValue(key, out value); /// IEnumerator IEnumerable.GetEnumerator() => _inner.GetEnumerator(); @@ -195,7 +193,7 @@ namespace Avalonia.Collections } /// - void IDictionary.Add(object key, object value) => Add((TKey)key, (TValue)value); + void IDictionary.Add(object key, object? value) => Add((TKey)key, (TValue)value!); /// bool IDictionary.Contains(object key) => ((IDictionary) _inner).Contains(key); diff --git a/src/Avalonia.Base/Collections/AvaloniaList.cs b/src/Avalonia.Base/Collections/AvaloniaList.cs index 5b8ba108c7..6414328e90 100644 --- a/src/Avalonia.Base/Collections/AvaloniaList.cs +++ b/src/Avalonia.Base/Collections/AvaloniaList.cs @@ -6,8 +6,6 @@ using System.ComponentModel; using System.Linq; using Avalonia.Diagnostics; -#nullable enable - namespace Avalonia.Collections { /// @@ -95,7 +93,7 @@ namespace Avalonia.Collections /// /// Raised when a change is made to the collection's items. /// - public event NotifyCollectionChangedEventHandler CollectionChanged + public event NotifyCollectionChangedEventHandler? CollectionChanged { add => _collectionChanged += value; remove => _collectionChanged -= value; @@ -135,7 +133,7 @@ namespace Avalonia.Collections bool ICollection.IsSynchronized => false; /// - object? ICollection.SyncRoot => null; + object ICollection.SyncRoot => this; /// bool ICollection.IsReadOnly => false; diff --git a/src/Avalonia.Base/Collections/AvaloniaListConverter.cs b/src/Avalonia.Base/Collections/AvaloniaListConverter.cs index 444cdec144..b3fc0b01b6 100644 --- a/src/Avalonia.Base/Collections/AvaloniaListConverter.cs +++ b/src/Avalonia.Base/Collections/AvaloniaListConverter.cs @@ -3,8 +3,6 @@ using System.ComponentModel; using System.Globalization; using Avalonia.Utilities; -#nullable enable - namespace Avalonia.Collections { /// @@ -12,23 +10,26 @@ namespace Avalonia.Collections /// public class AvaloniaListConverter : TypeConverter { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return sourceType == typeof(string); } - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object? value) { + if (value is not string stringValue) + return null; + var result = new AvaloniaList(); // TODO: Use StringTokenizer here. - var values = ((string)value).Split(','); + var values = stringValue.Split(','); foreach (var s in values) { if (TypeUtilities.TryConvert(typeof(T), s, culture, out var v)) { - result.Add((T)v); + result.Add((T)v!); } else { diff --git a/src/Avalonia.Base/Collections/AvaloniaListExtensions.cs b/src/Avalonia.Base/Collections/AvaloniaListExtensions.cs index 5f3c3964f7..fb70729cf8 100644 --- a/src/Avalonia.Base/Collections/AvaloniaListExtensions.cs +++ b/src/Avalonia.Base/Collections/AvaloniaListExtensions.cs @@ -5,8 +5,6 @@ using System.Collections.Specialized; using System.ComponentModel; using System.Reactive.Disposables; -#nullable enable - namespace Avalonia.Collections { /// @@ -88,7 +86,7 @@ namespace Avalonia.Collections { for (var i = items.Count - 1; i >= 0; --i) { - removed(index + i, (T)items[i]); + removed(index + i, (T)items[i]!); } } @@ -97,22 +95,22 @@ namespace Avalonia.Collections switch (e.Action) { case NotifyCollectionChangedAction.Add: - Add(e.NewStartingIndex, e.NewItems); + Add(e.NewStartingIndex, e.NewItems!); break; case NotifyCollectionChangedAction.Move: case NotifyCollectionChangedAction.Replace: - Remove(e.OldStartingIndex, e.OldItems); + Remove(e.OldStartingIndex, e.OldItems!); int newIndex = e.NewStartingIndex; if(newIndex > e.OldStartingIndex) { - newIndex -= e.OldItems.Count; + newIndex -= e.OldItems!.Count; } - Add(newIndex, e.NewItems); + Add(newIndex, e.NewItems!); break; case NotifyCollectionChangedAction.Remove: - Remove(e.OldStartingIndex, e.OldItems); + Remove(e.OldStartingIndex, e.OldItems!); break; case NotifyCollectionChangedAction.Reset: @@ -166,7 +164,7 @@ namespace Avalonia.Collections /// A disposable used to terminate the subscription. public static IDisposable TrackItemPropertyChanged( this IAvaloniaReadOnlyList collection, - Action> callback) + Action> callback) { List tracked = new List(); diff --git a/src/Avalonia.Base/Collections/IAvaloniaList.cs b/src/Avalonia.Base/Collections/IAvaloniaList.cs index c28fb835e0..250d4faeb9 100644 --- a/src/Avalonia.Base/Collections/IAvaloniaList.cs +++ b/src/Avalonia.Base/Collections/IAvaloniaList.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; -#nullable enable - namespace Avalonia.Collections { /// diff --git a/src/Avalonia.Base/Collections/IAvaloniaReadOnlyList.cs b/src/Avalonia.Base/Collections/IAvaloniaReadOnlyList.cs index 09622dceba..a6a5953827 100644 --- a/src/Avalonia.Base/Collections/IAvaloniaReadOnlyList.cs +++ b/src/Avalonia.Base/Collections/IAvaloniaReadOnlyList.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; -#nullable enable - namespace Avalonia.Collections { /// diff --git a/src/Avalonia.Base/Collections/NotifyCollectionChangedExtensions.cs b/src/Avalonia.Base/Collections/NotifyCollectionChangedExtensions.cs index 7a8c2325e6..dcd32ddd76 100644 --- a/src/Avalonia.Base/Collections/NotifyCollectionChangedExtensions.cs +++ b/src/Avalonia.Base/Collections/NotifyCollectionChangedExtensions.cs @@ -4,8 +4,6 @@ using System.Reactive.Linq; using Avalonia.Reactive; using Avalonia.Utilities; -#nullable enable - namespace Avalonia.Collections { public static class NotifyCollectionChangedExtensions @@ -70,14 +68,14 @@ namespace Avalonia.Collections _sourceReference = source; } - public void OnEvent(object sender, NotifyCollectionChangedEventArgs e) + public void OnEvent(object? sender, NotifyCollectionChangedEventArgs e) { PublishNext(e); } protected override void Initialize() { - if (_sourceReference.TryGetTarget(out INotifyCollectionChanged instance)) + if (_sourceReference.TryGetTarget(out var instance)) { WeakSubscriptionManager.Subscribe( instance, @@ -88,7 +86,7 @@ namespace Avalonia.Collections protected override void Deinitialize() { - if (_sourceReference.TryGetTarget(out INotifyCollectionChanged instance)) + if (_sourceReference.TryGetTarget(out var instance)) { WeakSubscriptionManager.Unsubscribe( instance, diff --git a/src/Avalonia.Base/Collections/Pooled/ClearMode.cs b/src/Avalonia.Base/Collections/Pooled/ClearMode.cs index f13538dce3..d78ac8feab 100644 --- a/src/Avalonia.Base/Collections/Pooled/ClearMode.cs +++ b/src/Avalonia.Base/Collections/Pooled/ClearMode.cs @@ -1,8 +1,6 @@ // This source file is adapted from the Collections.Pooled. // (https://github.com/jtmueller/Collections.Pooled/tree/master/Collections.Pooled/) -#nullable enable - namespace Avalonia.Collections.Pooled { /// diff --git a/src/Avalonia.Base/Collections/Pooled/ICollectionDebugView.cs b/src/Avalonia.Base/Collections/Pooled/ICollectionDebugView.cs index 6f89cb7728..2b15388a13 100644 --- a/src/Avalonia.Base/Collections/Pooled/ICollectionDebugView.cs +++ b/src/Avalonia.Base/Collections/Pooled/ICollectionDebugView.cs @@ -6,8 +6,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -#nullable enable - namespace Avalonia.Collections.Pooled { internal sealed class ICollectionDebugView diff --git a/src/Avalonia.Base/Collections/Pooled/IReadOnlyPooledList.cs b/src/Avalonia.Base/Collections/Pooled/IReadOnlyPooledList.cs index 7ac22d2baf..7a233a62ab 100644 --- a/src/Avalonia.Base/Collections/Pooled/IReadOnlyPooledList.cs +++ b/src/Avalonia.Base/Collections/Pooled/IReadOnlyPooledList.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; -#nullable enable - namespace Avalonia.Collections.Pooled { /// diff --git a/src/Avalonia.Base/Collections/Pooled/PooledList.cs b/src/Avalonia.Base/Collections/Pooled/PooledList.cs index 73cd602948..200a52fb0d 100644 --- a/src/Avalonia.Base/Collections/Pooled/PooledList.cs +++ b/src/Avalonia.Base/Collections/Pooled/PooledList.cs @@ -13,8 +13,6 @@ using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; -#nullable enable - namespace Avalonia.Collections.Pooled { /// @@ -656,14 +654,15 @@ namespace Avalonia.Collections.Pooled // compatible array type. void ICollection.CopyTo(Array array, int arrayIndex) { - if ((array != null) && (array.Rank != 1)) + _ = array ?? throw new ArgumentNullException(nameof(array)); + + if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } try { - // Array.Copy will check for NULL. Array.Copy(_items, 0, array, arrayIndex, _size); } catch (ArrayTypeMismatchException) @@ -1336,7 +1335,7 @@ namespace Avalonia.Collections.Pooled _version++; } - public void Sort(Func comparison) + public void Sort(Func comparison) { if (comparison == null) { @@ -1442,7 +1441,7 @@ namespace Avalonia.Collections.Pooled _version++; } - void IDeserializationCallback.OnDeserialization(object sender) + void IDeserializationCallback.OnDeserialization(object? sender) { // We can't serialize array pools, so deserialized PooledLists will // have to use the shared pool, even if they were using a custom pool @@ -1522,14 +1521,14 @@ namespace Avalonia.Collections.Pooled private readonly struct Comparer : IComparer { - private readonly Func _comparison; + private readonly Func _comparison; - public Comparer(Func comparison) + public Comparer(Func comparison) { _comparison = comparison; } - public int Compare(T x, T y) => _comparison(x, y); + public int Compare(T? x, T? y) => _comparison(x, y); } } } diff --git a/src/Avalonia.Base/Collections/Pooled/PooledStack.cs b/src/Avalonia.Base/Collections/Pooled/PooledStack.cs index 8a03c6f5e4..f721cb1b62 100644 --- a/src/Avalonia.Base/Collections/Pooled/PooledStack.cs +++ b/src/Avalonia.Base/Collections/Pooled/PooledStack.cs @@ -20,8 +20,6 @@ using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; -#nullable enable - namespace Avalonia.Collections.Pooled { /// @@ -613,7 +611,7 @@ namespace Avalonia.Collections.Pooled _version++; } - void IDeserializationCallback.OnDeserialization(object sender) + void IDeserializationCallback.OnDeserialization(object? sender) { // We can't serialize array pools, so deserialized PooledStacks will // have to use the shared pool, even if they were using a custom pool diff --git a/src/Avalonia.Base/Collections/Pooled/StackDebugView.cs b/src/Avalonia.Base/Collections/Pooled/StackDebugView.cs index b55ac110c6..b042388079 100644 --- a/src/Avalonia.Base/Collections/Pooled/StackDebugView.cs +++ b/src/Avalonia.Base/Collections/Pooled/StackDebugView.cs @@ -5,8 +5,6 @@ using System; using System.Diagnostics; -#nullable enable - namespace Avalonia.Collections.Pooled { internal sealed class StackDebugView diff --git a/src/Avalonia.Base/Collections/Pooled/ThrowHelper.cs b/src/Avalonia.Base/Collections/Pooled/ThrowHelper.cs index 3237286107..c0a60b695a 100644 --- a/src/Avalonia.Base/Collections/Pooled/ThrowHelper.cs +++ b/src/Avalonia.Base/Collections/Pooled/ThrowHelper.cs @@ -42,8 +42,6 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.Serialization; -#nullable enable - namespace Avalonia.Collections.Pooled { internal static class ThrowHelper diff --git a/src/Avalonia.Base/Data/AssignBindingAttribute.cs b/src/Avalonia.Base/Data/AssignBindingAttribute.cs index f88055a1e1..15bd32c7c2 100644 --- a/src/Avalonia.Base/Data/AssignBindingAttribute.cs +++ b/src/Avalonia.Base/Data/AssignBindingAttribute.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data { /// diff --git a/src/Avalonia.Base/Data/BindingChainException.cs b/src/Avalonia.Base/Data/BindingChainException.cs index 09acf459cc..2890680f9a 100644 --- a/src/Avalonia.Base/Data/BindingChainException.cs +++ b/src/Avalonia.Base/Data/BindingChainException.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data { /// diff --git a/src/Avalonia.Base/Data/BindingMode.cs b/src/Avalonia.Base/Data/BindingMode.cs index a57487fa7a..0d04c2eb10 100644 --- a/src/Avalonia.Base/Data/BindingMode.cs +++ b/src/Avalonia.Base/Data/BindingMode.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Avalonia.Data { /// diff --git a/src/Avalonia.Base/Data/BindingNotification.cs b/src/Avalonia.Base/Data/BindingNotification.cs index 867a7f637a..4b97b1a02c 100644 --- a/src/Avalonia.Base/Data/BindingNotification.cs +++ b/src/Avalonia.Base/Data/BindingNotification.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data { /// @@ -214,8 +212,10 @@ namespace Avalonia.Data /// The error type. public void AddError(Exception e, BindingErrorType type) { - Contract.Requires(e != null); - Contract.Requires(type != BindingErrorType.None); + _ = e ?? throw new ArgumentNullException(nameof(e)); + + if (type == BindingErrorType.None) + throw new ArgumentException("BindingErrorType may not be None", nameof(type)); Error = Error != null ? new AggregateException(Error, e) : e; diff --git a/src/Avalonia.Base/Data/BindingOperations.cs b/src/Avalonia.Base/Data/BindingOperations.cs index 05900de01d..5353e8175d 100644 --- a/src/Avalonia.Base/Data/BindingOperations.cs +++ b/src/Avalonia.Base/Data/BindingOperations.cs @@ -2,8 +2,6 @@ using System; using System.Reactive.Disposables; using System.Reactive.Linq; -#nullable enable - namespace Avalonia.Data { public static class BindingOperations diff --git a/src/Avalonia.Base/Data/BindingPriority.cs b/src/Avalonia.Base/Data/BindingPriority.cs index e4fb11cf06..ece64375f2 100644 --- a/src/Avalonia.Base/Data/BindingPriority.cs +++ b/src/Avalonia.Base/Data/BindingPriority.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Avalonia.Data { /// diff --git a/src/Avalonia.Base/Data/BindingValue.cs b/src/Avalonia.Base/Data/BindingValue.cs index 8e90bed8bc..55be611083 100644 --- a/src/Avalonia.Base/Data/BindingValue.cs +++ b/src/Avalonia.Base/Data/BindingValue.cs @@ -2,8 +2,6 @@ using System.Diagnostics; using Avalonia.Utilities; -#nullable enable - namespace Avalonia.Data { /// @@ -418,15 +416,15 @@ namespace Avalonia.Data { BindingValueType.DoNothing => BindingValue.DoNothing, BindingValueType.UnsetValue => BindingValue.Unset, - BindingValueType.Value => new BindingValue(TypeUtilities.ConvertImplicit(value.Value)), + BindingValueType.Value => new BindingValue(TypeUtilities.ConvertImplicit(value.Value!)), BindingValueType.BindingError => BindingValue.BindingError(value.Error!), BindingValueType.BindingErrorWithFallback => BindingValue.BindingError( value.Error!, - TypeUtilities.ConvertImplicit(value.Value)), + TypeUtilities.ConvertImplicit(value.Value!)), BindingValueType.DataValidationError => BindingValue.DataValidationError(value.Error!), BindingValueType.DataValidationErrorWithFallback => BindingValue.DataValidationError( value.Error!, - TypeUtilities.ConvertImplicit(value.Value)), + TypeUtilities.ConvertImplicit(value.Value!)), _ => throw new NotSupportedException("Invalid BindingValue type."), }; } diff --git a/src/Avalonia.Base/Data/Converters/BoolConverters.cs b/src/Avalonia.Base/Data/Converters/BoolConverters.cs index 6a45ab8593..3985c5e32f 100644 --- a/src/Avalonia.Base/Data/Converters/BoolConverters.cs +++ b/src/Avalonia.Base/Data/Converters/BoolConverters.cs @@ -1,7 +1,5 @@ using System.Linq; -#nullable enable - namespace Avalonia.Data.Converters { /// diff --git a/src/Avalonia.Base/Data/Converters/DefaultValueConverter.cs b/src/Avalonia.Base/Data/Converters/DefaultValueConverter.cs index f99ac1f81d..11d50afe93 100644 --- a/src/Avalonia.Base/Data/Converters/DefaultValueConverter.cs +++ b/src/Avalonia.Base/Data/Converters/DefaultValueConverter.cs @@ -3,8 +3,6 @@ using System.Globalization; using System.Windows.Input; using Avalonia.Utilities; -#nullable enable - namespace Avalonia.Data.Converters { /// @@ -38,7 +36,7 @@ namespace Avalonia.Data.Converters return new MethodToCommandConverter(d); } - if (TypeUtilities.TryConvert(targetType, value, culture, out object result)) + if (TypeUtilities.TryConvert(targetType, value, culture, out var result)) { return result; } diff --git a/src/Avalonia.Base/Data/Converters/FuncMultiValueConverter.cs b/src/Avalonia.Base/Data/Converters/FuncMultiValueConverter.cs index 85dc6fc4f4..2577cac743 100644 --- a/src/Avalonia.Base/Data/Converters/FuncMultiValueConverter.cs +++ b/src/Avalonia.Base/Data/Converters/FuncMultiValueConverter.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; -#nullable enable - namespace Avalonia.Data.Converters { /// diff --git a/src/Avalonia.Base/Data/Converters/FuncValueConverter.cs b/src/Avalonia.Base/Data/Converters/FuncValueConverter.cs index fe71f1da1c..8a1f032593 100644 --- a/src/Avalonia.Base/Data/Converters/FuncValueConverter.cs +++ b/src/Avalonia.Base/Data/Converters/FuncValueConverter.cs @@ -2,8 +2,6 @@ using System; using System.Globalization; using Avalonia.Utilities; -#nullable enable - namespace Avalonia.Data.Converters { /// diff --git a/src/Avalonia.Base/Data/Converters/IMultiValueConverter.cs b/src/Avalonia.Base/Data/Converters/IMultiValueConverter.cs index e21746f571..d6e1c9f804 100644 --- a/src/Avalonia.Base/Data/Converters/IMultiValueConverter.cs +++ b/src/Avalonia.Base/Data/Converters/IMultiValueConverter.cs @@ -2,8 +2,6 @@ using System; using System.Collections.Generic; using System.Globalization; -#nullable enable - namespace Avalonia.Data.Converters { /// diff --git a/src/Avalonia.Base/Data/Converters/IValueConverter.cs b/src/Avalonia.Base/Data/Converters/IValueConverter.cs index c591dbda32..26c0e9582a 100644 --- a/src/Avalonia.Base/Data/Converters/IValueConverter.cs +++ b/src/Avalonia.Base/Data/Converters/IValueConverter.cs @@ -1,8 +1,6 @@ using System; using System.Globalization; -#nullable enable - namespace Avalonia.Data.Converters { /// diff --git a/src/Avalonia.Base/Data/Converters/MethodToCommandConverter.cs b/src/Avalonia.Base/Data/Converters/MethodToCommandConverter.cs index ee83776220..0672185a55 100644 --- a/src/Avalonia.Base/Data/Converters/MethodToCommandConverter.cs +++ b/src/Avalonia.Base/Data/Converters/MethodToCommandConverter.cs @@ -7,19 +7,17 @@ using System.Reflection; using System.Windows.Input; using Avalonia.Utilities; -#nullable enable - namespace Avalonia.Data.Converters { class MethodToCommandConverter : ICommand { - readonly static Func AlwaysEnabled = (_) => true; + readonly static Func AlwaysEnabled = (_) => true; readonly static MethodInfo tryConvert = typeof(TypeUtilities) - .GetMethod(nameof(TypeUtilities.TryConvert), BindingFlags.Public | BindingFlags.Static); + .GetMethod(nameof(TypeUtilities.TryConvert), BindingFlags.Public | BindingFlags.Static)!; readonly static PropertyInfo currentCulture = typeof(CultureInfo) - .GetProperty(nameof(CultureInfo.CurrentCulture), BindingFlags.Public | BindingFlags.Static); - readonly Func canExecute; - readonly Action execute; + .GetProperty(nameof(CultureInfo.CurrentCulture), BindingFlags.Public | BindingFlags.Static)!; + readonly Func canExecute; + readonly Action execute; readonly WeakPropertyChangedProxy? weakPropertyChanged; readonly PropertyChangedEventHandler? propertyChangedEventHandler; readonly string[]? dependencyProperties; @@ -40,7 +38,7 @@ namespace Avalonia.Data.Converters execute = CreateExecute(target, action.Method, parameterInfo); } - var canExecuteMethod = action.Method.DeclaringType.GetRuntimeMethods() + var canExecuteMethod = action.Method.DeclaringType?.GetRuntimeMethods() .FirstOrDefault(m => m.Name == canExecuteMethodName && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == typeof(object)); @@ -65,7 +63,7 @@ namespace Avalonia.Data.Converters } } - void OnPropertyChanged(object sender, PropertyChangedEventArgs args) + void OnPropertyChanged(object? sender, PropertyChangedEventArgs args) { if (string.IsNullOrWhiteSpace(args.PropertyName) || dependencyProperties?.Contains(args.PropertyName) == true) @@ -79,12 +77,12 @@ namespace Avalonia.Data.Converters public event EventHandler? CanExecuteChanged; #pragma warning restore 0067 - public bool CanExecute(object parameter) => canExecute(parameter); + public bool CanExecute(object? parameter) => canExecute(parameter); - public void Execute(object parameter) => execute(parameter); + public void Execute(object? parameter) => execute(parameter); - static Action CreateExecute(object target + static Action CreateExecute(object? target , System.Reflection.MethodInfo method) { @@ -100,11 +98,11 @@ namespace Avalonia.Data.Converters return Expression - .Lambda>(call, parameter) + .Lambda>(call, parameter) .Compile(); } - static Action CreateExecute(object target + static Action CreateExecute(object? target , System.Reflection.MethodInfo method , Type parameterType) { @@ -143,11 +141,11 @@ namespace Avalonia.Data.Converters } return Expression - .Lambda>(body, parameter) + .Lambda>(body, parameter) .Compile(); } - static Func CreateCanExecute(object target + static Func CreateCanExecute(object? target , System.Reflection.MethodInfo method) { var parameter = Expression.Parameter(typeof(object), "parameter"); @@ -159,12 +157,12 @@ namespace Avalonia.Data.Converters parameter ); return Expression - .Lambda>(call, parameter) + .Lambda>(call, parameter) .Compile(); } - private static Expression? ConvertTarget(object target, MethodInfo method) => - target is null ? null : Expression.Convert(Expression.Constant(target), method.DeclaringType); + private static Expression? ConvertTarget(object? target, MethodInfo method) => + target is null ? null : Expression.Convert(Expression.Constant(target), method.DeclaringType!); internal class WeakPropertyChangedProxy { @@ -199,7 +197,7 @@ namespace Avalonia.Data.Converters _listener.SetTarget(null); } - void OnPropertyChanged(object sender, PropertyChangedEventArgs e) + void OnPropertyChanged(object? sender, PropertyChangedEventArgs e) { if (_listener.TryGetTarget(out var handler) && handler != null) handler(sender, e); diff --git a/src/Avalonia.Base/Data/Converters/ObjectConverters.cs b/src/Avalonia.Base/Data/Converters/ObjectConverters.cs index 3794d0ca3b..6796a1793e 100644 --- a/src/Avalonia.Base/Data/Converters/ObjectConverters.cs +++ b/src/Avalonia.Base/Data/Converters/ObjectConverters.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Avalonia.Data.Converters { /// diff --git a/src/Avalonia.Base/Data/Converters/StringConverters.cs b/src/Avalonia.Base/Data/Converters/StringConverters.cs index a13cef349d..182eaf2e65 100644 --- a/src/Avalonia.Base/Data/Converters/StringConverters.cs +++ b/src/Avalonia.Base/Data/Converters/StringConverters.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Avalonia.Data.Converters { /// diff --git a/src/Avalonia.Base/Data/Converters/StringFormatMultiValueConverter.cs b/src/Avalonia.Base/Data/Converters/StringFormatMultiValueConverter.cs index d66a2d2cdf..606ac9e6fa 100644 --- a/src/Avalonia.Base/Data/Converters/StringFormatMultiValueConverter.cs +++ b/src/Avalonia.Base/Data/Converters/StringFormatMultiValueConverter.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; -#nullable enable - namespace Avalonia.Data.Converters { /// diff --git a/src/Avalonia.Base/Data/Converters/StringFormatValueConverter.cs b/src/Avalonia.Base/Data/Converters/StringFormatValueConverter.cs index 1b3451370a..5307ea4b9a 100644 --- a/src/Avalonia.Base/Data/Converters/StringFormatValueConverter.cs +++ b/src/Avalonia.Base/Data/Converters/StringFormatValueConverter.cs @@ -1,8 +1,6 @@ using System; using System.Globalization; -#nullable enable - namespace Avalonia.Data.Converters { /// diff --git a/src/Avalonia.Base/Data/Core/AvaloniaPropertyAccessorNode.cs b/src/Avalonia.Base/Data/Core/AvaloniaPropertyAccessorNode.cs index ce60e12ae1..92ecdafa0c 100644 --- a/src/Avalonia.Base/Data/Core/AvaloniaPropertyAccessorNode.cs +++ b/src/Avalonia.Base/Data/Core/AvaloniaPropertyAccessorNode.cs @@ -2,8 +2,6 @@ using System.Reactive.Linq; using Avalonia.Reactive; -#nullable enable - namespace Avalonia.Data.Core { public class AvaloniaPropertyAccessorNode : SettableNode diff --git a/src/Avalonia.Base/Data/Core/BindingExpression.cs b/src/Avalonia.Base/Data/Core/BindingExpression.cs index 3f7a9722b7..ea903c1042 100644 --- a/src/Avalonia.Base/Data/Core/BindingExpression.cs +++ b/src/Avalonia.Base/Data/Core/BindingExpression.cs @@ -7,8 +7,6 @@ using Avalonia.Logging; using Avalonia.Reactive; using Avalonia.Utilities; -#nullable enable - namespace Avalonia.Data.Core { /// @@ -263,7 +261,7 @@ namespace Avalonia.Data.Core private BindingNotification ConvertFallback() { - object converted; + object? converted; if (_fallbackValue == AvaloniaProperty.UnsetValue) { diff --git a/src/Avalonia.Base/Data/Core/ClrPropertyInfo.cs b/src/Avalonia.Base/Data/Core/ClrPropertyInfo.cs index f52940bc80..24149c17e0 100644 --- a/src/Avalonia.Base/Data/Core/ClrPropertyInfo.cs +++ b/src/Avalonia.Base/Data/Core/ClrPropertyInfo.cs @@ -2,8 +2,6 @@ using System; using System.Linq.Expressions; using System.Reflection; -#nullable enable - namespace Avalonia.Data.Core { public class ClrPropertyInfo : IPropertyInfo @@ -49,7 +47,7 @@ namespace Avalonia.Data.Core var target = Expression.Parameter(typeof(object), "target"); var value = Expression.Parameter(typeof(object), "value"); return Expression.Lambda>( - Expression.Call(Expression.Convert(target, info.DeclaringType), info.SetMethod, + Expression.Call(Expression.Convert(target, info.DeclaringType!), info.SetMethod, Expression.Convert(value, info.SetMethod.GetParameters()[0].ParameterType)), target, value) .Compile(); @@ -61,7 +59,7 @@ namespace Avalonia.Data.Core return null; var target = Expression.Parameter(typeof(object), "target"); return Expression.Lambda>( - Expression.Convert(Expression.Call(Expression.Convert(target, info.DeclaringType), info.GetMethod), + Expression.Convert(Expression.Call(Expression.Convert(target, info.DeclaringType!), info.GetMethod), typeof(object))) .Compile(); } diff --git a/src/Avalonia.Base/Data/Core/CommonPropertyNames.cs b/src/Avalonia.Base/Data/Core/CommonPropertyNames.cs index 908beeca33..da6f407d81 100644 --- a/src/Avalonia.Base/Data/Core/CommonPropertyNames.cs +++ b/src/Avalonia.Base/Data/Core/CommonPropertyNames.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Avalonia.Data.Core { public static class CommonPropertyNames diff --git a/src/Avalonia.Base/Data/Core/EmptyExpressionNode.cs b/src/Avalonia.Base/Data/Core/EmptyExpressionNode.cs index 115f617270..4e142fbee9 100644 --- a/src/Avalonia.Base/Data/Core/EmptyExpressionNode.cs +++ b/src/Avalonia.Base/Data/Core/EmptyExpressionNode.cs @@ -1,6 +1,4 @@ -#nullable enable - -namespace Avalonia.Data.Core +namespace Avalonia.Data.Core { public class EmptyExpressionNode : ExpressionNode { diff --git a/src/Avalonia.Base/Data/Core/ExpressionNode.cs b/src/Avalonia.Base/Data/Core/ExpressionNode.cs index 25b0102891..54785f18e8 100644 --- a/src/Avalonia.Base/Data/Core/ExpressionNode.cs +++ b/src/Avalonia.Base/Data/Core/ExpressionNode.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data.Core { public abstract class ExpressionNode diff --git a/src/Avalonia.Base/Data/Core/ExpressionObserver.cs b/src/Avalonia.Base/Data/Core/ExpressionObserver.cs index 9e38c8bfba..e4affd97de 100644 --- a/src/Avalonia.Base/Data/Core/ExpressionObserver.cs +++ b/src/Avalonia.Base/Data/Core/ExpressionObserver.cs @@ -7,8 +7,6 @@ using Avalonia.Data.Core.Parsers; using Avalonia.Data.Core.Plugins; using Avalonia.Reactive; -#nullable enable - namespace Avalonia.Data.Core { /// diff --git a/src/Avalonia.Base/Data/Core/ExpressionParseException.cs b/src/Avalonia.Base/Data/Core/ExpressionParseException.cs index 8fd7066a7b..a50e79f9cd 100644 --- a/src/Avalonia.Base/Data/Core/ExpressionParseException.cs +++ b/src/Avalonia.Base/Data/Core/ExpressionParseException.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data.Core { /// diff --git a/src/Avalonia.Base/Data/Core/IPropertyInfo.cs b/src/Avalonia.Base/Data/Core/IPropertyInfo.cs index 9544565fcb..4d80feb4ba 100644 --- a/src/Avalonia.Base/Data/Core/IPropertyInfo.cs +++ b/src/Avalonia.Base/Data/Core/IPropertyInfo.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data.Core { public interface IPropertyInfo diff --git a/src/Avalonia.Base/Data/Core/ITransformNode.cs b/src/Avalonia.Base/Data/Core/ITransformNode.cs index 49c1dea7b9..645d637e44 100644 --- a/src/Avalonia.Base/Data/Core/ITransformNode.cs +++ b/src/Avalonia.Base/Data/Core/ITransformNode.cs @@ -1,6 +1,4 @@ -#nullable enable - -namespace Avalonia.Data.Core +namespace Avalonia.Data.Core { interface ITransformNode { diff --git a/src/Avalonia.Base/Data/Core/IndexerExpressionNode.cs b/src/Avalonia.Base/Data/Core/IndexerExpressionNode.cs index 22a58a245b..7a24f9cb77 100644 --- a/src/Avalonia.Base/Data/Core/IndexerExpressionNode.cs +++ b/src/Avalonia.Base/Data/Core/IndexerExpressionNode.cs @@ -4,8 +4,6 @@ using System.ComponentModel; using System.Linq.Expressions; using System.Reflection; -#nullable enable - namespace Avalonia.Data.Core { class IndexerExpressionNode : IndexerNodeBase @@ -18,7 +16,7 @@ namespace Avalonia.Data.Core public IndexerExpressionNode(IndexExpression expression) { - _parameter = Expression.Parameter(expression.Object.Type); + _parameter = Expression.Parameter(expression.Object!.Type); _expression = expression.Update(_parameter, expression.Arguments); _getDelegate = Expression.Lambda(_expression, _parameter).Compile(); diff --git a/src/Avalonia.Base/Data/Core/IndexerNodeBase.cs b/src/Avalonia.Base/Data/Core/IndexerNodeBase.cs index ef4375a02c..e197e29103 100644 --- a/src/Avalonia.Base/Data/Core/IndexerNodeBase.cs +++ b/src/Avalonia.Base/Data/Core/IndexerNodeBase.cs @@ -7,8 +7,6 @@ using System.Linq; using System.Reactive.Linq; using Avalonia.Utilities; -#nullable enable - namespace Avalonia.Data.Core { public abstract class IndexerNodeBase : SettableNode @@ -72,12 +70,12 @@ namespace Avalonia.Data.Core return index >= e.OldStartingIndex; case NotifyCollectionChangedAction.Replace: return index >= e.NewStartingIndex && - index < e.NewStartingIndex + e.NewItems.Count; + index < e.NewStartingIndex + e.NewItems!.Count; case NotifyCollectionChangedAction.Move: return (index >= e.NewStartingIndex && - index < e.NewStartingIndex + e.NewItems.Count) || + index < e.NewStartingIndex + e.NewItems!.Count) || (index >= e.OldStartingIndex && - index < e.OldStartingIndex + e.OldItems.Count); + index < e.OldStartingIndex + e.OldItems!.Count); case NotifyCollectionChangedAction.Reset: return true; } diff --git a/src/Avalonia.Base/Data/Core/LogicalNotNode.cs b/src/Avalonia.Base/Data/Core/LogicalNotNode.cs index 7ccec51e1a..45837db73d 100644 --- a/src/Avalonia.Base/Data/Core/LogicalNotNode.cs +++ b/src/Avalonia.Base/Data/Core/LogicalNotNode.cs @@ -1,8 +1,6 @@ using System; using System.Globalization; -#nullable enable - namespace Avalonia.Data.Core { public class LogicalNotNode : ExpressionNode, ITransformNode diff --git a/src/Avalonia.Base/Data/Core/MarkupBindingChainException.cs b/src/Avalonia.Base/Data/Core/MarkupBindingChainException.cs index 2dbeae41ae..5d23cecbef 100644 --- a/src/Avalonia.Base/Data/Core/MarkupBindingChainException.cs +++ b/src/Avalonia.Base/Data/Core/MarkupBindingChainException.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.Linq; -#nullable enable - namespace Avalonia.Data.Core { internal class MarkupBindingChainException : BindingChainException diff --git a/src/Avalonia.Base/Data/Core/Parsers/ExpressionTreeParser.cs b/src/Avalonia.Base/Data/Core/Parsers/ExpressionTreeParser.cs index 34409a3e36..d2035a592f 100644 --- a/src/Avalonia.Base/Data/Core/Parsers/ExpressionTreeParser.cs +++ b/src/Avalonia.Base/Data/Core/Parsers/ExpressionTreeParser.cs @@ -1,8 +1,6 @@ using System.Linq; using System.Linq.Expressions; -#nullable enable - namespace Avalonia.Data.Core.Parsers { static class ExpressionTreeParser diff --git a/src/Avalonia.Base/Data/Core/Parsers/ExpressionVisitorNodeBuilder.cs b/src/Avalonia.Base/Data/Core/Parsers/ExpressionVisitorNodeBuilder.cs index caba0c2e78..1e82214d76 100644 --- a/src/Avalonia.Base/Data/Core/Parsers/ExpressionVisitorNodeBuilder.cs +++ b/src/Avalonia.Base/Data/Core/Parsers/ExpressionVisitorNodeBuilder.cs @@ -4,8 +4,6 @@ using System.Linq; using System.Linq.Expressions; using System.Reflection; -#nullable enable - namespace Avalonia.Data.Core.Parsers { class ExpressionVisitorNodeBuilder : ExpressionVisitor @@ -18,8 +16,8 @@ namespace Avalonia.Data.Core.Parsers static ExpressionVisitorNodeBuilder() { - AvaloniaObjectIndexer = typeof(AvaloniaObject).GetProperty("Item", new[] { typeof(AvaloniaProperty) }); - CreateDelegateMethod = typeof(MethodInfo).GetMethod("CreateDelegate", new[] { typeof(Type), typeof(object) }); + AvaloniaObjectIndexer = typeof(AvaloniaObject).GetProperty("Item", new[] { typeof(AvaloniaProperty) })!; + CreateDelegateMethod = typeof(MethodInfo).GetMethod("CreateDelegate", new[] { typeof(Type), typeof(object) })!; } public List Nodes { get; } @@ -164,7 +162,7 @@ namespace Avalonia.Data.Core.Parsers if (node.Method == CreateDelegateMethod) { var visited = Visit(node.Arguments[1]); - Nodes.Add(new PropertyAccessorNode(GetArgumentExpressionValue(node.Object).Name, _enableDataValidation)); + Nodes.Add(new PropertyAccessorNode(GetArgumentExpressionValue(node.Object!).Name, _enableDataValidation)); return node; } else if (node.Method.Name == StreamBindingExtensions.StreamBindingName || node.Method.Name.StartsWith(StreamBindingExtensions.StreamBindingName + '`')) @@ -185,20 +183,20 @@ namespace Avalonia.Data.Core.Parsers if (property != null) { - return Visit(Expression.MakeIndex(node.Object, property, node.Arguments)); + return Visit(Expression.MakeIndex(node.Object!, property, node.Arguments)); } - else if (node.Object.Type.IsArray && node.Method.Name == MultiDimensionalArrayGetterMethodName) + else if (node.Object!.Type.IsArray && node.Method.Name == MultiDimensionalArrayGetterMethodName) { return Visit(Expression.MakeIndex(node.Object, null, node.Arguments)); } - throw new ExpressionParseException(0, $"Invalid method call in binding expression: '{node.Method.DeclaringType.AssemblyQualifiedName}.{node.Method.Name}'."); + throw new ExpressionParseException(0, $"Invalid method call in binding expression: '{node.Method.DeclaringType!.AssemblyQualifiedName}.{node.Method.Name}'."); } - private PropertyInfo TryGetPropertyFromMethod(MethodInfo method) + private PropertyInfo? TryGetPropertyFromMethod(MethodInfo method) { var type = method.DeclaringType; - return type.GetRuntimeProperties().FirstOrDefault(prop => prop.GetMethod == method); + return type?.GetRuntimeProperties().FirstOrDefault(prop => prop.GetMethod == method); } protected override Expression VisitSwitch(SwitchExpression node) diff --git a/src/Avalonia.Base/Data/Core/Plugins/AvaloniaPropertyAccessorPlugin.cs b/src/Avalonia.Base/Data/Core/Plugins/AvaloniaPropertyAccessorPlugin.cs index b72989ce00..3c4120ad0b 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/AvaloniaPropertyAccessorPlugin.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/AvaloniaPropertyAccessorPlugin.cs @@ -1,8 +1,6 @@ using System; using System.Runtime.ExceptionServices; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// @@ -74,12 +72,11 @@ namespace Avalonia.Data.Core.Plugins _property = property ?? throw new ArgumentNullException(nameof(property)); } - public AvaloniaObject Instance + public AvaloniaObject? Instance { get { - AvaloniaObject result; - _reference.TryGetTarget(out result); + _reference.TryGetTarget(out var result); return result; } } @@ -91,7 +88,7 @@ namespace Avalonia.Data.Core.Plugins { if (!_property.IsReadOnly) { - Instance.SetValue(_property, value, priority); + Instance?.SetValue(_property, value, priority); return true; } diff --git a/src/Avalonia.Base/Data/Core/Plugins/DataAnnotationsValidationPlugin.cs b/src/Avalonia.Base/Data/Core/Plugins/DataAnnotationsValidationPlugin.cs index 4d973d4aaa..361d68dc81 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/DataAnnotationsValidationPlugin.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/DataAnnotationsValidationPlugin.cs @@ -4,8 +4,6 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// @@ -33,19 +31,23 @@ namespace Avalonia.Data.Core.Plugins private sealed class Accessor : DataValidationBase { - private readonly ValidationContext _context; + private readonly ValidationContext? _context; public Accessor(WeakReference reference, string name, IPropertyAccessor inner) : base(inner) { - reference.TryGetTarget(out var target); - - _context = new ValidationContext(target); - _context.MemberName = name; + if (reference.TryGetTarget(out var target)) + { + _context = new ValidationContext(target); + _context.MemberName = name; + } } protected override void InnerValueChanged(object? value) { + if (_context is null) + return; + var errors = new List(); if (Validator.TryValidateProperty(value, _context, errors)) diff --git a/src/Avalonia.Base/Data/Core/Plugins/DataValidationBase.cs b/src/Avalonia.Base/Data/Core/Plugins/DataValidationBase.cs index 3e98d26fa1..6bef9f69f6 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/DataValidationBase.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/DataValidationBase.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// diff --git a/src/Avalonia.Base/Data/Core/Plugins/ExceptionValidationPlugin.cs b/src/Avalonia.Base/Data/Core/Plugins/ExceptionValidationPlugin.cs index 95855b09f4..bf4a0a88bd 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/ExceptionValidationPlugin.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/ExceptionValidationPlugin.cs @@ -1,8 +1,6 @@ using System; using System.Reflection; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// @@ -32,7 +30,7 @@ namespace Avalonia.Data.Core.Plugins { return base.SetValue(value, priority); } - catch (TargetInvocationException ex) + catch (TargetInvocationException ex) when (ex.InnerException is not null) { PublishValue(new BindingNotification(ex.InnerException, BindingErrorType.DataValidationError)); } diff --git a/src/Avalonia.Base/Data/Core/Plugins/IDataValidationPlugin.cs b/src/Avalonia.Base/Data/Core/Plugins/IDataValidationPlugin.cs index 549327bc0f..88e38a8d08 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/IDataValidationPlugin.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/IDataValidationPlugin.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// diff --git a/src/Avalonia.Base/Data/Core/Plugins/IPropertyAccessor.cs b/src/Avalonia.Base/Data/Core/Plugins/IPropertyAccessor.cs index 59017b5aae..8941e86598 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/IPropertyAccessor.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/IPropertyAccessor.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// diff --git a/src/Avalonia.Base/Data/Core/Plugins/IPropertyAccessorPlugin.cs b/src/Avalonia.Base/Data/Core/Plugins/IPropertyAccessorPlugin.cs index 4a391e8489..f000427de3 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/IPropertyAccessorPlugin.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/IPropertyAccessorPlugin.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// diff --git a/src/Avalonia.Base/Data/Core/Plugins/IStreamPlugin.cs b/src/Avalonia.Base/Data/Core/Plugins/IStreamPlugin.cs index 543bcba601..b741cfaca2 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/IStreamPlugin.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/IStreamPlugin.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// diff --git a/src/Avalonia.Base/Data/Core/Plugins/IndeiValidationPlugin.cs b/src/Avalonia.Base/Data/Core/Plugins/IndeiValidationPlugin.cs index 7b37b5d4e7..9f827daf94 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/IndeiValidationPlugin.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/IndeiValidationPlugin.cs @@ -4,8 +4,6 @@ using System.ComponentModel; using System.Linq; using Avalonia.Utilities; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// @@ -39,7 +37,7 @@ namespace Avalonia.Data.Core.Plugins _name = name; } - void IWeakSubscriber.OnEvent(object sender, DataErrorsChangedEventArgs e) + void IWeakSubscriber.OnEvent(object? sender, DataErrorsChangedEventArgs e) { if (e.PropertyName == _name || string.IsNullOrEmpty(e.PropertyName)) { diff --git a/src/Avalonia.Base/Data/Core/Plugins/InpcPropertyAccessorPlugin.cs b/src/Avalonia.Base/Data/Core/Plugins/InpcPropertyAccessorPlugin.cs index d5bf8da029..fd532f3014 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/InpcPropertyAccessorPlugin.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/InpcPropertyAccessorPlugin.cs @@ -4,8 +4,6 @@ using System.ComponentModel; using System.Reflection; using Avalonia.Utilities; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// @@ -131,7 +129,7 @@ namespace Avalonia.Data.Core.Plugins return false; } - void IWeakSubscriber.OnEvent(object sender, PropertyChangedEventArgs e) + void IWeakSubscriber.OnEvent(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == _property.Name || string.IsNullOrEmpty(e.PropertyName)) { diff --git a/src/Avalonia.Base/Data/Core/Plugins/MethodAccessorPlugin.cs b/src/Avalonia.Base/Data/Core/Plugins/MethodAccessorPlugin.cs index e0d686586c..160c7301f5 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/MethodAccessorPlugin.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/MethodAccessorPlugin.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; -#nullable enable - namespace Avalonia.Data.Core.Plugins { public class MethodAccessorPlugin : IPropertyAccessorPlugin diff --git a/src/Avalonia.Base/Data/Core/Plugins/ObservableStreamPlugin.cs b/src/Avalonia.Base/Data/Core/Plugins/ObservableStreamPlugin.cs index 7d77adfb00..0288dbce91 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/ObservableStreamPlugin.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/ObservableStreamPlugin.cs @@ -3,8 +3,6 @@ using System.Linq; using System.Reactive.Linq; using System.Reflection; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// @@ -57,14 +55,14 @@ namespace Avalonia.Data.Core.Plugins // Make a Box<> delegate of the correct type. var funcType = typeof(Func<,>).MakeGenericType(sourceType, typeof(object)); - var box = GetType().GetMethod(nameof(Box), BindingFlags.Static | BindingFlags.NonPublic) + var box = GetType().GetMethod(nameof(Box), BindingFlags.Static | BindingFlags.NonPublic)! .MakeGenericMethod(sourceType) .CreateDelegate(funcType); // Call Observable.Select(target, box); - return (IObservable)select.Invoke( + return (IObservable)select.Invoke( null, - new object[] { target, box }); + new object[] { target, box })!; } private static MethodInfo GetObservableSelect(Type source) diff --git a/src/Avalonia.Base/Data/Core/Plugins/PropertyAccessorBase.cs b/src/Avalonia.Base/Data/Core/Plugins/PropertyAccessorBase.cs index ba3fca1ab5..df36347e93 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/PropertyAccessorBase.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/PropertyAccessorBase.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// diff --git a/src/Avalonia.Base/Data/Core/Plugins/PropertyError.cs b/src/Avalonia.Base/Data/Core/Plugins/PropertyError.cs index c2a3214c0d..62629e13bd 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/PropertyError.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/PropertyError.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// diff --git a/src/Avalonia.Base/Data/Core/Plugins/TaskStreamPlugin.cs b/src/Avalonia.Base/Data/Core/Plugins/TaskStreamPlugin.cs index d1a3568a55..377ea9f275 100644 --- a/src/Avalonia.Base/Data/Core/Plugins/TaskStreamPlugin.cs +++ b/src/Avalonia.Base/Data/Core/Plugins/TaskStreamPlugin.cs @@ -4,8 +4,6 @@ using System.Reactive.Subjects; using System.Reflection; using System.Threading.Tasks; -#nullable enable - namespace Avalonia.Data.Core.Plugins { /// @@ -72,7 +70,7 @@ namespace Avalonia.Data.Core.Plugins case TaskStatus.RanToCompletion: return Observable.Return(resultProperty.GetValue(task)); case TaskStatus.Faulted: - return Observable.Return(new BindingNotification(task.Exception, BindingErrorType.Error)); + return Observable.Return(new BindingNotification(task.Exception!, BindingErrorType.Error)); default: throw new AvaloniaInternalException("HandleCompleted called for non-completed Task."); } diff --git a/src/Avalonia.Base/Data/Core/PropertyAccessorNode.cs b/src/Avalonia.Base/Data/Core/PropertyAccessorNode.cs index 92c3b65307..c13c6fcbc8 100644 --- a/src/Avalonia.Base/Data/Core/PropertyAccessorNode.cs +++ b/src/Avalonia.Base/Data/Core/PropertyAccessorNode.cs @@ -2,8 +2,6 @@ using System; using System.Diagnostics; using Avalonia.Data.Core.Plugins; -#nullable enable - namespace Avalonia.Data.Core { public class PropertyAccessorNode : SettableNode diff --git a/src/Avalonia.Base/Data/Core/PropertyPath.cs b/src/Avalonia.Base/Data/Core/PropertyPath.cs index 4ec402d7e1..665953c4a1 100644 --- a/src/Avalonia.Base/Data/Core/PropertyPath.cs +++ b/src/Avalonia.Base/Data/Core/PropertyPath.cs @@ -2,8 +2,6 @@ using System; using System.Collections.Generic; using System.Linq; -#nullable enable - namespace Avalonia.Data.Core { public class PropertyPath diff --git a/src/Avalonia.Base/Data/Core/SettableNode.cs b/src/Avalonia.Base/Data/Core/SettableNode.cs index 3467a16123..9ad9ace814 100644 --- a/src/Avalonia.Base/Data/Core/SettableNode.cs +++ b/src/Avalonia.Base/Data/Core/SettableNode.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data.Core { public abstract class SettableNode : ExpressionNode diff --git a/src/Avalonia.Base/Data/Core/StreamBindingExtensions.cs b/src/Avalonia.Base/Data/Core/StreamBindingExtensions.cs index 75fe37f958..fa2929c6ef 100644 --- a/src/Avalonia.Base/Data/Core/StreamBindingExtensions.cs +++ b/src/Avalonia.Base/Data/Core/StreamBindingExtensions.cs @@ -1,8 +1,6 @@ using System; using System.Threading.Tasks; -#nullable enable - namespace Avalonia { public static class StreamBindingExtensions diff --git a/src/Avalonia.Base/Data/Core/StreamNode.cs b/src/Avalonia.Base/Data/Core/StreamNode.cs index 086fbb7ee2..133e6a75f1 100644 --- a/src/Avalonia.Base/Data/Core/StreamNode.cs +++ b/src/Avalonia.Base/Data/Core/StreamNode.cs @@ -2,8 +2,6 @@ using System; using System.Reactive.Linq; using Avalonia.Data.Core.Plugins; -#nullable enable - namespace Avalonia.Data.Core { public class StreamNode : ExpressionNode diff --git a/src/Avalonia.Base/Data/Core/TypeCastNode.cs b/src/Avalonia.Base/Data/Core/TypeCastNode.cs index 2404c90fe2..3a2ca955fa 100644 --- a/src/Avalonia.Base/Data/Core/TypeCastNode.cs +++ b/src/Avalonia.Base/Data/Core/TypeCastNode.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.Text; -#nullable enable - namespace Avalonia.Data.Core { public class TypeCastNode : ExpressionNode diff --git a/src/Avalonia.Base/Data/DataValidationException.cs b/src/Avalonia.Base/Data/DataValidationException.cs index cafe74cd2c..74f39a1b6f 100644 --- a/src/Avalonia.Base/Data/DataValidationException.cs +++ b/src/Avalonia.Base/Data/DataValidationException.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Data { /// diff --git a/src/Avalonia.Base/Data/IBinding.cs b/src/Avalonia.Base/Data/IBinding.cs index 3b4add0269..9535cf608e 100644 --- a/src/Avalonia.Base/Data/IBinding.cs +++ b/src/Avalonia.Base/Data/IBinding.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Avalonia.Data { /// diff --git a/src/Avalonia.Base/Data/IndexerBinding.cs b/src/Avalonia.Base/Data/IndexerBinding.cs index bc8fe85a70..6a33d0c4fc 100644 --- a/src/Avalonia.Base/Data/IndexerBinding.cs +++ b/src/Avalonia.Base/Data/IndexerBinding.cs @@ -1,6 +1,4 @@ -#nullable enable - -namespace Avalonia.Data +namespace Avalonia.Data { public class IndexerBinding : IBinding { diff --git a/src/Avalonia.Base/Data/IndexerDescriptor.cs b/src/Avalonia.Base/Data/IndexerDescriptor.cs index 3c02509063..c823630d3c 100644 --- a/src/Avalonia.Base/Data/IndexerDescriptor.cs +++ b/src/Avalonia.Base/Data/IndexerDescriptor.cs @@ -1,8 +1,6 @@ using System; using System.Reactive; -#nullable enable - namespace Avalonia.Data { /// diff --git a/src/Avalonia.Base/Data/InstancedBinding.cs b/src/Avalonia.Base/Data/InstancedBinding.cs index dd7fcb3007..9ff319eddb 100644 --- a/src/Avalonia.Base/Data/InstancedBinding.cs +++ b/src/Avalonia.Base/Data/InstancedBinding.cs @@ -1,8 +1,6 @@ using System; using System.Reactive.Subjects; -#nullable enable - namespace Avalonia.Data { /// diff --git a/src/Avalonia.Base/Data/Optional.cs b/src/Avalonia.Base/Data/Optional.cs index d2283bf66b..513222d427 100644 --- a/src/Avalonia.Base/Data/Optional.cs +++ b/src/Avalonia.Base/Data/Optional.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -#nullable enable - namespace Avalonia.Data { /// diff --git a/src/Avalonia.Base/Diagnostics/AvaloniaPropertyValue.cs b/src/Avalonia.Base/Diagnostics/AvaloniaPropertyValue.cs index c881c389c1..4189fd5234 100644 --- a/src/Avalonia.Base/Diagnostics/AvaloniaPropertyValue.cs +++ b/src/Avalonia.Base/Diagnostics/AvaloniaPropertyValue.cs @@ -17,9 +17,9 @@ namespace Avalonia.Diagnostics /// A diagnostic string. public AvaloniaPropertyValue( AvaloniaProperty property, - object value, + object? value, BindingPriority priority, - string diagnostic) + string? diagnostic) { Property = property; Value = value; @@ -35,7 +35,7 @@ namespace Avalonia.Diagnostics /// /// Gets the current property value. /// - public object Value { get; } + public object? Value { get; } /// /// Gets the priority of the current value. @@ -45,6 +45,6 @@ namespace Avalonia.Diagnostics /// /// Gets a diagnostic string. /// - public string Diagnostic { get; } + public string? Diagnostic { get; } } } diff --git a/src/Avalonia.Base/Diagnostics/IAvaloniaObjectDebug.cs b/src/Avalonia.Base/Diagnostics/IAvaloniaObjectDebug.cs index 4b9f12ddf8..2d88203f67 100644 --- a/src/Avalonia.Base/Diagnostics/IAvaloniaObjectDebug.cs +++ b/src/Avalonia.Base/Diagnostics/IAvaloniaObjectDebug.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia.Diagnostics { /// diff --git a/src/Avalonia.Base/Diagnostics/INotifyCollectionChangedDebug.cs b/src/Avalonia.Base/Diagnostics/INotifyCollectionChangedDebug.cs index 36152e6430..00f2949b08 100644 --- a/src/Avalonia.Base/Diagnostics/INotifyCollectionChangedDebug.cs +++ b/src/Avalonia.Base/Diagnostics/INotifyCollectionChangedDebug.cs @@ -17,6 +17,6 @@ namespace Avalonia.Diagnostics /// /// The subscribers or null if no subscribers. /// - Delegate[] GetCollectionChangedSubscribers(); + Delegate[]? GetCollectionChangedSubscribers(); } } diff --git a/src/Avalonia.Base/DirectProperty.cs b/src/Avalonia.Base/DirectProperty.cs index eb04cfdce0..a5905a6081 100644 --- a/src/Avalonia.Base/DirectProperty.cs +++ b/src/Avalonia.Base/DirectProperty.cs @@ -2,8 +2,6 @@ using System; using System.Diagnostics.CodeAnalysis; using Avalonia.Data; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/DirectPropertyBase.cs b/src/Avalonia.Base/DirectPropertyBase.cs index 4b54ee75ab..9c4896b96c 100644 --- a/src/Avalonia.Base/DirectPropertyBase.cs +++ b/src/Avalonia.Base/DirectPropertyBase.cs @@ -3,8 +3,6 @@ using Avalonia.Data; using Avalonia.Reactive; using Avalonia.Utilities; -#nullable enable - namespace Avalonia { /// @@ -155,7 +153,7 @@ namespace Avalonia if (v.HasValue) { - o.SetValue(this, (TValue)v.Value); + o.SetValue(this, (TValue)v.Value!); } else if (v.Type == BindingValueType.UnsetValue) { diff --git a/src/Avalonia.Base/DirectPropertyMetadata`1.cs b/src/Avalonia.Base/DirectPropertyMetadata`1.cs index a265032139..fe1cdd0e65 100644 --- a/src/Avalonia.Base/DirectPropertyMetadata`1.cs +++ b/src/Avalonia.Base/DirectPropertyMetadata`1.cs @@ -1,7 +1,5 @@ using Avalonia.Data; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/EnumExtensions.cs b/src/Avalonia.Base/EnumExtensions.cs index 1f7c532cce..19eb42a700 100644 --- a/src/Avalonia.Base/EnumExtensions.cs +++ b/src/Avalonia.Base/EnumExtensions.cs @@ -1,8 +1,6 @@ using System; using System.Runtime.CompilerServices; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/IAvaloniaObject.cs b/src/Avalonia.Base/IAvaloniaObject.cs index 2e992f8616..654528658f 100644 --- a/src/Avalonia.Base/IAvaloniaObject.cs +++ b/src/Avalonia.Base/IAvaloniaObject.cs @@ -1,8 +1,6 @@ using System; using Avalonia.Data; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/IDescription.cs b/src/Avalonia.Base/IDescription.cs index 17a7f98776..e1ff52476d 100644 --- a/src/Avalonia.Base/IDescription.cs +++ b/src/Avalonia.Base/IDescription.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/IDirectPropertyAccessor.cs b/src/Avalonia.Base/IDirectPropertyAccessor.cs index e75ca238ad..e34483fa7b 100644 --- a/src/Avalonia.Base/IDirectPropertyAccessor.cs +++ b/src/Avalonia.Base/IDirectPropertyAccessor.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/IDirectPropertyMetadata.cs b/src/Avalonia.Base/IDirectPropertyMetadata.cs index 7b132d192e..4fd4a3a6b7 100644 --- a/src/Avalonia.Base/IDirectPropertyMetadata.cs +++ b/src/Avalonia.Base/IDirectPropertyMetadata.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/IStyledPropertyAccessor.cs b/src/Avalonia.Base/IStyledPropertyAccessor.cs index 6ef6391010..c4a0005f55 100644 --- a/src/Avalonia.Base/IStyledPropertyAccessor.cs +++ b/src/Avalonia.Base/IStyledPropertyAccessor.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/IStyledPropertyMetadata.cs b/src/Avalonia.Base/IStyledPropertyMetadata.cs index 2a0d09d6a7..6b29b5f977 100644 --- a/src/Avalonia.Base/IStyledPropertyMetadata.cs +++ b/src/Avalonia.Base/IStyledPropertyMetadata.cs @@ -1,5 +1,3 @@ -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/Logging/ILogSink.cs b/src/Avalonia.Base/Logging/ILogSink.cs index 71268d5965..27558ba0ee 100644 --- a/src/Avalonia.Base/Logging/ILogSink.cs +++ b/src/Avalonia.Base/Logging/ILogSink.cs @@ -23,7 +23,7 @@ namespace Avalonia.Logging void Log( LogEventLevel level, string area, - object source, + object? source, string messageTemplate); /// @@ -37,7 +37,7 @@ namespace Avalonia.Logging void Log( LogEventLevel level, string area, - object source, + object? source, string messageTemplate, T0 propertyValue0); @@ -53,7 +53,7 @@ namespace Avalonia.Logging void Log( LogEventLevel level, string area, - object source, + object? source, string messageTemplate, T0 propertyValue0, T1 propertyValue1); @@ -71,7 +71,7 @@ namespace Avalonia.Logging void Log( LogEventLevel level, string area, - object source, + object? source, string messageTemplate, T0 propertyValue0, T1 propertyValue1, @@ -88,8 +88,8 @@ namespace Avalonia.Logging void Log( LogEventLevel level, string area, - object source, + object? source, string messageTemplate, - params object[] propertyValues); + params object?[] propertyValues); } } diff --git a/src/Avalonia.Base/Logging/Logger.cs b/src/Avalonia.Base/Logging/Logger.cs index ed3fad93fc..c3fffb62de 100644 --- a/src/Avalonia.Base/Logging/Logger.cs +++ b/src/Avalonia.Base/Logging/Logger.cs @@ -8,7 +8,7 @@ namespace Avalonia.Logging /// /// Gets or sets the application-defined sink that receives the messages. /// - public static ILogSink Sink { get; set; } + public static ILogSink? Sink { get; set; } /// /// Checks if given log level is enabled. @@ -34,7 +34,7 @@ namespace Avalonia.Logging return null; } - return new ParametrizedLogger(Sink, level, area); + return new ParametrizedLogger(Sink!, level, area); } /// diff --git a/src/Avalonia.Base/Logging/ParametrizedLogger.cs b/src/Avalonia.Base/Logging/ParametrizedLogger.cs index adadb0f990..6b7331b504 100644 --- a/src/Avalonia.Base/Logging/ParametrizedLogger.cs +++ b/src/Avalonia.Base/Logging/ParametrizedLogger.cs @@ -30,7 +30,7 @@ namespace Avalonia.Logging /// The message template. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Log( - object source, + object? source, string messageTemplate) { _sink.Log(_level, _area, source, messageTemplate); @@ -44,7 +44,7 @@ namespace Avalonia.Logging /// Message property value. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Log( - object source, + object? source, string messageTemplate, T0 propertyValue0) { @@ -60,7 +60,7 @@ namespace Avalonia.Logging /// Message property value. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Log( - object source, + object? source, string messageTemplate, T0 propertyValue0, T1 propertyValue1) @@ -78,7 +78,7 @@ namespace Avalonia.Logging /// Message property value. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Log( - object source, + object? source, string messageTemplate, T0 propertyValue0, T1 propertyValue1, @@ -98,7 +98,7 @@ namespace Avalonia.Logging /// Message property value. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Log( - object source, + object? source, string messageTemplate, T0 propertyValue0, T1 propertyValue1, @@ -120,7 +120,7 @@ namespace Avalonia.Logging /// Message property value. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Log( - object source, + object? source, string messageTemplate, T0 propertyValue0, T1 propertyValue1, @@ -144,7 +144,7 @@ namespace Avalonia.Logging /// Message property value. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Log( - object source, + object? source, string messageTemplate, T0 propertyValue0, T1 propertyValue1, diff --git a/src/Avalonia.Base/Logging/TraceLogSink.cs b/src/Avalonia.Base/Logging/TraceLogSink.cs index f597844378..02ed191d2c 100644 --- a/src/Avalonia.Base/Logging/TraceLogSink.cs +++ b/src/Avalonia.Base/Logging/TraceLogSink.cs @@ -9,11 +9,11 @@ namespace Avalonia.Logging public class TraceLogSink : ILogSink { private readonly LogEventLevel _level; - private readonly IList _areas; + private readonly IList? _areas; public TraceLogSink( LogEventLevel minimumLevel, - IList areas = null) + IList? areas = null) { _level = minimumLevel; _areas = areas?.Count > 0 ? areas : null; @@ -24,7 +24,7 @@ namespace Avalonia.Logging return level >= _level && (_areas?.Contains(area) ?? true); } - public void Log(LogEventLevel level, string area, object source, string messageTemplate) + public void Log(LogEventLevel level, string area, object? source, string messageTemplate) { if (IsEnabled(level, area)) { @@ -32,7 +32,7 @@ namespace Avalonia.Logging } } - public void Log(LogEventLevel level, string area, object source, string messageTemplate, T0 propertyValue0) + public void Log(LogEventLevel level, string area, object? source, string messageTemplate, T0 propertyValue0) { if (IsEnabled(level, area)) { @@ -40,7 +40,7 @@ namespace Avalonia.Logging } } - public void Log(LogEventLevel level, string area, object source, string messageTemplate, T0 propertyValue0, T1 propertyValue1) + public void Log(LogEventLevel level, string area, object? source, string messageTemplate, T0 propertyValue0, T1 propertyValue1) { if (IsEnabled(level, area)) { @@ -48,7 +48,7 @@ namespace Avalonia.Logging } } - public void Log(LogEventLevel level, string area, object source, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) + public void Log(LogEventLevel level, string area, object? source, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { if (IsEnabled(level, area)) { @@ -56,7 +56,7 @@ namespace Avalonia.Logging } } - public void Log(LogEventLevel level, string area, object source, string messageTemplate, params object[] propertyValues) + public void Log(LogEventLevel level, string area, object? source, string messageTemplate, params object?[] propertyValues) { if (IsEnabled(level, area)) { @@ -67,10 +67,10 @@ namespace Avalonia.Logging private static string Format( string area, string template, - object source, - T0 v0 = default, - T1 v1 = default, - T2 v2 = default) + object? source, + T0? v0 = default, + T1? v1 = default, + T2? v2 = default) { var result = new StringBuilder(template.Length); var r = new CharacterReader(template.AsSpan()); @@ -127,8 +127,8 @@ namespace Avalonia.Logging private static string Format( string area, string template, - object source, - object[] v) + object? source, + object?[] v) { var result = new StringBuilder(template.Length); var r = new CharacterReader(template.AsSpan()); diff --git a/src/Avalonia.Base/Metadata/TemplateContent.cs b/src/Avalonia.Base/Metadata/TemplateContent.cs index 7f9e878419..258154aba4 100644 --- a/src/Avalonia.Base/Metadata/TemplateContent.cs +++ b/src/Avalonia.Base/Metadata/TemplateContent.cs @@ -8,6 +8,6 @@ namespace Avalonia.Metadata [AttributeUsage(AttributeTargets.Property)] public class TemplateContentAttribute : Attribute { - public Type TemplateResultType { get; set; } + public Type? TemplateResultType { get; set; } } } diff --git a/src/Avalonia.Base/Platform/IAssetLoader.cs b/src/Avalonia.Base/Platform/IAssetLoader.cs index c2e422cabb..ec1f97f178 100644 --- a/src/Avalonia.Base/Platform/IAssetLoader.cs +++ b/src/Avalonia.Base/Platform/IAssetLoader.cs @@ -27,7 +27,7 @@ namespace Avalonia.Platform /// A base URI to use if is relative. /// /// True if the asset could be found; otherwise false. - bool Exists(Uri uri, Uri baseUri = null); + bool Exists(Uri uri, Uri? baseUri = null); /// /// Opens the asset with the requested URI. @@ -40,7 +40,7 @@ namespace Avalonia.Platform /// /// The asset could not be found. /// - Stream Open(Uri uri, Uri baseUri = null); + Stream Open(Uri uri, Uri? baseUri = null); /// /// Opens the asset with the requested URI and returns the asset stream and the @@ -56,7 +56,7 @@ namespace Avalonia.Platform /// /// The asset could not be found. /// - (Stream stream, Assembly assembly) OpenAndGetAssembly(Uri uri, Uri baseUri = null); + (Stream stream, Assembly assembly) OpenAndGetAssembly(Uri uri, Uri? baseUri = null); /// /// Extracts assembly information from URI @@ -66,7 +66,7 @@ namespace Avalonia.Platform /// A base URI to use if is relative. /// /// Assembly associated with the Uri - Assembly GetAssembly(Uri uri, Uri baseUri = null); + Assembly? GetAssembly(Uri uri, Uri? baseUri = null); /// /// Gets all assets of a folder and subfolders that match specified uri. diff --git a/src/Avalonia.Base/Platform/IPlatformHandle.cs b/src/Avalonia.Base/Platform/IPlatformHandle.cs index a3b9d8f07c..e1e9888045 100644 --- a/src/Avalonia.Base/Platform/IPlatformHandle.cs +++ b/src/Avalonia.Base/Platform/IPlatformHandle.cs @@ -15,6 +15,6 @@ namespace Avalonia.Platform /// /// Gets an optional string that describes what represents. /// - string HandleDescriptor { get; } + string? HandleDescriptor { get; } } } diff --git a/src/Avalonia.Base/Platform/Interop/Utf8Buffer.cs b/src/Avalonia.Base/Platform/Interop/Utf8Buffer.cs index 7117576b3b..7a0b5b34cd 100644 --- a/src/Avalonia.Base/Platform/Interop/Utf8Buffer.cs +++ b/src/Avalonia.Base/Platform/Interop/Utf8Buffer.cs @@ -8,9 +8,9 @@ namespace Avalonia.Platform.Interop public class Utf8Buffer : SafeHandle { private GCHandle _gcHandle; - private byte[] _data; + private byte[]? _data; - public Utf8Buffer(string s) : base(IntPtr.Zero, true) + public Utf8Buffer(string? s) : base(IntPtr.Zero, true) { if (s == null) return; @@ -19,7 +19,7 @@ namespace Avalonia.Platform.Interop handle = _gcHandle.AddrOfPinnedObject(); } - public int ByteLen => _data.Length; + public int ByteLen => _data?.Length ?? 0; protected override bool ReleaseHandle() { @@ -34,7 +34,7 @@ namespace Avalonia.Platform.Interop public override bool IsInvalid => handle == IntPtr.Zero; - public static unsafe string StringFromPtr(IntPtr s) + public static unsafe string? StringFromPtr(IntPtr s) { var pstr = (byte*)s; if (pstr == null) diff --git a/src/Avalonia.Base/Platform/PlatformHandle.cs b/src/Avalonia.Base/Platform/PlatformHandle.cs index bed25a3b5b..9cc2741a12 100644 --- a/src/Avalonia.Base/Platform/PlatformHandle.cs +++ b/src/Avalonia.Base/Platform/PlatformHandle.cs @@ -14,7 +14,7 @@ namespace Avalonia.Platform /// /// An optional string that describes what represents. /// - public PlatformHandle(IntPtr handle, string descriptor) + public PlatformHandle(IntPtr handle, string? descriptor) { Handle = handle; HandleDescriptor = descriptor; @@ -28,6 +28,6 @@ namespace Avalonia.Platform /// /// Gets an optional string that describes what represents. /// - public string HandleDescriptor { get; } + public string? HandleDescriptor { get; } } } diff --git a/src/Avalonia.Base/PropertyStore/BindingEntry.cs b/src/Avalonia.Base/PropertyStore/BindingEntry.cs index 315e28f84a..cffbaed6b0 100644 --- a/src/Avalonia.Base/PropertyStore/BindingEntry.cs +++ b/src/Avalonia.Base/PropertyStore/BindingEntry.cs @@ -2,8 +2,6 @@ using Avalonia.Data; using Avalonia.Threading; -#nullable enable - namespace Avalonia.PropertyStore { /// diff --git a/src/Avalonia.Base/PropertyStore/ConstantValueEntry.cs b/src/Avalonia.Base/PropertyStore/ConstantValueEntry.cs index 7e904f57df..c7fbf56abc 100644 --- a/src/Avalonia.Base/PropertyStore/ConstantValueEntry.cs +++ b/src/Avalonia.Base/PropertyStore/ConstantValueEntry.cs @@ -2,8 +2,6 @@ using System.Diagnostics.CodeAnalysis; using Avalonia.Data; -#nullable enable - namespace Avalonia.PropertyStore { /// diff --git a/src/Avalonia.Base/PropertyStore/IPriorityValueEntry.cs b/src/Avalonia.Base/PropertyStore/IPriorityValueEntry.cs index 4d82381323..26665ab683 100644 --- a/src/Avalonia.Base/PropertyStore/IPriorityValueEntry.cs +++ b/src/Avalonia.Base/PropertyStore/IPriorityValueEntry.cs @@ -1,6 +1,4 @@ -#nullable enable - -namespace Avalonia.PropertyStore +namespace Avalonia.PropertyStore { /// /// Represents an untyped interface to . diff --git a/src/Avalonia.Base/PropertyStore/IValue.cs b/src/Avalonia.Base/PropertyStore/IValue.cs index bbf4739e6a..a4ec06e64e 100644 --- a/src/Avalonia.Base/PropertyStore/IValue.cs +++ b/src/Avalonia.Base/PropertyStore/IValue.cs @@ -1,7 +1,5 @@ using Avalonia.Data; -#nullable enable - namespace Avalonia.PropertyStore { /// diff --git a/src/Avalonia.Base/PropertyStore/IValueSink.cs b/src/Avalonia.Base/PropertyStore/IValueSink.cs index 3a1e9731d8..738fdef267 100644 --- a/src/Avalonia.Base/PropertyStore/IValueSink.cs +++ b/src/Avalonia.Base/PropertyStore/IValueSink.cs @@ -1,7 +1,5 @@ using Avalonia.Data; -#nullable enable - namespace Avalonia.PropertyStore { /// diff --git a/src/Avalonia.Base/PropertyStore/LocalValueEntry.cs b/src/Avalonia.Base/PropertyStore/LocalValueEntry.cs index 4afc90e71d..cb5f3556d1 100644 --- a/src/Avalonia.Base/PropertyStore/LocalValueEntry.cs +++ b/src/Avalonia.Base/PropertyStore/LocalValueEntry.cs @@ -1,8 +1,6 @@ using System.Diagnostics.CodeAnalysis; using Avalonia.Data; -#nullable enable - namespace Avalonia.PropertyStore { /// diff --git a/src/Avalonia.Base/PropertyStore/PriorityValue.cs b/src/Avalonia.Base/PropertyStore/PriorityValue.cs index f5723cb3a7..f670160e75 100644 --- a/src/Avalonia.Base/PropertyStore/PriorityValue.cs +++ b/src/Avalonia.Base/PropertyStore/PriorityValue.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; using System.ComponentModel; using Avalonia.Data; -#nullable enable - namespace Avalonia.PropertyStore { /// diff --git a/src/Avalonia.Base/Reactive/AvaloniaPropertyBindingObservable.cs b/src/Avalonia.Base/Reactive/AvaloniaPropertyBindingObservable.cs index 9a0dc61ba3..238bb16e3e 100644 --- a/src/Avalonia.Base/Reactive/AvaloniaPropertyBindingObservable.cs +++ b/src/Avalonia.Base/Reactive/AvaloniaPropertyBindingObservable.cs @@ -2,17 +2,14 @@ using System.Collections.Generic; using Avalonia.Data; -#nullable enable - namespace Avalonia.Reactive { internal class AvaloniaPropertyBindingObservable : LightweightObservableBase>, IDescription { private readonly WeakReference _target; private readonly AvaloniaProperty _property; - private T _value; + private BindingValue _value = BindingValue.Unset; -#nullable disable public AvaloniaPropertyBindingObservable( IAvaloniaObject target, AvaloniaProperty property) @@ -20,7 +17,6 @@ namespace Avalonia.Reactive _target = new WeakReference(target); _property = property; } -#nullable enable public string Description => $"{_target.GetType().Name}.{_property.Name}"; @@ -43,10 +39,13 @@ namespace Avalonia.Reactive protected override void Subscribed(IObserver> observer, bool first) { - observer.OnNext(new BindingValue(_value)); + if (_value.Type != BindingValueType.UnsetValue) + { + observer.OnNext(_value); + } } - private void PropertyChanged(object sender, AvaloniaPropertyChangedEventArgs e) + private void PropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) { if (e.Property == _property) { @@ -54,7 +53,7 @@ namespace Avalonia.Reactive { var newValue = e.Sender.GetValue(typedArgs.Property); - if (!typedArgs.OldValue.HasValue || !EqualityComparer.Default.Equals(newValue, _value)) + if (!_value.HasValue || !EqualityComparer.Default.Equals(newValue, _value.Value)) { _value = newValue; PublishNext(_value); diff --git a/src/Avalonia.Base/Reactive/AvaloniaPropertyChangedObservable.cs b/src/Avalonia.Base/Reactive/AvaloniaPropertyChangedObservable.cs index 5ef0d25133..dc29ddbdff 100644 --- a/src/Avalonia.Base/Reactive/AvaloniaPropertyChangedObservable.cs +++ b/src/Avalonia.Base/Reactive/AvaloniaPropertyChangedObservable.cs @@ -35,7 +35,7 @@ namespace Avalonia.Reactive } } - private void PropertyChanged(object sender, AvaloniaPropertyChangedEventArgs e) + private void PropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) { if (e.Property == _property) { diff --git a/src/Avalonia.Base/Reactive/AvaloniaPropertyObservable.cs b/src/Avalonia.Base/Reactive/AvaloniaPropertyObservable.cs index 6a3f9b0b30..fbc126bb05 100644 --- a/src/Avalonia.Base/Reactive/AvaloniaPropertyObservable.cs +++ b/src/Avalonia.Base/Reactive/AvaloniaPropertyObservable.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Avalonia.Data; namespace Avalonia.Reactive { @@ -7,7 +8,7 @@ namespace Avalonia.Reactive { private readonly WeakReference _target; private readonly AvaloniaProperty _property; - private T _value; + private Optional _value; public AvaloniaPropertyObservable( IAvaloniaObject target, @@ -23,7 +24,7 @@ namespace Avalonia.Reactive { if (_target.TryGetTarget(out var target)) { - _value = (T)target.GetValue(_property); + _value = (T)target.GetValue(_property)!; target.PropertyChanged += PropertyChanged; } } @@ -34,14 +35,17 @@ namespace Avalonia.Reactive { target.PropertyChanged -= PropertyChanged; } + + _value = default; } protected override void Subscribed(IObserver observer, bool first) { - observer.OnNext(_value); + if (_value.HasValue) + observer.OnNext(_value.Value); } - private void PropertyChanged(object sender, AvaloniaPropertyChangedEventArgs e) + private void PropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) { if (e.Property == _property) { @@ -53,13 +57,14 @@ namespace Avalonia.Reactive } else { - newValue = (T)e.Sender.GetValue(e.Property); + newValue = (T)e.Sender.GetValue(e.Property)!; } - if (!EqualityComparer.Default.Equals(newValue, _value)) + if (!_value.HasValue || + !EqualityComparer.Default.Equals(newValue, _value.Value)) { _value = newValue; - PublishNext(_value); + PublishNext(_value.Value!); } } } diff --git a/src/Avalonia.Base/Reactive/BindingValueAdapter.cs b/src/Avalonia.Base/Reactive/BindingValueAdapter.cs index 8c80e9f48c..8eaf21dcdc 100644 --- a/src/Avalonia.Base/Reactive/BindingValueAdapter.cs +++ b/src/Avalonia.Base/Reactive/BindingValueAdapter.cs @@ -2,8 +2,6 @@ using System.Reactive.Subjects; using Avalonia.Data; -#nullable enable - namespace Avalonia.Reactive { internal class BindingValueAdapter : SingleSubscriberObservableBase>, diff --git a/src/Avalonia.Base/Reactive/BindingValueExtensions.cs b/src/Avalonia.Base/Reactive/BindingValueExtensions.cs index 6f0d29dd0f..770da2cab4 100644 --- a/src/Avalonia.Base/Reactive/BindingValueExtensions.cs +++ b/src/Avalonia.Base/Reactive/BindingValueExtensions.cs @@ -2,8 +2,6 @@ using System.Reactive.Subjects; using Avalonia.Data; -#nullable enable - namespace Avalonia.Reactive { public static class BindingValueExtensions diff --git a/src/Avalonia.Base/Reactive/LightweightObservableBase.cs b/src/Avalonia.Base/Reactive/LightweightObservableBase.cs index f5052e5858..9a3ab89b62 100644 --- a/src/Avalonia.Base/Reactive/LightweightObservableBase.cs +++ b/src/Avalonia.Base/Reactive/LightweightObservableBase.cs @@ -18,12 +18,13 @@ namespace Avalonia.Reactive /// public abstract class LightweightObservableBase : IObservable { - private Exception _error; - private List> _observers = new List>(); + private Exception? _error; + private List>? _observers = new List>(); public IDisposable Subscribe(IObserver observer) { - Contract.Requires(observer != null); + _ = observer ?? throw new ArgumentNullException(nameof(observer)); + Dispatcher.UIThread.VerifyAccess(); var first = false; @@ -91,9 +92,9 @@ namespace Avalonia.Reactive sealed class RemoveObserver : IDisposable { - LightweightObservableBase _parent; + LightweightObservableBase? _parent; - IObserver _observer; + IObserver? _observer; public RemoveObserver(LightweightObservableBase parent, IObserver observer) { @@ -104,7 +105,7 @@ namespace Avalonia.Reactive public void Dispose() { var observer = _observer; - Interlocked.Exchange(ref _parent, null)?.Remove(observer); + Interlocked.Exchange(ref _parent, null)?.Remove(observer!); _observer = null; } } @@ -116,8 +117,8 @@ namespace Avalonia.Reactive { if (Volatile.Read(ref _observers) != null) { - IObserver[] observers = null; - IObserver singleObserver = null; + IObserver[]? observers = null; + IObserver? singleObserver = null; lock (this) { if (_observers == null) @@ -139,7 +140,7 @@ namespace Avalonia.Reactive } else { - foreach (var observer in observers) + foreach (var observer in observers!) { observer.OnNext(value); } diff --git a/src/Avalonia.Base/Reactive/ObservableEx.cs b/src/Avalonia.Base/Reactive/ObservableEx.cs index 8e963fb9d5..1cea568c88 100644 --- a/src/Avalonia.Base/Reactive/ObservableEx.cs +++ b/src/Avalonia.Base/Reactive/ObservableEx.cs @@ -34,4 +34,4 @@ namespace Avalonia.Reactive } } } -} \ No newline at end of file +} diff --git a/src/Avalonia.Base/Reactive/SingleSubscriberObservableBase.cs b/src/Avalonia.Base/Reactive/SingleSubscriberObservableBase.cs index d3ac3dac8a..5e3a6bf79a 100644 --- a/src/Avalonia.Base/Reactive/SingleSubscriberObservableBase.cs +++ b/src/Avalonia.Base/Reactive/SingleSubscriberObservableBase.cs @@ -5,13 +5,13 @@ namespace Avalonia.Reactive { public abstract class SingleSubscriberObservableBase : IObservable, IDisposable { - private Exception _error; - private IObserver _observer; + private Exception? _error; + private IObserver? _observer; private bool _completed; public IDisposable Subscribe(IObserver observer) { - Contract.Requires(observer != null); + _ = observer ?? throw new ArgumentNullException(nameof(observer)); Dispatcher.UIThread.VerifyAccess(); if (_observer != null) diff --git a/src/Avalonia.Base/Reactive/TypedBindingAdapter.cs b/src/Avalonia.Base/Reactive/TypedBindingAdapter.cs index 44803bc7d6..f60ef247d5 100644 --- a/src/Avalonia.Base/Reactive/TypedBindingAdapter.cs +++ b/src/Avalonia.Base/Reactive/TypedBindingAdapter.cs @@ -2,8 +2,6 @@ using Avalonia.Data; using Avalonia.Logging; -#nullable enable - namespace Avalonia.Reactive { internal class TypedBindingAdapter : SingleSubscriberObservableBase>, diff --git a/src/Avalonia.Base/Reactive/UntypedBindingAdapter.cs b/src/Avalonia.Base/Reactive/UntypedBindingAdapter.cs index 03c1afcea9..58fbee7b8f 100644 --- a/src/Avalonia.Base/Reactive/UntypedBindingAdapter.cs +++ b/src/Avalonia.Base/Reactive/UntypedBindingAdapter.cs @@ -2,8 +2,6 @@ using System.Reactive.Subjects; using Avalonia.Data; -#nullable enable - namespace Avalonia.Reactive { internal class UntypedBindingAdapter : SingleSubscriberObservableBase, diff --git a/src/Avalonia.Base/StyledProperty.cs b/src/Avalonia.Base/StyledProperty.cs index 4bd24d4a42..d00a675d0f 100644 --- a/src/Avalonia.Base/StyledProperty.cs +++ b/src/Avalonia.Base/StyledProperty.cs @@ -1,7 +1,5 @@ using System; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/StyledPropertyBase.cs b/src/Avalonia.Base/StyledPropertyBase.cs index 526b1175b4..16ba571a5a 100644 --- a/src/Avalonia.Base/StyledPropertyBase.cs +++ b/src/Avalonia.Base/StyledPropertyBase.cs @@ -4,8 +4,6 @@ using Avalonia.Data; using Avalonia.Reactive; using Avalonia.Utilities; -#nullable enable - namespace Avalonia { /// @@ -207,7 +205,7 @@ namespace Avalonia if (v.HasValue) { - return o.SetValue(this, (TValue)v.Value, priority); + return o.SetValue(this, (TValue)v.Value!, priority); } else if (v.Type == BindingValueType.UnsetValue) { diff --git a/src/Avalonia.Base/StyledPropertyMetadata`1.cs b/src/Avalonia.Base/StyledPropertyMetadata`1.cs index a9f7eb38de..0a38960228 100644 --- a/src/Avalonia.Base/StyledPropertyMetadata`1.cs +++ b/src/Avalonia.Base/StyledPropertyMetadata`1.cs @@ -1,8 +1,6 @@ using System; using Avalonia.Data; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Base/Threading/AvaloniaSynchronizationContext.cs b/src/Avalonia.Base/Threading/AvaloniaSynchronizationContext.cs index 326d1a3f53..b991f9eb40 100644 --- a/src/Avalonia.Base/Threading/AvaloniaSynchronizationContext.cs +++ b/src/Avalonia.Base/Threading/AvaloniaSynchronizationContext.cs @@ -28,13 +28,13 @@ namespace Avalonia.Threading } /// - public override void Post(SendOrPostCallback d, object state) + public override void Post(SendOrPostCallback d, object? state) { Dispatcher.UIThread.Post(() => d(state), DispatcherPriority.Send); } /// - public override void Send(SendOrPostCallback d, object state) + public override void Send(SendOrPostCallback d, object? state) { if (Dispatcher.UIThread.CheckAccess()) d(state); diff --git a/src/Avalonia.Base/Threading/Dispatcher.cs b/src/Avalonia.Base/Threading/Dispatcher.cs index fe2cec11f0..949c11fbe0 100644 --- a/src/Avalonia.Base/Threading/Dispatcher.cs +++ b/src/Avalonia.Base/Threading/Dispatcher.cs @@ -15,12 +15,12 @@ namespace Avalonia.Threading public class Dispatcher : IDispatcher { private readonly JobRunner _jobRunner; - private IPlatformThreadingInterface _platform; + private IPlatformThreadingInterface? _platform; public static Dispatcher UIThread { get; } = new Dispatcher(AvaloniaLocator.Current.GetService()); - public Dispatcher(IPlatformThreadingInterface platform) + public Dispatcher(IPlatformThreadingInterface? platform) { _platform = platform; _jobRunner = new JobRunner(platform); @@ -57,6 +57,10 @@ namespace Avalonia.Threading public void MainLoop(CancellationToken cancellationToken) { var platform = AvaloniaLocator.Current.GetService(); + + if (platform is null) + throw new InvalidOperationException("Unable to locate IPlatformThreadingInterface"); + cancellationToken.Register(() => platform.Signal(DispatcherPriority.Send)); platform.RunLoop(cancellationToken); } @@ -78,35 +82,35 @@ namespace Avalonia.Threading /// public Task InvokeAsync(Action action, DispatcherPriority priority = DispatcherPriority.Normal) { - Contract.Requires(action != null); + _ = action ?? throw new ArgumentNullException(nameof(action)); return _jobRunner.InvokeAsync(action, priority); } /// public Task InvokeAsync(Func function, DispatcherPriority priority = DispatcherPriority.Normal) { - Contract.Requires(function != null); + _ = function ?? throw new ArgumentNullException(nameof(function)); return _jobRunner.InvokeAsync(function, priority); } /// public Task InvokeAsync(Func function, DispatcherPriority priority = DispatcherPriority.Normal) { - Contract.Requires(function != null); + _ = function ?? throw new ArgumentNullException(nameof(function)); return _jobRunner.InvokeAsync(function, priority).Unwrap(); } /// public Task InvokeAsync(Func> function, DispatcherPriority priority = DispatcherPriority.Normal) { - Contract.Requires(function != null); + _ = function ?? throw new ArgumentNullException(nameof(function)); return _jobRunner.InvokeAsync(function, priority).Unwrap(); } /// public void Post(Action action, DispatcherPriority priority = DispatcherPriority.Normal) { - Contract.Requires(action != null); + _ = action ?? throw new ArgumentNullException(nameof(action)); _jobRunner.Post(action, priority); } @@ -142,4 +146,4 @@ namespace Avalonia.Threading } } } -} \ No newline at end of file +} diff --git a/src/Avalonia.Base/Threading/DispatcherTimer.cs b/src/Avalonia.Base/Threading/DispatcherTimer.cs index 56cde9738e..93023b90a5 100644 --- a/src/Avalonia.Base/Threading/DispatcherTimer.cs +++ b/src/Avalonia.Base/Threading/DispatcherTimer.cs @@ -9,7 +9,7 @@ namespace Avalonia.Threading /// public class DispatcherTimer { - private IDisposable _timer; + private IDisposable? _timer; private readonly DispatcherPriority _priority; @@ -58,7 +58,7 @@ namespace Avalonia.Threading /// /// Raised when the timer ticks. /// - public event EventHandler Tick; + public event EventHandler? Tick; /// /// Gets or sets the interval at which the timer ticks. @@ -108,7 +108,7 @@ namespace Avalonia.Threading /// /// Gets or sets user-defined data associated with the timer. /// - public object Tag + public object? Tag { get; set; @@ -176,7 +176,7 @@ namespace Avalonia.Threading { if (!IsEnabled) { - IPlatformThreadingInterface threading = AvaloniaLocator.Current.GetService(); + var threading = AvaloniaLocator.Current.GetService(); if (threading == null) { @@ -194,7 +194,7 @@ namespace Avalonia.Threading { if (IsEnabled) { - _timer.Dispose(); + _timer!.Dispose(); _timer = null; } } @@ -210,4 +210,4 @@ namespace Avalonia.Threading Tick?.Invoke(this, EventArgs.Empty); } } -} \ No newline at end of file +} diff --git a/src/Avalonia.Base/Threading/JobRunner.cs b/src/Avalonia.Base/Threading/JobRunner.cs index 58f623fb3f..eb7c5e1af3 100644 --- a/src/Avalonia.Base/Threading/JobRunner.cs +++ b/src/Avalonia.Base/Threading/JobRunner.cs @@ -11,12 +11,12 @@ namespace Avalonia.Threading /// internal class JobRunner { - private IPlatformThreadingInterface _platform; + private IPlatformThreadingInterface? _platform; private readonly Queue[] _queues = Enumerable.Range(0, (int) DispatcherPriority.MaxValue + 1) .Select(_ => new Queue()).ToArray(); - public JobRunner(IPlatformThreadingInterface platform) + public JobRunner(IPlatformThreadingInterface? platform) { _platform = platform; } @@ -48,7 +48,7 @@ namespace Avalonia.Threading { var job = new Job(action, priority, false); AddJob(job); - return job.Task; + return job.Task!; } /// @@ -96,7 +96,7 @@ namespace Avalonia.Threading _platform?.Signal(job.Priority); } - private IJob GetNextJob(DispatcherPriority minimumPriority) + private IJob? GetNextJob(DispatcherPriority minimumPriority) { for (int c = (int) DispatcherPriority.MaxValue; c >= (int) minimumPriority; c--) { @@ -135,7 +135,7 @@ namespace Avalonia.Threading /// /// The task completion source. /// - private readonly TaskCompletionSource _taskCompletionSource; + private readonly TaskCompletionSource? _taskCompletionSource; /// /// Initializes a new instance of the class. @@ -147,7 +147,7 @@ namespace Avalonia.Threading { _action = action; Priority = priority; - _taskCompletionSource = throwOnUiThread ? null : new TaskCompletionSource(); + _taskCompletionSource = throwOnUiThread ? null : new TaskCompletionSource(); } /// @@ -156,7 +156,7 @@ namespace Avalonia.Threading /// /// The task. /// - public Task Task => _taskCompletionSource?.Task; + public Task? Task => _taskCompletionSource?.Task; /// void IJob.Run() diff --git a/src/Avalonia.Base/Utilities/AvaloniaPropertyValueStore.cs b/src/Avalonia.Base/Utilities/AvaloniaPropertyValueStore.cs index c513f75962..cbe3771577 100644 --- a/src/Avalonia.Base/Utilities/AvaloniaPropertyValueStore.cs +++ b/src/Avalonia.Base/Utilities/AvaloniaPropertyValueStore.cs @@ -2,8 +2,6 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -#nullable enable - namespace Avalonia.Utilities { /// diff --git a/src/Avalonia.Base/Utilities/AvaloniaResourcesIndex.cs b/src/Avalonia.Base/Utilities/AvaloniaResourcesIndex.cs index ed5bc697b0..09e408cb42 100644 --- a/src/Avalonia.Base/Utilities/AvaloniaResourcesIndex.cs +++ b/src/Avalonia.Base/Utilities/AvaloniaResourcesIndex.cs @@ -7,8 +7,6 @@ using System.Runtime.Serialization.Json; using System.Xml.Linq; using System.Linq; -// ReSharper disable AssignNullToNotNullAttribute - namespace Avalonia.Utilities { #if !BUILDTASK @@ -24,14 +22,14 @@ namespace Avalonia.Utilities throw new Exception("Resources index format version is not known"); var assetDoc = XDocument.Load(stream); - XNamespace assetNs = assetDoc.Root.Attribute("xmlns").Value; + XNamespace assetNs = assetDoc.Root!.Attribute("xmlns")!.Value; List entries= - (from entry in assetDoc.Root.Element(assetNs + "Entries").Elements(assetNs + "AvaloniaResourcesIndexEntry") + (from entry in assetDoc.Root.Element(assetNs + "Entries")!.Elements(assetNs + "AvaloniaResourcesIndexEntry") select new AvaloniaResourcesIndexEntry { - Path = entry.Element(assetNs + "Path").Value, - Offset = int.Parse(entry.Element(assetNs + "Offset").Value), - Size = int.Parse(entry.Element(assetNs + "Size").Value) + Path = entry.Element(assetNs + "Path")!.Value, + Offset = int.Parse(entry.Element(assetNs + "Offset")!.Value), + Size = int.Parse(entry.Element(assetNs + "Size")!.Value) }).ToList(); return entries; @@ -95,7 +93,7 @@ namespace Avalonia.Utilities class AvaloniaResourcesIndexEntry { [DataMember] - public string Path { get; set; } + public string? Path { get; set; } [DataMember] public int Offset { get; set; } diff --git a/src/Avalonia.Base/Utilities/DisposableLock.cs b/src/Avalonia.Base/Utilities/DisposableLock.cs index b06e97da00..c6f01b24fa 100644 --- a/src/Avalonia.Base/Utilities/DisposableLock.cs +++ b/src/Avalonia.Base/Utilities/DisposableLock.cs @@ -11,7 +11,7 @@ namespace Avalonia.Utilities /// Tries to take a lock /// /// IDisposable if succeeded to obtain the lock - public IDisposable TryLock() + public IDisposable? TryLock() { if (Monitor.TryEnter(_lock)) return new UnlockDisposable(_lock); @@ -29,7 +29,7 @@ namespace Avalonia.Utilities private sealed class UnlockDisposable : IDisposable { - private object _lock; + private object? _lock; public UnlockDisposable(object @lock) { @@ -38,7 +38,7 @@ namespace Avalonia.Utilities public void Dispose() { - object @lock = Interlocked.Exchange(ref _lock, null); + object? @lock = Interlocked.Exchange(ref _lock, null); if (@lock != null) { diff --git a/src/Avalonia.Base/Utilities/IAvaloniaPropertyVisitor.cs b/src/Avalonia.Base/Utilities/IAvaloniaPropertyVisitor.cs index 4b889eb129..6a8df91b81 100644 --- a/src/Avalonia.Base/Utilities/IAvaloniaPropertyVisitor.cs +++ b/src/Avalonia.Base/Utilities/IAvaloniaPropertyVisitor.cs @@ -1,6 +1,4 @@ -#nullable enable - -namespace Avalonia.Utilities +namespace Avalonia.Utilities { /// /// A visitor to resolve an untyped to a typed property. diff --git a/src/Avalonia.Base/Utilities/IWeakSubscriber.cs b/src/Avalonia.Base/Utilities/IWeakSubscriber.cs index a2907eea2e..613c931165 100644 --- a/src/Avalonia.Base/Utilities/IWeakSubscriber.cs +++ b/src/Avalonia.Base/Utilities/IWeakSubscriber.cs @@ -13,6 +13,6 @@ namespace Avalonia.Utilities /// /// The event sender. /// The event arguments. - void OnEvent(object sender, T e); + void OnEvent(object? sender, T e); } } diff --git a/src/Avalonia.Base/Utilities/ImmutableReadOnlyListStructEnumerator.cs b/src/Avalonia.Base/Utilities/ImmutableReadOnlyListStructEnumerator.cs index a1246c57b5..90d1c52ff5 100644 --- a/src/Avalonia.Base/Utilities/ImmutableReadOnlyListStructEnumerator.cs +++ b/src/Avalonia.Base/Utilities/ImmutableReadOnlyListStructEnumerator.cs @@ -7,21 +7,18 @@ namespace Avalonia.Utilities { private readonly IReadOnlyList _readOnlyList; private int _pos; + private T? _current; public ImmutableReadOnlyListStructEnumerator(IReadOnlyList readOnlyList) { _readOnlyList = readOnlyList; _pos = -1; - Current = default; + _current = default; } - public T Current - { - get; - private set; - } + public T Current => _current!; - object IEnumerator.Current => Current; + object? IEnumerator.Current => Current; public void Dispose() { } @@ -32,7 +29,7 @@ namespace Avalonia.Utilities return false; } - Current = _readOnlyList[++_pos]; + _current = _readOnlyList[++_pos]; return true; @@ -42,7 +39,7 @@ namespace Avalonia.Utilities { _pos = -1; - Current = default; + _current = default; } } } diff --git a/src/Avalonia.Base/Utilities/NonPumpingLockHelper.cs b/src/Avalonia.Base/Utilities/NonPumpingLockHelper.cs index fd4e5d2ace..4cc1ba5190 100644 --- a/src/Avalonia.Base/Utilities/NonPumpingLockHelper.cs +++ b/src/Avalonia.Base/Utilities/NonPumpingLockHelper.cs @@ -6,9 +6,9 @@ namespace Avalonia.Utilities { public interface IHelperImpl { - IDisposable Use(); + IDisposable? Use(); } - public static IDisposable Use() => AvaloniaLocator.Current.GetService()?.Use(); + public static IDisposable? Use() => AvaloniaLocator.Current.GetService()?.Use(); } } diff --git a/src/Avalonia.Base/Utilities/Ref.cs b/src/Avalonia.Base/Utilities/Ref.cs index c9ebeefebc..7209f02720 100644 --- a/src/Avalonia.Base/Utilities/Ref.cs +++ b/src/Avalonia.Base/Utilities/Ref.cs @@ -82,7 +82,7 @@ namespace Avalonia.Utilities class RefCounter { - private IDisposable _item; + private IDisposable? _item; private volatile int _refs; public RefCounter(IDisposable item) @@ -120,7 +120,7 @@ namespace Avalonia.Utilities { if (old == 1) { - _item.Dispose(); + _item?.Dispose(); _item = null; } break; @@ -134,7 +134,7 @@ namespace Avalonia.Utilities class Ref : CriticalFinalizerObject, IRef where T : class { - private T _item; + private T? _item; private RefCounter _counter; private object _lock = new object(); @@ -168,7 +168,7 @@ namespace Avalonia.Utilities { lock (_lock) { - return _item; + return _item!; } } } @@ -206,4 +206,4 @@ namespace Avalonia.Utilities } } -} \ No newline at end of file +} diff --git a/src/Avalonia.Base/Utilities/SingleOrDictionary.cs b/src/Avalonia.Base/Utilities/SingleOrDictionary.cs index 140da6750d..00cc5864f5 100644 --- a/src/Avalonia.Base/Utilities/SingleOrDictionary.cs +++ b/src/Avalonia.Base/Utilities/SingleOrDictionary.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Avalonia.Utilities @@ -11,9 +12,10 @@ namespace Avalonia.Utilities /// The type of the key. /// The type of the value. public class SingleOrDictionary : IEnumerable> + where TKey : notnull { private KeyValuePair? _singleValue; - private Dictionary dictionary; + private Dictionary? dictionary; public void Add(TKey key, TValue value) { @@ -34,7 +36,7 @@ namespace Avalonia.Utilities } } - public bool TryGetValue(TKey key, out TValue value) + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { if (dictionary == null) { @@ -120,7 +122,7 @@ namespace Avalonia.Utilities } } - object IEnumerator.Current => Current; + object? IEnumerator.Current => Current; public void Dispose() { diff --git a/src/Avalonia.Base/Utilities/SingleOrQueue.cs b/src/Avalonia.Base/Utilities/SingleOrQueue.cs index 643b0ba04d..99a92f6788 100644 --- a/src/Avalonia.Base/Utilities/SingleOrQueue.cs +++ b/src/Avalonia.Base/Utilities/SingleOrQueue.cs @@ -9,8 +9,8 @@ namespace Avalonia.Utilities /// The type of items held in the queue. public class SingleOrQueue { - private T _head; - private Queue _tail; + private T? _head; + private Queue? _tail; private Queue Tail => _tail ?? (_tail = new Queue()); @@ -51,7 +51,7 @@ namespace Avalonia.Utilities Empty = true; } - return result; + return result!; } } } diff --git a/src/Avalonia.Base/Utilities/StringTokenizer.cs b/src/Avalonia.Base/Utilities/StringTokenizer.cs index 24e99febb9..748eb09209 100644 --- a/src/Avalonia.Base/Utilities/StringTokenizer.cs +++ b/src/Avalonia.Base/Utilities/StringTokenizer.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using static System.Char; @@ -14,19 +15,19 @@ namespace Avalonia.Utilities private readonly string _s; private readonly int _length; private readonly char _separator; - private readonly string _exceptionMessage; + private readonly string? _exceptionMessage; private readonly IFormatProvider _formatProvider; private int _index; private int _tokenIndex; private int _tokenLength; - public StringTokenizer(string s, IFormatProvider formatProvider, string exceptionMessage = null) + public StringTokenizer(string s, IFormatProvider formatProvider, string? exceptionMessage = null) : this(s, GetSeparatorFromFormatProvider(formatProvider), exceptionMessage) { _formatProvider = formatProvider; } - public StringTokenizer(string s, char separator = DefaultSeparatorChar, string exceptionMessage = null) + public StringTokenizer(string s, char separator = DefaultSeparatorChar, string? exceptionMessage = null) { _s = s ?? throw new ArgumentNullException(nameof(s)); _length = s?.Length ?? 0; @@ -43,7 +44,7 @@ namespace Avalonia.Utilities } } - public string CurrentToken => _tokenIndex < 0 ? null : _s.Substring(_tokenIndex, _tokenLength); + public string? CurrentToken => _tokenIndex < 0 ? null : _s.Substring(_tokenIndex, _tokenLength); public void Dispose() { @@ -101,7 +102,7 @@ namespace Avalonia.Utilities return result; } - public bool TryReadString(out string result, char? separator = null) + public bool TryReadString([MaybeNullWhen(false)] out string result, char? separator = null) { var success = TryReadToken(separator ?? _separator); result = CurrentToken; @@ -219,4 +220,4 @@ namespace Avalonia.Utilities return c; } } -} \ No newline at end of file +} diff --git a/src/Avalonia.Base/Utilities/SynchronousCompletionAsyncResult.cs b/src/Avalonia.Base/Utilities/SynchronousCompletionAsyncResult.cs index f321b2b2f1..fb8d3ed224 100644 --- a/src/Avalonia.Base/Utilities/SynchronousCompletionAsyncResult.cs +++ b/src/Avalonia.Base/Utilities/SynchronousCompletionAsyncResult.cs @@ -10,8 +10,8 @@ namespace Avalonia.Utilities /// public struct SynchronousCompletionAsyncResult : INotifyCompletion { - private readonly SynchronousCompletionAsyncResultSource _source; - private readonly T _result; + private readonly SynchronousCompletionAsyncResultSource? _source; + private readonly T? _result; private readonly bool _isValid; internal SynchronousCompletionAsyncResult(SynchronousCompletionAsyncResultSource source) { @@ -44,7 +44,7 @@ namespace Avalonia.Utilities { if (!_isValid) ThrowNotInitialized(); - return _source == null ? _result : _source.Result; + return _source == null ? _result! : _source.Result; } @@ -67,15 +67,15 @@ namespace Avalonia.Utilities /// public class SynchronousCompletionAsyncResultSource { - private T _result; + private T? _result; internal bool IsCompleted { get; private set; } public SynchronousCompletionAsyncResult AsyncResult => new SynchronousCompletionAsyncResult(this); internal T Result => IsCompleted ? - _result : + _result! : throw new InvalidOperationException("Asynchronous operation is not yet completed"); - private List _continuations; + private List? _continuations; internal void OnCompleted(Action continuation) { diff --git a/src/Avalonia.Base/Utilities/TypeUtilities.cs b/src/Avalonia.Base/Utilities/TypeUtilities.cs index 0978308ef6..d29335d3d0 100644 --- a/src/Avalonia.Base/Utilities/TypeUtilities.cs +++ b/src/Avalonia.Base/Utilities/TypeUtilities.cs @@ -112,7 +112,7 @@ namespace Avalonia.Utilities /// The type to cast to /// The value to check if cast possible /// True if the cast is possible, otherwise false. - public static bool CanCast(object value) + public static bool CanCast(object? value) { return value is T || (value is null && AcceptsNull()); } @@ -125,7 +125,7 @@ namespace Avalonia.Utilities /// The culture to use. /// If successful, contains the convert value. /// True if the cast was successful, otherwise false. - public static bool TryConvert(Type to, object value, CultureInfo culture, out object result) + public static bool TryConvert(Type to, object? value, CultureInfo? culture, out object? result) { if (value == null) { @@ -167,9 +167,9 @@ namespace Avalonia.Utilities { result = null; - if (TryConvert(Enum.GetUnderlyingType(toUnderl), value, culture, out object enumValue)) + if (TryConvert(Enum.GetUnderlyingType(toUnderl), value, culture, out var enumValue)) { - result = Enum.ToObject(toUnderl, enumValue); + result = Enum.ToObject(toUnderl, enumValue!); return true; } } @@ -244,7 +244,7 @@ namespace Avalonia.Utilities /// The value to convert. /// If successful, contains the converted value. /// True if the convert was successful, otherwise false. - public static bool TryConvertImplicit(Type to, object value, out object result) + public static bool TryConvertImplicit(Type to, object? value, out object? result) { if (value == null) { @@ -306,9 +306,9 @@ namespace Avalonia.Utilities /// The type to convert to.. /// The culture to use. /// A value of . - public static object ConvertOrDefault(object value, Type type, CultureInfo culture) + public static object? ConvertOrDefault(object? value, Type type, CultureInfo culture) { - return TryConvert(type, value, culture, out object result) ? result : Default(type); + return TryConvert(type, value, culture, out var result) ? result : Default(type); } /// @@ -318,16 +318,16 @@ namespace Avalonia.Utilities /// The value to convert. /// The type to convert to. /// A value of . - public static object ConvertImplicitOrDefault(object value, Type type) + public static object? ConvertImplicitOrDefault(object? value, Type type) { - return TryConvertImplicit(type, value, out object result) ? result : Default(type); + return TryConvertImplicit(type, value, out var result) ? result : Default(type); } public static T ConvertImplicit(object value) { if (TryConvertImplicit(typeof(T), value, out var result)) { - return (T)result; + return (T)result!; } throw new InvalidCastException( @@ -339,7 +339,7 @@ namespace Avalonia.Utilities /// /// The type. /// The default value. - public static object Default(Type type) + public static object? Default(Type type) { if (type.IsValueType) { @@ -367,7 +367,7 @@ namespace Avalonia.Utilities return false; } - Type underlyingType = Nullable.GetUnderlyingType(type); + var underlyingType = Nullable.GetUnderlyingType(type); if (underlyingType != null) { @@ -391,7 +391,7 @@ namespace Avalonia.Utilities return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } - private static MethodInfo FindTypeConversionOperatorMethod(Type fromType, Type toType, OperatorType operatorType) + private static MethodInfo? FindTypeConversionOperatorMethod(Type fromType, Type toType, OperatorType operatorType) { const string implicitName = "op_Implicit"; const string explicitName = "op_Explicit"; diff --git a/src/Avalonia.Base/Utilities/ValueSingleOrList.cs b/src/Avalonia.Base/Utilities/ValueSingleOrList.cs index dc32cedb76..c1e5d912a8 100644 --- a/src/Avalonia.Base/Utilities/ValueSingleOrList.cs +++ b/src/Avalonia.Base/Utilities/ValueSingleOrList.cs @@ -58,7 +58,7 @@ namespace Avalonia.Utilities List.Add(Single); List.Add(value); - Single = default; + Single = default!; } } } @@ -81,7 +81,7 @@ namespace Avalonia.Utilities if (EqualityComparer.Default.Equals(Single, value)) { - Single = default; + Single = default!; _isSingleSet = false; diff --git a/src/Avalonia.Base/Utilities/WeakEventHandlerManager.cs b/src/Avalonia.Base/Utilities/WeakEventHandlerManager.cs index 28c9dcc262..4605aba800 100644 --- a/src/Avalonia.Base/Utilities/WeakEventHandlerManager.cs +++ b/src/Avalonia.Base/Utilities/WeakEventHandlerManager.cs @@ -23,10 +23,11 @@ namespace Avalonia.Utilities public static void Subscribe(TTarget target, string eventName, EventHandler subscriber) where TEventArgs : EventArgs where TSubscriber : class { + _ = target ?? throw new ArgumentNullException(nameof(target)); + var dic = SubscriptionTypeStorage.Subscribers.GetOrCreateValue(target); - Subscription sub; - if (!dic.TryGetValue(eventName, out sub)) + if (!dic.TryGetValue(eventName, out var sub)) { dic[eventName] = sub = new Subscription(dic, typeof(TTarget), target, eventName); } @@ -45,13 +46,9 @@ namespace Avalonia.Utilities public static void Unsubscribe(object target, string eventName, EventHandler subscriber) where TEventArgs : EventArgs where TSubscriber : class { - SubscriptionDic dic; - - if (SubscriptionTypeStorage.Subscribers.TryGetValue(target, out dic)) + if (SubscriptionTypeStorage.Subscribers.TryGetValue(target, out var dic)) { - Subscription sub; - - if (dic.TryGetValue(eventName, out sub)) + if (dic.TryGetValue(eventName, out var sub)) { sub.Remove(subscriber); } @@ -100,11 +97,14 @@ namespace Avalonia.Utilities _sdic = sdic; _target = target; _eventName = eventName; - Dictionary evDic; - if (!Accessors.TryGetValue(targetType, out evDic)) + if (!Accessors.TryGetValue(targetType, out var evDic)) Accessors[targetType] = evDic = new Dictionary(); - if (!evDic.TryGetValue(eventName, out _info)) + if (evDic.TryGetValue(eventName, out var info)) + { + _info = info; + } + else { var ev = targetType.GetRuntimeEvents().FirstOrDefault(x => x.Name == eventName); @@ -118,13 +118,13 @@ namespace Avalonia.Utilities } var del = new Action(OnEvent); - _delegate = del.GetMethodInfo().CreateDelegate(_info.EventHandlerType, del.Target); - _info.AddMethod.Invoke(target, new[] { _delegate }); + _delegate = del.GetMethodInfo().CreateDelegate(_info.EventHandlerType!, del.Target); + _info.AddMethod!.Invoke(target, new[] { _delegate }); } void Destroy() { - _info.RemoveMethod.Invoke(_target, new[] { _delegate }); + _info.RemoveMethod!.Invoke(_target, new[] { _delegate }); _sdic.Remove(_eventName); } @@ -141,7 +141,7 @@ namespace Avalonia.Utilities MethodInfo method = s.Method; - var subscriber = (TSubscriber)s.Target; + var subscriber = (TSubscriber)s.Target!; if (!s_Callers.TryGetValue(method, out var caller)) s_Callers[method] = caller = (CallerDelegate)Delegate.CreateDelegate(typeof(CallerDelegate), null, method); @@ -161,7 +161,7 @@ namespace Avalonia.Utilities { var reference = _data[c].Subscriber; - if (reference != null && reference.TryGetTarget(out TSubscriber instance) && Equals(instance, s.Target)) + if (reference != null && reference.TryGetTarget(out var instance) && Equals(instance, s.Target)) { _data[c] = default; removed = true; @@ -181,7 +181,7 @@ namespace Avalonia.Utilities { var r = _data[c]; - TSubscriber target = null; + TSubscriber? target = null; r.Subscriber?.TryGetTarget(out target); @@ -208,8 +208,7 @@ namespace Avalonia.Utilities for(var c=0; c<_count; c++) { var r = _data[c].Subscriber; - TSubscriber sub; - if (r.TryGetTarget(out sub)) + if (r.TryGetTarget(out var sub)) { _data[c].Caller(sub, sender, eventArgs); } diff --git a/src/Avalonia.Base/Utilities/WeakObservable.cs b/src/Avalonia.Base/Utilities/WeakObservable.cs index 20e01c751f..52edc7ad1a 100644 --- a/src/Avalonia.Base/Utilities/WeakObservable.cs +++ b/src/Avalonia.Base/Utilities/WeakObservable.cs @@ -23,8 +23,8 @@ namespace Avalonia.Utilities string eventName) where TEventArgs : EventArgs { - Contract.Requires(target != null); - Contract.Requires(eventName != null); + _ = target ?? throw new ArgumentNullException(nameof(target)); + _ = eventName ?? throw new ArgumentNullException(nameof(eventName)); return Observable.Create>(observer => { @@ -43,7 +43,7 @@ namespace Avalonia.Utilities _observer = observer; } - public void OnEvent(object sender, TEventArgs e) + public void OnEvent(object? sender, TEventArgs e) { _observer.OnNext(new EventPattern(sender, e)); } diff --git a/src/Avalonia.Base/Utilities/WeakSubscriptionManager.cs b/src/Avalonia.Base/Utilities/WeakSubscriptionManager.cs index 65128e7932..66223e513d 100644 --- a/src/Avalonia.Base/Utilities/WeakSubscriptionManager.cs +++ b/src/Avalonia.Base/Utilities/WeakSubscriptionManager.cs @@ -22,10 +22,11 @@ namespace Avalonia.Utilities public static void Subscribe(TTarget target, string eventName, IWeakSubscriber subscriber) where TEventArgs : EventArgs { + _ = target ?? throw new ArgumentNullException(nameof(target)); + var dic = SubscriptionTypeStorage.Subscribers.GetOrCreateValue(target); - Subscription sub; - if (!dic.TryGetValue(eventName, out sub)) + if (!dic.TryGetValue(eventName, out var sub)) { dic[eventName] = sub = new Subscription(dic, typeof(TTarget), target, eventName); } @@ -43,13 +44,9 @@ namespace Avalonia.Utilities public static void Unsubscribe(object target, string eventName, IWeakSubscriber subscriber) where T : EventArgs { - SubscriptionDic dic; - - if (SubscriptionTypeStorage.Subscribers.TryGetValue(target, out dic)) + if (SubscriptionTypeStorage.Subscribers.TryGetValue(target, out var dic)) { - Subscription sub; - - if (dic.TryGetValue(eventName, out sub)) + if (dic.TryGetValue(eventName, out var sub)) { sub.Remove(subscriber); } @@ -79,7 +76,7 @@ namespace Avalonia.Utilities private readonly string _eventName; private readonly Delegate _delegate; - private WeakReference>[] _data = new WeakReference>[16]; + private WeakReference>?[] _data = new WeakReference>?[16]; private int _count = 0; public Subscription(SubscriptionDic sdic, Type targetType, object target, string eventName) @@ -87,11 +84,14 @@ namespace Avalonia.Utilities _sdic = sdic; _target = target; _eventName = eventName; - Dictionary evDic; - if (!Accessors.TryGetValue(targetType, out evDic)) + if (!Accessors.TryGetValue(targetType, out var evDic)) Accessors[targetType] = evDic = new Dictionary(); - if (!evDic.TryGetValue(eventName, out _info)) + if (evDic.TryGetValue(eventName, out var info)) + { + _info = info; + } + else { var ev = targetType.GetRuntimeEvents().FirstOrDefault(x => x.Name == eventName); @@ -105,13 +105,13 @@ namespace Avalonia.Utilities } var del = new Action(OnEvent); - _delegate = del.GetMethodInfo().CreateDelegate(_info.EventHandlerType, del.Target); - _info.AddMethod.Invoke(target, new[] { _delegate }); + _delegate = del.GetMethodInfo().CreateDelegate(_info.EventHandlerType!, del.Target); + _info.AddMethod!.Invoke(target, new[] { _delegate }); } void Destroy() { - _info.RemoveMethod.Invoke(_target, new[] { _delegate }); + _info.RemoveMethod!.Invoke(_target, new[] { _delegate }); _sdic.Remove(_eventName); } @@ -120,11 +120,11 @@ namespace Avalonia.Utilities if (_count == _data.Length) { //Extend capacity - var ndata = new WeakReference>[_data.Length*2]; + var ndata = new WeakReference>?[_data.Length*2]; Array.Copy(_data, ndata, _data.Length); _data = ndata; } - _data[_count] = s; + _data[_count] = s!; _count++; } @@ -135,7 +135,7 @@ namespace Avalonia.Utilities for (int c = 0; c < _count; ++c) { var reference = _data[c]; - IWeakSubscriber instance; + IWeakSubscriber? instance; if (reference != null && reference.TryGetTarget(out instance) && instance == s) { @@ -179,8 +179,7 @@ namespace Avalonia.Utilities for(var c=0; c<_count; c++) { var r = _data[c]; - IWeakSubscriber sub; - if (r.TryGetTarget(out sub)) + if (r?.TryGetTarget(out var sub) == true) sub.OnEvent(sender, eventArgs); else needCompact = true; diff --git a/src/Avalonia.Base/Utilities/WeakTimer.cs b/src/Avalonia.Base/Utilities/WeakTimer.cs index a4d18ca13b..ab784fca4d 100644 --- a/src/Avalonia.Base/Utilities/WeakTimer.cs +++ b/src/Avalonia.Base/Utilities/WeakTimer.cs @@ -23,8 +23,7 @@ namespace Avalonia.Utilities private void OnTick() { - IWeakTimerSubscriber subscriber; - if (!_subscriber.TryGetTarget(out subscriber) || !subscriber.Tick()) + if (!_subscriber.TryGetTarget(out var subscriber) || !subscriber.Tick()) Stop(); } diff --git a/src/Avalonia.Base/ValueStore.cs b/src/Avalonia.Base/ValueStore.cs index 9f036fbd34..6b7b598086 100644 --- a/src/Avalonia.Base/ValueStore.cs +++ b/src/Avalonia.Base/ValueStore.cs @@ -5,8 +5,6 @@ using Avalonia.Data; using Avalonia.PropertyStore; using Avalonia.Utilities; -#nullable enable - namespace Avalonia { /// diff --git a/src/Avalonia.Build.Tasks/Avalonia.Build.Tasks.csproj b/src/Avalonia.Build.Tasks/Avalonia.Build.Tasks.csproj index 47b4451817..7884f13ddb 100644 --- a/src/Avalonia.Build.Tasks/Avalonia.Build.Tasks.csproj +++ b/src/Avalonia.Build.Tasks/Avalonia.Build.Tasks.csproj @@ -89,6 +89,7 @@ Markup/%(RecursiveDir)%(FileName)%(Extension) + diff --git a/src/Avalonia.Controls/Application.cs b/src/Avalonia.Controls/Application.cs index df55d9e250..584c3db23b 100644 --- a/src/Avalonia.Controls/Application.cs +++ b/src/Avalonia.Controls/Application.cs @@ -38,8 +38,8 @@ namespace Avalonia /// private DataTemplates? _dataTemplates; - private readonly Lazy _clipboard = - new Lazy(() => (IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))); + private readonly Lazy _clipboard = + new Lazy(() => (IClipboard?)AvaloniaLocator.Current.GetService(typeof(IClipboard))); private readonly Styler _styler = new Styler(); private Styles? _styles; private IResourceDictionary? _resources; @@ -85,7 +85,7 @@ namespace Avalonia /// /// The current instance of the class. /// - public static Application Current + public static Application? Current { get { return AvaloniaLocator.Current.GetService(); } } @@ -125,7 +125,7 @@ namespace Avalonia /// /// Gets the application clipboard. /// - public IClipboard Clipboard => _clipboard.Value; + public IClipboard? Clipboard => _clipboard.Value; /// /// Gets the application's global resource dictionary. diff --git a/src/Avalonia.Controls/ContextMenu.cs b/src/Avalonia.Controls/ContextMenu.cs index d8fd864e9b..d94bff37df 100644 --- a/src/Avalonia.Controls/ContextMenu.cs +++ b/src/Avalonia.Controls/ContextMenu.cs @@ -417,7 +417,7 @@ namespace Avalonia.Controls { var keymap = AvaloniaLocator.Current.GetService(); - if (keymap.OpenContextMenu.Any(k => k.Matches(e)) + if (keymap?.OpenContextMenu.Any(k => k.Matches(e)) == true && !CancelClosing()) { Close(); diff --git a/src/Avalonia.Controls/Control.cs b/src/Avalonia.Controls/Control.cs index fe731b9d4b..441421181c 100644 --- a/src/Avalonia.Controls/Control.cs +++ b/src/Avalonia.Controls/Control.cs @@ -248,7 +248,11 @@ namespace Avalonia.Controls if (e.Source == this && !e.Handled) { - var keymap = AvaloniaLocator.Current.GetService().OpenContextMenu; + var keymap = AvaloniaLocator.Current.GetService()?.OpenContextMenu; + + if (keymap is null) + return; + var matches = false; for (var index = 0; index < keymap.Count; index++) diff --git a/src/Avalonia.Controls/Flyouts/FlyoutBase.cs b/src/Avalonia.Controls/Flyouts/FlyoutBase.cs index d78ddd4169..a08b82f512 100644 --- a/src/Avalonia.Controls/Flyouts/FlyoutBase.cs +++ b/src/Avalonia.Controls/Flyouts/FlyoutBase.cs @@ -399,7 +399,7 @@ namespace Avalonia.Controls.Primitives { var keymap = AvaloniaLocator.Current.GetService(); - if (keymap.OpenContextMenu.Any(k => k.Matches(e))) + if (keymap?.OpenContextMenu.Any(k => k.Matches(e)) == true) { e.Handled = HideCore(); } diff --git a/src/Avalonia.Controls/MaskedTextBox.cs b/src/Avalonia.Controls/MaskedTextBox.cs index a72c617f05..f59cef8223 100644 --- a/src/Avalonia.Controls/MaskedTextBox.cs +++ b/src/Avalonia.Controls/MaskedTextBox.cs @@ -207,9 +207,14 @@ namespace Avalonia.Controls bool Match(List gestures) => gestures.Any(g => g.Matches(e)); - if (Match(keymap.Paste)) + if (keymap is not null && Match(keymap.Paste)) { - var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync(); + var clipboard = (IClipboard?)AvaloniaLocator.Current.GetService(typeof(IClipboard)); + + if (clipboard is null) + return; + + var text = await clipboard.GetTextAsync(); if (text == null) return; diff --git a/src/Avalonia.Controls/MenuItem.cs b/src/Avalonia.Controls/MenuItem.cs index b661bcfe33..b843992f04 100644 --- a/src/Avalonia.Controls/MenuItem.cs +++ b/src/Avalonia.Controls/MenuItem.cs @@ -715,7 +715,7 @@ namespace Avalonia.Controls /// /// The service type. /// A service of the requested type. - public object GetService(Type serviceType) + public object? GetService(Type serviceType) { if (serviceType == typeof(IAccessKeyHandler)) { diff --git a/src/Avalonia.Controls/Platform/PlatformManager.cs b/src/Avalonia.Controls/Platform/PlatformManager.cs index acd45ad29a..8e9f64b3ad 100644 --- a/src/Avalonia.Controls/Platform/PlatformManager.cs +++ b/src/Avalonia.Controls/Platform/PlatformManager.cs @@ -8,9 +8,6 @@ namespace Avalonia.Controls.Platform { public static partial class PlatformManager { - static IPlatformSettings GetSettings() - => AvaloniaLocator.Current.GetService(); - static bool s_designerMode; public static IDisposable DesignerMode() diff --git a/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs b/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs index 07bc789cc1..80f3d345a6 100644 --- a/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs +++ b/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs @@ -545,6 +545,10 @@ namespace Avalonia.Controls.Primitives if (!e.Handled) { var keymap = AvaloniaLocator.Current.GetService(); + + if (keymap is null) + return; + bool Match(List gestures) => gestures.Any(g => g.Matches(e)); if (ItemCount > 0 && diff --git a/src/Avalonia.Controls/SystemDialog.cs b/src/Avalonia.Controls/SystemDialog.cs index d81926ecc7..3fac10b2d1 100644 --- a/src/Avalonia.Controls/SystemDialog.cs +++ b/src/Avalonia.Controls/SystemDialog.cs @@ -66,8 +66,9 @@ namespace Avalonia.Controls { if(parent == null) throw new ArgumentNullException(nameof(parent)); - return ((await AvaloniaLocator.Current.GetService() - .ShowFileDialogAsync(this, parent)) ?? + var service = AvaloniaLocator.Current.GetService() ?? + throw new InvalidOperationException("Unable to locate ISystemDialogImpl."); + return (await service.ShowFileDialogAsync(this, parent) ?? Array.Empty()).FirstOrDefault(); } } @@ -94,7 +95,9 @@ namespace Avalonia.Controls { if(parent == null) throw new ArgumentNullException(nameof(parent)); - return AvaloniaLocator.Current.GetService().ShowFileDialogAsync(this, parent); + var service = AvaloniaLocator.Current.GetService() ?? + throw new InvalidOperationException("Unable to locate ISystemDialogImpl."); + return service.ShowFileDialogAsync(this, parent); } } @@ -122,7 +125,9 @@ namespace Avalonia.Controls { if(parent == null) throw new ArgumentNullException(nameof(parent)); - return AvaloniaLocator.Current.GetService().ShowFolderDialogAsync(this, parent); + var service = AvaloniaLocator.Current.GetService() ?? + throw new InvalidOperationException("Unable to locate ISystemDialogImpl."); + return service.ShowFolderDialogAsync(this, parent); } } diff --git a/src/Avalonia.Controls/Templates/DataTemplateExtensions.cs b/src/Avalonia.Controls/Templates/DataTemplateExtensions.cs index 2b115aec7e..82a1758c26 100644 --- a/src/Avalonia.Controls/Templates/DataTemplateExtensions.cs +++ b/src/Avalonia.Controls/Templates/DataTemplateExtensions.cs @@ -47,7 +47,7 @@ namespace Avalonia.Controls.Templates currentTemplateHost = currentTemplateHost.LogicalParent; } - IGlobalDataTemplates global = AvaloniaLocator.Current.GetService(); + var global = AvaloniaLocator.Current.GetService(); if (global != null && global.IsDataTemplatesInitialized) { diff --git a/src/Avalonia.Controls/TrayIcon.cs b/src/Avalonia.Controls/TrayIcon.cs index 9fbc2fc8b2..03ffe830ed 100644 --- a/src/Avalonia.Controls/TrayIcon.cs +++ b/src/Avalonia.Controls/TrayIcon.cs @@ -65,7 +65,9 @@ namespace Avalonia.Controls } }); - if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime) + var app = Application.Current ?? throw new InvalidOperationException("Application not yet initialized."); + + if (app.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime) { lifetime.Exit += Lifetime_Exit; } @@ -186,7 +188,8 @@ namespace Avalonia.Controls private static void Lifetime_Exit(object sender, ControlledApplicationLifetimeExitEventArgs e) { - var trayIcons = GetIcons(Application.Current); + var app = Application.Current ?? throw new InvalidOperationException("Application not yet initialized."); + var trayIcons = GetIcons(app); RemoveIcons(trayIcons); } diff --git a/src/Avalonia.Controls/Utils/CollectionChangedEventManager.cs b/src/Avalonia.Controls/Utils/CollectionChangedEventManager.cs index c26c5e0513..1a190391b7 100644 --- a/src/Avalonia.Controls/Utils/CollectionChangedEventManager.cs +++ b/src/Avalonia.Controls/Utils/CollectionChangedEventManager.cs @@ -107,7 +107,7 @@ namespace Avalonia.Controls.Utils this); } - void IWeakSubscriber.OnEvent(object sender, NotifyCollectionChangedEventArgs e) + void IWeakSubscriber.OnEvent(object? sender, NotifyCollectionChangedEventArgs e) { static void Notify( INotifyCollectionChanged incc, diff --git a/src/Avalonia.Diagnostics/Diagnostics/ViewModels/MainViewModel.cs b/src/Avalonia.Diagnostics/Diagnostics/ViewModels/MainViewModel.cs index d0a4ad38c5..74f2f05948 100644 --- a/src/Avalonia.Diagnostics/Diagnostics/ViewModels/MainViewModel.cs +++ b/src/Avalonia.Diagnostics/Diagnostics/ViewModels/MainViewModel.cs @@ -14,7 +14,7 @@ namespace Avalonia.Diagnostics.ViewModels private readonly TreePageViewModel _visualTree; private readonly EventsPageViewModel _events; private readonly IDisposable _pointerOverSubscription; - private ViewModelBase _content; + private ViewModelBase? _content; private int _selectedTab; private string? _focusedControl; private string? _pointerOverElement; @@ -23,10 +23,7 @@ namespace Avalonia.Diagnostics.ViewModels private bool _showFpsOverlay; private bool _freezePopups; -#nullable disable - // Remove "nullable disable" after MemberNotNull will work on our CI. public MainViewModel(TopLevel root) -#nullable restore { _root = root; _logicalTree = new TreePageViewModel(this, LogicalTreeNode.Create(root)); @@ -34,7 +31,9 @@ namespace Avalonia.Diagnostics.ViewModels _events = new EventsPageViewModel(this); UpdateFocusedControl(); - KeyboardDevice.Instance.PropertyChanged += KeyboardPropertyChanged; + + if (KeyboardDevice.Instance is not null) + KeyboardDevice.Instance.PropertyChanged += KeyboardPropertyChanged; SelectedTab = 0; _pointerOverSubscription = root.GetObservable(TopLevel.PointerOverElementProperty) .Subscribe(x => PointerOverElement = x?.GetType().Name); @@ -90,10 +89,9 @@ namespace Avalonia.Diagnostics.ViewModels public ConsoleViewModel Console { get; } - public ViewModelBase Content + public ViewModelBase? Content { get { return _content; } - // [MemberNotNull(nameof(_content))] private set { if (_content is TreePageViewModel oldTree && @@ -185,7 +183,8 @@ namespace Avalonia.Diagnostics.ViewModels public void Dispose() { - KeyboardDevice.Instance.PropertyChanged -= KeyboardPropertyChanged; + if (KeyboardDevice.Instance is not null) + KeyboardDevice.Instance.PropertyChanged -= KeyboardPropertyChanged; _pointerOverSubscription.Dispose(); _logicalTree.Dispose(); _visualTree.Dispose(); @@ -195,7 +194,7 @@ namespace Avalonia.Diagnostics.ViewModels private void UpdateFocusedControl() { - FocusedControl = KeyboardDevice.Instance.FocusedElement?.GetType().Name; + FocusedControl = KeyboardDevice.Instance?.FocusedElement?.GetType().Name; } private void KeyboardPropertyChanged(object? sender, PropertyChangedEventArgs e) diff --git a/src/Avalonia.Input/AccessKeyHandler.cs b/src/Avalonia.Input/AccessKeyHandler.cs index 24feb357b9..a3330b65ae 100644 --- a/src/Avalonia.Input/AccessKeyHandler.cs +++ b/src/Avalonia.Input/AccessKeyHandler.cs @@ -143,7 +143,7 @@ namespace Avalonia.Input { // TODO: Use FocusScopes to store the current element and restore it when context menu is closed. // Save currently focused input element. - _restoreFocusElement = FocusManager.Instance.Current; + _restoreFocusElement = FocusManager.Instance?.Current; // When Alt is pressed without a main menu, or with a closed main menu, show // access key markers in the window (i.e. "_File"). diff --git a/src/Avalonia.Input/FocusManager.cs b/src/Avalonia.Input/FocusManager.cs index 177e6035b0..30301788bc 100644 --- a/src/Avalonia.Input/FocusManager.cs +++ b/src/Avalonia.Input/FocusManager.cs @@ -32,7 +32,7 @@ namespace Avalonia.Input /// /// Gets the instance of the . /// - public static IFocusManager Instance => AvaloniaLocator.Current.GetService(); + public static IFocusManager? Instance => AvaloniaLocator.Current.GetService(); /// /// Gets the currently focused . diff --git a/src/Avalonia.Input/InputElement.cs b/src/Avalonia.Input/InputElement.cs index 26ebf86857..c2197ee64d 100644 --- a/src/Avalonia.Input/InputElement.cs +++ b/src/Avalonia.Input/InputElement.cs @@ -499,7 +499,7 @@ namespace Avalonia.Input if (IsFocused) { - FocusManager.Instance.Focus(null); + FocusManager.Instance?.Focus(null); } } diff --git a/src/Avalonia.Input/InputManager.cs b/src/Avalonia.Input/InputManager.cs index 129b9cf474..f604ff8e74 100644 --- a/src/Avalonia.Input/InputManager.cs +++ b/src/Avalonia.Input/InputManager.cs @@ -17,7 +17,7 @@ namespace Avalonia.Input /// /// Gets the global instance of the input manager. /// - public static IInputManager Instance => AvaloniaLocator.Current.GetService(); + public static IInputManager? Instance => AvaloniaLocator.Current.GetService(); /// public IObservable PreProcess => _preProcess; diff --git a/src/Avalonia.Input/KeyboardDevice.cs b/src/Avalonia.Input/KeyboardDevice.cs index a159b19026..438e3fcadb 100644 --- a/src/Avalonia.Input/KeyboardDevice.cs +++ b/src/Avalonia.Input/KeyboardDevice.cs @@ -14,11 +14,11 @@ namespace Avalonia.Input public event PropertyChangedEventHandler? PropertyChanged; - public static IKeyboardDevice Instance => AvaloniaLocator.Current.GetService(); + public static IKeyboardDevice? Instance => AvaloniaLocator.Current.GetService(); - public IInputManager InputManager => AvaloniaLocator.Current.GetService(); + public IInputManager? InputManager => AvaloniaLocator.Current.GetService(); - public IFocusManager FocusManager => AvaloniaLocator.Current.GetService(); + public IFocusManager? FocusManager => AvaloniaLocator.Current.GetService(); // This should live in the FocusManager, but with the current outdated architecture // the source of truth about the input focus is in KeyboardDevice diff --git a/src/Avalonia.Input/KeyboardNavigationHandler.cs b/src/Avalonia.Input/KeyboardNavigationHandler.cs index b2ebee9ef5..f73203f6b7 100644 --- a/src/Avalonia.Input/KeyboardNavigationHandler.cs +++ b/src/Avalonia.Input/KeyboardNavigationHandler.cs @@ -89,7 +89,7 @@ namespace Avalonia.Input var method = direction == NavigationDirection.Next || direction == NavigationDirection.Previous ? NavigationMethod.Tab : NavigationMethod.Directional; - FocusManager.Instance.Focus(next, method, keyModifiers); + FocusManager.Instance?.Focus(next, method, keyModifiers); } } @@ -100,7 +100,7 @@ namespace Avalonia.Input /// The event args. protected virtual void OnKeyDown(object? sender, KeyEventArgs e) { - var current = FocusManager.Instance.Current; + var current = FocusManager.Instance?.Current; if (current != null && e.Key == Key.Tab) { diff --git a/src/Avalonia.Input/MouseDevice.cs b/src/Avalonia.Input/MouseDevice.cs index 6eccb3f101..a2c43013fd 100644 --- a/src/Avalonia.Input/MouseDevice.cs +++ b/src/Avalonia.Input/MouseDevice.cs @@ -240,7 +240,8 @@ namespace Avalonia.Input if (source != null) { var settings = AvaloniaLocator.Current.GetService(); - var doubleClickTime = settings.DoubleClickTime.TotalMilliseconds; + var doubleClickTime = settings?.DoubleClickTime.TotalMilliseconds ?? 500; + var doubleClickSize = settings?.DoubleClickSize ?? new Size(4, 4); if (!_lastClickRect.Contains(p) || timestamp - _lastClickTime > doubleClickTime) { @@ -250,7 +251,7 @@ namespace Avalonia.Input ++_clickCount; _lastClickTime = timestamp; _lastClickRect = new Rect(p, new Size()) - .Inflate(new Thickness(settings.DoubleClickSize.Width / 2, settings.DoubleClickSize.Height / 2)); + .Inflate(new Thickness(doubleClickSize.Width / 2, doubleClickSize.Height / 2)); _lastMouseDownButton = properties.PointerUpdateKind.GetMouseButton(); var e = new PointerPressedEventArgs(source, _pointer, root, p, timestamp, properties, inputModifiers, _clickCount); source.RaiseEvent(e); diff --git a/src/Avalonia.Visuals/Media/CombinedGeometry.cs b/src/Avalonia.Visuals/Media/CombinedGeometry.cs index 2202030b7a..b76c496c4e 100644 --- a/src/Avalonia.Visuals/Media/CombinedGeometry.cs +++ b/src/Avalonia.Visuals/Media/CombinedGeometry.cs @@ -154,7 +154,8 @@ namespace Avalonia.Media if (g1 is object && g2 is object) { - var factory = AvaloniaLocator.Current.GetService(); + var factory = AvaloniaLocator.Current.GetService() ?? + throw new InvalidOperationException("Unable to locate IPlatformRenderInterface."); return factory.CreateCombinedGeometry(GeometryCombineMode, g1, g2); } else if (GeometryCombineMode == GeometryCombineMode.Intersect) diff --git a/src/Avalonia.Visuals/Media/GeometryGroup.cs b/src/Avalonia.Visuals/Media/GeometryGroup.cs index edbe63d4bb..01d4923456 100644 --- a/src/Avalonia.Visuals/Media/GeometryGroup.cs +++ b/src/Avalonia.Visuals/Media/GeometryGroup.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Avalonia.Metadata; using Avalonia.Platform; @@ -60,7 +61,8 @@ namespace Avalonia.Media { if (_children?.Count > 0) { - var factory = AvaloniaLocator.Current.GetService(); + var factory = AvaloniaLocator.Current.GetService() ?? + throw new InvalidOperationException("Unable to locate IPlatformRenderInterface."); return factory.CreateGeometryGroup(FillRule, _children); } diff --git a/src/Avalonia.X11/X11CursorFactory.cs b/src/Avalonia.X11/X11CursorFactory.cs index 9c37de86bf..8e5cac1400 100644 --- a/src/Avalonia.X11/X11CursorFactory.cs +++ b/src/Avalonia.X11/X11CursorFactory.cs @@ -94,9 +94,13 @@ namespace Avalonia.X11 { var size = Marshal.SizeOf() + (bitmap.PixelSize.Width * bitmap.PixelSize.Height * 4); + var runtimePlatform = AvaloniaLocator.Current.GetService() ?? + throw new InvalidOperationException("Unable to locate IRuntimePlatform"); + var platformRenderInterface = AvaloniaLocator.Current.GetService() ?? + throw new InvalidOperationException("Unable to locate IPlatformRenderInterface"); _pixelSize = bitmap.PixelSize; - _blob = AvaloniaLocator.Current.GetService().AllocBlob(size); + _blob = runtimePlatform.AllocBlob(size); var image = (XcursorImage*)_blob.Address; image->version = 1; @@ -107,7 +111,7 @@ namespace Avalonia.X11 image->yhot = hotSpot.Y; image->pixels = (IntPtr)(image + 1); - using (var renderTarget = AvaloniaLocator.Current.GetService().CreateRenderTarget(new[] { this })) + using (var renderTarget = platformRenderInterface.CreateRenderTarget(new[] { this })) using (var ctx = renderTarget.CreateDrawingContext(null)) { var r = new Rect(_pixelSize.ToSize(1)); diff --git a/src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/StringIndexerNode.cs b/src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/StringIndexerNode.cs index 3857c9aff0..9c505486b7 100644 --- a/src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/StringIndexerNode.cs +++ b/src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/StringIndexerNode.cs @@ -45,7 +45,7 @@ namespace Avalonia.Markup.Parsers.Nodes return false; } - convertedObjectArray[i] = temp; + convertedObjectArray[i] = temp!; } var intArgs = convertedObjectArray.OfType().ToArray(); @@ -163,7 +163,7 @@ namespace Avalonia.Markup.Parsers.Nodes return AvaloniaProperty.UnsetValue; } - convertedObjectArray[i] = temp; + convertedObjectArray[i] = temp!; } var intArgs = convertedObjectArray.OfType().ToArray(); @@ -238,14 +238,14 @@ namespace Avalonia.Markup.Parsers.Nodes for (int i = 0; i < Arguments.Count; ++i) { - object value; + object? value; if (!TypeUtilities.TryConvert(typeof(int), Arguments[i], CultureInfo.InvariantCulture, out value)) { return false; } - intArgs[i] = (int)value; + intArgs[i] = (int)value!; } return true; } diff --git a/src/Markup/Avalonia.Markup/Markup/Parsers/SelectorParser.cs b/src/Markup/Avalonia.Markup/Markup/Parsers/SelectorParser.cs index 11fb287d46..0a3986ce2b 100644 --- a/src/Markup/Avalonia.Markup/Markup/Parsers/SelectorParser.cs +++ b/src/Markup/Avalonia.Markup/Markup/Parsers/SelectorParser.cs @@ -75,7 +75,7 @@ namespace Avalonia.Markup.Parsers throw new InvalidOperationException($"Cannot find '{property.Property}' on '{type}"); } - object typedValue; + object? typedValue; if (TypeUtilities.TryConvert( targetProperty.PropertyType, diff --git a/src/Shared/PlatformSupport/AssetLoader.cs b/src/Shared/PlatformSupport/AssetLoader.cs index affb861de0..95ac79ae31 100644 --- a/src/Shared/PlatformSupport/AssetLoader.cs +++ b/src/Shared/PlatformSupport/AssetLoader.cs @@ -6,6 +6,8 @@ using System.Reflection; using Avalonia.Platform; using Avalonia.Utilities; +#nullable enable + namespace Avalonia.Shared.PlatformSupport { /// @@ -94,7 +96,7 @@ namespace Avalonia.Shared.PlatformSupport return (asset.GetStream(), asset.Assembly); } - public Assembly? GetAssembly(Uri uri, Uri baseUri) + public Assembly? GetAssembly(Uri uri, Uri? baseUri) { if (!uri.IsAbsoluteUri && baseUri != null) uri = new Uri(baseUri, uri); @@ -375,7 +377,7 @@ namespace Avalonia.Shared.PlatformSupport var indexLength = new BinaryReader(resources).ReadInt32(); var index = AvaloniaResourcesIndexReaderWriter.Read(new SlicedStream(resources, 4, indexLength)); var baseOffset = indexLength + 4; - AvaloniaResources = index.ToDictionary(r => "/" + r.Path.TrimStart('/'), r => (IAssetDescriptor) + AvaloniaResources = index.ToDictionary(r => "/" + r.Path!.TrimStart('/'), r => (IAssetDescriptor) new AvaloniaResourceDescriptor(assembly, baseOffset + r.Offset, r.Size)); } } diff --git a/src/Web/Avalonia.Web.Blazor/AvaloniaView.razor.cs b/src/Web/Avalonia.Web.Blazor/AvaloniaView.razor.cs index e1f8cd5b72..bc2a2f3103 100644 --- a/src/Web/Avalonia.Web.Blazor/AvaloniaView.razor.cs +++ b/src/Web/Avalonia.Web.Blazor/AvaloniaView.razor.cs @@ -41,7 +41,7 @@ namespace Avalonia.Web.Blazor _topLevel = new EmbeddableControlRoot(_topLevelImpl); - if (Application.Current.ApplicationLifetime is ISingleViewApplicationLifetime lifetime) + if (Application.Current?.ApplicationLifetime is ISingleViewApplicationLifetime lifetime) { _topLevel.Content = lifetime.MainView; } @@ -280,7 +280,7 @@ namespace Avalonia.Web.Blazor var options = AvaloniaLocator.Current.GetService(); // bump the default resource cache limit - _context.SetResourceCacheLimit(options.MaxGpuResourceSizeBytes ?? 32 * 1024 * 1024); + _context.SetResourceCacheLimit(options?.MaxGpuResourceSizeBytes ?? 32 * 1024 * 1024); Console.WriteLine("glcontext created and resource limit set"); } diff --git a/src/Web/Avalonia.Web.Blazor/WindowingPlatform.cs b/src/Web/Avalonia.Web.Blazor/WindowingPlatform.cs index 4439ec161c..4804016ab2 100644 --- a/src/Web/Avalonia.Web.Blazor/WindowingPlatform.cs +++ b/src/Web/Avalonia.Web.Blazor/WindowingPlatform.cs @@ -58,7 +58,7 @@ namespace Avalonia.Web.Blazor public IDisposable StartTimer(DispatcherPriority priority, TimeSpan interval, Action tick) { - return AvaloniaLocator.Current.GetService() + return GetRuntimePlatform() .StartSystemTimer(interval, () => { Dispatcher.UIThread.RunJobs(priority); @@ -75,7 +75,7 @@ namespace Avalonia.Web.Blazor IDisposable? disp = null; - disp = AvaloniaLocator.Current.GetService() + disp = GetRuntimePlatform() .StartSystemTimer(TimeSpan.FromMilliseconds(1), () => { @@ -96,6 +96,10 @@ namespace Avalonia.Web.Blazor public event Action? Signaled; - + private static IRuntimePlatform GetRuntimePlatform() + { + return AvaloniaLocator.Current.GetService() ?? + throw new InvalidOperationException("Unable to locate IRuntimePlatform."); + } } } diff --git a/src/Windows/Avalonia.Win32/FramebufferManager.cs b/src/Windows/Avalonia.Win32/FramebufferManager.cs index 0240ac9701..119edcebbf 100644 --- a/src/Windows/Avalonia.Win32/FramebufferManager.cs +++ b/src/Windows/Avalonia.Win32/FramebufferManager.cs @@ -107,7 +107,9 @@ namespace Avalonia.Win32 private static FramebufferData AllocateFramebufferData(int width, int height) { - var bitmapBlob = AvaloniaLocator.Current.GetService().AllocBlob(width * height * _bytesPerPixel); + var service = AvaloniaLocator.Current.GetService() ?? + throw new InvalidOperationException("Unable to locate IRuntimePlatform."); + var bitmapBlob = service.AllocBlob(width * height * _bytesPerPixel); return new FramebufferData(bitmapBlob, width, height); }