Browse Source

Merge pull request #9189 from workgroupengineering/features/NetAnalyzers/CA1822

feat: Enable Rule CA1822
pull/9609/head
Max Katz 4 years ago
committed by GitHub
parent
commit
5d785ca99a
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 3
      .editorconfig
  2. 25
      samples/ControlCatalog/Pages/AutoCompleteBoxPage.xaml.cs
  3. 2
      samples/ControlCatalog/Pages/CompositionPage.axaml.cs
  4. 2
      samples/ControlCatalog/Pages/ImagePage.xaml.cs
  5. 2
      samples/ControlCatalog/Pages/OpenGlPage.xaml.cs
  6. 3
      samples/ControlCatalog/Pages/ScreenPage.cs
  7. 2
      samples/ControlCatalog/Pages/TabControlPage.xaml.cs
  8. 2
      src/Android/Avalonia.Android/Platform/Specific/Helpers/AndroidKeyboardEventsHelper.cs
  9. 2
      src/Android/Avalonia.Android/Platform/Storage/AndroidStorageItem.cs
  10. 2
      src/Avalonia.Base/Animation/Animators/GradientBrushAnimator.cs
  11. 2
      src/Avalonia.Base/Animation/KeySpline.cs
  12. 4
      src/Avalonia.Base/Controls/Classes.cs
  13. 2
      src/Avalonia.Base/Data/Core/ExpressionNode.cs
  14. 4
      src/Avalonia.Base/Data/Core/Parsers/ExpressionVisitorNodeBuilder.cs
  15. 2
      src/Avalonia.Base/Data/Core/Plugins/DataAnnotationsValidationPlugin.cs
  16. 2
      src/Avalonia.Base/Data/Core/Plugins/IndeiValidationPlugin.cs
  17. 2
      src/Avalonia.Base/Data/Core/Plugins/TaskStreamPlugin.cs
  18. 4
      src/Avalonia.Base/Input/DragDropDevice.cs
  19. 2
      src/Avalonia.Base/Input/KeyGesture.cs
  20. 2
      src/Avalonia.Base/Input/KeyboardDevice.cs
  21. 9
      src/Avalonia.Base/Input/MouseDevice.cs
  22. 2
      src/Avalonia.Base/Input/PenDevice.cs
  23. 4
      src/Avalonia.Base/Input/Pointer.cs
  24. 2
      src/Avalonia.Base/Input/TouchDevice.cs
  25. 2
      src/Avalonia.Base/Layout/AttachedLayout.cs
  26. 4
      src/Avalonia.Base/Layout/StackLayout.cs
  27. 2
      src/Avalonia.Base/Layout/UniformGridLayout.cs
  28. 12
      src/Avalonia.Base/Media/PathMarkupParser.cs
  29. 4
      src/Avalonia.Base/Platform/AssetLoader.cs
  30. 12
      src/Avalonia.Base/Rendering/Composition/Animations/KeyFrameAnimationInstance.cs
  31. 2
      src/Avalonia.Base/Rendering/Composition/CompositingRenderer.cs
  32. 4
      src/Avalonia.Base/Rendering/Composition/CompositionTarget.cs
  33. 2
      src/Avalonia.Base/Rendering/Composition/Drawing/CompositionDrawingContext.cs
  34. 2
      src/Avalonia.Base/Rendering/DeferredRenderer.cs
  35. 2
      src/Avalonia.Base/Rendering/SceneGraph/SceneBuilder.cs
  36. 2
      src/Avalonia.Controls.ColorPicker/ColorSlider/ColorSlider.cs
  37. 2
      src/Avalonia.Controls.ColorPicker/ColorSpectrum/ColorSpectrum.cs
  38. 2
      src/Avalonia.Controls.DataGrid/DataGridTemplateColumn.cs
  39. 2
      src/Avalonia.Controls/Automation/Peers/ComboBoxAutomationPeer.cs
  40. 2
      src/Avalonia.Controls/Calendar/CalendarBlackoutDatesCollection.cs
  41. 3
      src/Avalonia.Controls/Calendar/SelectedDatesCollection.cs
  42. 8
      src/Avalonia.Controls/Grid.cs
  43. 2
      src/Avalonia.Controls/GridSplitter.cs
  44. 4
      src/Avalonia.Controls/Platform/InProcessDragSource.cs
  45. 6
      src/Avalonia.Controls/Primitives/Popup.cs
  46. 2
      src/Avalonia.Controls/Repeater/RecyclingElementFactory.cs
  47. 7
      src/Avalonia.Controls/SplitView.cs
  48. 2
      src/Avalonia.Controls/TextBox.cs
  49. 2
      src/Avalonia.Controls/TopLevel.cs
  50. 1
      src/Avalonia.Controls/UserControl.cs
  51. 2
      src/Avalonia.Diagnostics/Diagnostics/Screenshots/FilePickerHandler.cs
  52. 14
      src/Avalonia.Diagnostics/Diagnostics/ViewModels/ControlDetailsViewModel.cs
  53. 8
      src/Avalonia.Dialogs/ManagedStorageProvider.cs
  54. 8
      src/Avalonia.FreeDesktop/LinuxMountedVolumeInfoListener.cs
  55. 2
      src/Avalonia.Native/AvaloniaNativeMenuExporter.cs
  56. 3
      src/Avalonia.Native/IAvnMenu.cs
  57. 4
      src/Avalonia.OpenGL/Controls/OpenGlControlBase.cs
  58. 2
      src/Avalonia.X11/X11IconLoader.cs
  59. 9
      src/Avalonia.X11/X11Platform.cs
  60. 1
      src/Avalonia.X11/X11Window.Ime.cs
  61. 4
      src/Avalonia.X11/X11Window.cs
  62. 8
      src/Markup/Avalonia.Markup.Xaml.Loader/CompilerExtensions/XamlIlAvaloniaPropertyHelper.cs
  63. 8
      src/Markup/Avalonia.Markup.Xaml/Converters/AvaloniaPropertyTypeConverter.cs
  64. 2
      src/Markup/Avalonia.Markup.Xaml/Converters/IconTypeConverter.cs
  65. 2
      src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/DynamicResourceExtension.cs
  66. 6
      src/Markup/Avalonia.Markup.Xaml/Parsers/PropertyParser.cs
  67. 6
      src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/StringIndexerNode.cs
  68. 4
      src/Skia/Avalonia.Skia/DrawingContextImpl.cs
  69. 7
      src/Windows/Avalonia.Win32.Interop/Wpf/Direct2DImageSurface.cs
  70. 3
      src/Windows/Avalonia.Win32.Interop/Wpf/WpfTopLevelImpl.cs
  71. 2
      src/Windows/Avalonia.Win32/ClipboardImpl.cs
  72. 2
      src/Windows/Avalonia.Win32/CursorFactory.cs
  73. 8
      src/Windows/Avalonia.Win32/DataObject.cs
  74. 6
      src/Windows/Avalonia.Win32/PopupImpl.cs
  75. 32
      src/Windows/Avalonia.Win32/Win32Platform.cs
  76. 4
      src/Windows/Avalonia.Win32/WindowImpl.AppWndProc.cs
  77. 4
      src/Windows/Avalonia.Win32/WindowImpl.CustomCaptionProc.cs
  78. 7
      src/Windows/Avalonia.Win32/WindowImpl.cs
  79. 2
      src/iOS/Avalonia.iOS/CombinedSpan3.cs
  80. 2
      src/iOS/Avalonia.iOS/TouchHandler.cs
  81. 4
      src/tools/DevGenerators/CompositionGenerator/Generator.ListProxy.cs
  82. 13
      src/tools/DevGenerators/CompositionGenerator/Generator.Utils.cs
  83. 56
      src/tools/DevGenerators/CompositionGenerator/Generator.cs
  84. 2
      tests/Avalonia.Base.UnitTests/Data/Core/ExpressionObserverTests_Lifetime.cs
  85. 2
      tests/Avalonia.Base.UnitTests/Data/Core/ExpressionObserverTests_Property.cs
  86. 2
      tests/Avalonia.Base.UnitTests/Data/Core/ExpressionObserverTests_Task.cs
  87. 2
      tests/Avalonia.Base.UnitTests/Input/GesturesTests.cs
  88. 2
      tests/Avalonia.Base.UnitTests/Interactivity/InteractiveTests.cs
  89. 12
      tests/Avalonia.Base.UnitTests/Layout/LayoutableTests_EffectiveViewportChanged.cs
  90. 2
      tests/Avalonia.Base.UnitTests/Layout/NonVirtualizingStackLayoutTests.cs
  91. 4
      tests/Avalonia.Base.UnitTests/MatrixTests.cs
  92. 2
      tests/Avalonia.Base.UnitTests/Media/RectangleGeometryTests.cs
  93. 2
      tests/Avalonia.Base.UnitTests/Rendering/CompositorHitTestingTests.cs
  94. 2
      tests/Avalonia.Base.UnitTests/Rendering/DeferredRendererTests_HitTesting.cs
  95. 2
      tests/Avalonia.Base.UnitTests/Rendering/ImmediateRendererTests_HitTesting.cs
  96. 2
      tests/Avalonia.Base.UnitTests/Styling/StyledElementTests_Resources.cs
  97. 2
      tests/Avalonia.Base.UnitTests/VisualTree/VisualExtensions_GetVisualsAt.cs
  98. 2
      tests/Avalonia.Base.UnitTests/WeakEventHandlerManagerTests.cs
  99. 2
      tests/Avalonia.Base.UnitTests/WeakEventTests.cs
  100. 2
      tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs

3
.editorconfig

@ -143,6 +143,9 @@ dotnet_diagnostic.CA1802.severity = warning
dotnet_diagnostic.CA1820.severity = warning dotnet_diagnostic.CA1820.severity = warning
# CA1821: Remove empty finalizers # CA1821: Remove empty finalizers
dotnet_diagnostic.CA1821.severity = warning dotnet_diagnostic.CA1821.severity = warning
# CA1822: Mark members as static
dotnet_diagnostic.CA1822.severity = suggestion
dotnet_code_quality.CA1822.api_surface = private, internal
# CA1825: Avoid zero-length array allocations # CA1825: Avoid zero-length array allocations
dotnet_diagnostic.CA1825.severity = warning dotnet_diagnostic.CA1825.severity = warning
# CA1826: Use property instead of Linq Enumerable method # CA1826: Use property instead of Linq Enumerable method

25
samples/ControlCatalog/Pages/AutoCompleteBoxPage.xaml.cs

@ -14,7 +14,26 @@ namespace ControlCatalog.Pages
{ {
public class AutoCompleteBoxPage : UserControl public class AutoCompleteBoxPage : UserControl
{ {
private StateData[] BuildAllStates() public class StateData
{
public string Name { get; private set; }
public string Abbreviation { get; private set; }
public string Capital { get; private set; }
public StateData(string name, string abbreviatoin, string capital)
{
Name = name;
Abbreviation = abbreviatoin;
Capital = capital;
}
public override string ToString()
{
return Name;
}
}
private static StateData[] BuildAllStates()
{ {
return new StateData[] return new StateData[]
{ {
@ -72,7 +91,7 @@ namespace ControlCatalog.Pages
} }
public StateData[] States { get; private set; } public StateData[] States { get; private set; }
private LinkedList<string>[] BuildAllSentences() private static LinkedList<string>[] BuildAllSentences()
{ {
return new string[] return new string[]
{ {
@ -124,7 +143,7 @@ namespace ControlCatalog.Pages
.OfType<AutoCompleteBox>(); .OfType<AutoCompleteBox>();
} }
private bool StringContains(string str, string? query) private static bool StringContains(string str, string? query)
{ {
if (query == null) return false; if (query == null) return false;
return str.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0; return str.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0;

2
samples/ControlCatalog/Pages/CompositionPage.axaml.cs

@ -25,7 +25,7 @@ public partial class CompositionPage : UserControl
this.Get<ItemsControl>("Items").Items = CreateColorItems(); this.Get<ItemsControl>("Items").Items = CreateColorItems();
} }
private List<CompositionPageColorItem> CreateColorItems() private static List<CompositionPageColorItem> CreateColorItems()
{ {
var list = new List<CompositionPageColorItem>(); var list = new List<CompositionPageColorItem>();

2
samples/ControlCatalog/Pages/ImagePage.xaml.cs

@ -58,7 +58,7 @@ namespace ControlCatalog.Pages
} }
} }
private PixelRect GetCropRect(int index) private static PixelRect GetCropRect(int index)
{ {
var bitmapWidth = 640; var bitmapWidth = 640;
var bitmapHeight = 426; var bitmapHeight = 426;

2
samples/ControlCatalog/Pages/OpenGlPage.xaml.cs

@ -247,7 +247,7 @@ namespace ControlCatalog.Pages
} }
private void CheckError(GlInterface gl) private static void CheckError(GlInterface gl)
{ {
int err; int err;
while ((err = gl.GetError()) != GL_NO_ERROR) while ((err = gl.GetError()) != GL_NO_ERROR)

3
samples/ControlCatalog/Pages/ScreenPage.cs

@ -66,6 +66,7 @@ namespace ControlCatalog.Pages
context.DrawText(formattedText, boundsRect.Position.WithY(boundsRect.Size.Height + 40)); context.DrawText(formattedText, boundsRect.Position.WithY(boundsRect.Size.Height + 40));
formattedText = CreateFormattedText($"IsPrimary: {screen.IsPrimary}"); formattedText = CreateFormattedText($"IsPrimary: {screen.IsPrimary}");
context.DrawText(formattedText, boundsRect.Position.WithY(boundsRect.Size.Height + 60)); context.DrawText(formattedText, boundsRect.Position.WithY(boundsRect.Size.Height + 60));
formattedText = formattedText =
@ -77,7 +78,7 @@ namespace ControlCatalog.Pages
context.DrawRectangle(p, new Rect(w.Position.X / 10f + Math.Abs(_leftMost), w.Position.Y / 10f, w.Bounds.Width / 10, w.Bounds.Height / 10)); context.DrawRectangle(p, new Rect(w.Position.X / 10f + Math.Abs(_leftMost), w.Position.Y / 10f, w.Bounds.Width / 10, w.Bounds.Height / 10));
} }
private FormattedText CreateFormattedText(string textToFormat) private static FormattedText CreateFormattedText(string textToFormat)
{ {
return new FormattedText(textToFormat, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, return new FormattedText(textToFormat, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
Typeface.Default, 12, Brushes.Green); Typeface.Default, 12, Brushes.Green);

2
samples/ControlCatalog/Pages/TabControlPage.xaml.cs

@ -49,7 +49,7 @@ namespace ControlCatalog.Pages
AvaloniaXamlLoader.Load(this); AvaloniaXamlLoader.Load(this);
} }
private IBitmap LoadBitmap(string uri) private static IBitmap LoadBitmap(string uri)
{ {
var assets = AvaloniaLocator.Current!.GetService<IAssetLoader>()!; var assets = AvaloniaLocator.Current!.GetService<IAssetLoader>()!;
return new Bitmap(assets.Open(new Uri(uri))); return new Bitmap(assets.Open(new Uri(uri)));

2
src/Android/Avalonia.Android/Platform/Specific/Helpers/AndroidKeyboardEventsHelper.cs

@ -30,7 +30,7 @@ namespace Avalonia.Android.Platform.Specific.Helpers
return DispatchKeyEventInternal(e, out callBase); return DispatchKeyEventInternal(e, out callBase);
} }
string UnicodeTextInput(KeyEvent keyEvent) static string UnicodeTextInput(KeyEvent keyEvent)
{ {
return keyEvent.Action == KeyEventActions.Multiple return keyEvent.Action == KeyEventActions.Multiple
&& keyEvent.RepeatCount == 0 && keyEvent.RepeatCount == 0

2
src/Android/Avalonia.Android/Platform/Storage/AndroidStorageItem.cs

@ -178,7 +178,7 @@ internal sealed class AndroidStorageFile : AndroidStorageItem, IStorageBookmarkF
return false; return false;
} }
private Stream? GetVirtualFileStream(Context context, AndroidUri uri, bool isOutput) private static Stream? GetVirtualFileStream(Context context, AndroidUri uri, bool isOutput)
{ {
var mimeTypes = context.ContentResolver?.GetStreamTypes(uri, FilePickerFileTypes.All.MimeTypes![0]); var mimeTypes = context.ContentResolver?.GetStreamTypes(uri, FilePickerFileTypes.All.MimeTypes![0]);
if (mimeTypes?.Length >= 1) if (mimeTypes?.Length >= 1)

2
src/Avalonia.Base/Animation/Animators/GradientBrushAnimator.cs

@ -72,7 +72,7 @@ namespace Avalonia.Animation.Animators
return control.Bind((AvaloniaProperty<IBrush?>)Property, instance, BindingPriority.Animation); return control.Bind((AvaloniaProperty<IBrush?>)Property, instance, BindingPriority.Animation);
} }
private IReadOnlyList<ImmutableGradientStop> InterpolateStops(double progress, IReadOnlyList<IGradientStop> oldValue, IReadOnlyList<IGradientStop> newValue) private static IReadOnlyList<ImmutableGradientStop> InterpolateStops(double progress, IReadOnlyList<IGradientStop> oldValue, IReadOnlyList<IGradientStop> newValue)
{ {
var resultCount = Math.Max(oldValue.Count, newValue.Count); var resultCount = Math.Max(oldValue.Count, newValue.Count);
var stops = new ImmutableGradientStop[resultCount]; var stops = new ImmutableGradientStop[resultCount];

2
src/Avalonia.Base/Animation/KeySpline.cs

@ -196,7 +196,7 @@ namespace Avalonia.Animation
/// </summary> /// </summary>
/// <param name="value"></param> /// <param name="value"></param>
/// <returns></returns> /// <returns></returns>
private bool IsValidXValue(double value) private static bool IsValidXValue(double value)
{ {
return value >= 0.0 && value <= 1.0; return value >= 0.0 && value <= 1.0;
} }

4
src/Avalonia.Base/Controls/Classes.cs

@ -37,7 +37,7 @@ namespace Avalonia.Controls
/// <param name="items">The initial items.</param> /// <param name="items">The initial items.</param>
public Classes(params string[] items) public Classes(params string[] items)
: base(items) : base(items)
{ {
} }
/// <summary> /// <summary>
@ -320,7 +320,7 @@ namespace Avalonia.Controls
listener.Changed(); listener.Changed();
} }
private void ThrowIfPseudoclass(string name, string operation) private static void ThrowIfPseudoclass(string name, string operation)
{ {
if (name.StartsWith(":")) if (name.StartsWith(":"))
{ {

2
src/Avalonia.Base/Data/Core/ExpressionNode.cs

@ -159,7 +159,7 @@ namespace Avalonia.Data.Core
_listening = false; _listening = false;
} }
private BindingNotification TargetNullNotification() private static BindingNotification TargetNullNotification()
{ {
return new BindingNotification( return new BindingNotification(
new MarkupBindingChainException("Null value"), new MarkupBindingChainException("Null value"),

4
src/Avalonia.Base/Data/Core/Parsers/ExpressionVisitorNodeBuilder.cs

@ -81,7 +81,7 @@ namespace Avalonia.Data.Core.Parsers
return node; return node;
} }
private T GetArgumentExpressionValue<T>(Expression expr) private static T GetArgumentExpressionValue<T>(Expression expr)
{ {
try try
{ {
@ -193,7 +193,7 @@ namespace Avalonia.Data.Core.Parsers
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 static PropertyInfo? TryGetPropertyFromMethod(MethodInfo method)
{ {
var type = method.DeclaringType; var type = method.DeclaringType;
return type?.GetRuntimeProperties().FirstOrDefault(prop => prop.GetMethod == method); return type?.GetRuntimeProperties().FirstOrDefault(prop => prop.GetMethod == method);

2
src/Avalonia.Base/Data/Core/Plugins/DataAnnotationsValidationPlugin.cs

@ -63,7 +63,7 @@ namespace Avalonia.Data.Core.Plugins
} }
} }
private Exception CreateException(IList<ValidationResult> errors) private static Exception CreateException(IList<ValidationResult> errors)
{ {
if (errors.Count == 1) if (errors.Count == 1)
{ {

2
src/Avalonia.Base/Data/Core/Plugins/IndeiValidationPlugin.cs

@ -108,7 +108,7 @@ namespace Avalonia.Data.Core.Plugins
return target; return target;
} }
private Exception GenerateException(IList<object> errors) private static Exception GenerateException(IList<object> errors)
{ {
if (errors.Count == 1) if (errors.Count == 1)
{ {

2
src/Avalonia.Base/Data/Core/Plugins/TaskStreamPlugin.cs

@ -59,7 +59,7 @@ namespace Avalonia.Data.Core.Plugins
return Observable.Empty<object?>(); return Observable.Empty<object?>();
} }
private IObservable<object?> HandleCompleted(Task task) private static IObservable<object?> HandleCompleted(Task task)
{ {
var resultProperty = task.GetType().GetRuntimeProperty("Result"); var resultProperty = task.GetType().GetRuntimeProperty("Result");

4
src/Avalonia.Base/Input/DragDropDevice.cs

@ -11,7 +11,7 @@ namespace Avalonia.Input
private Interactive? _lastTarget = null; private Interactive? _lastTarget = null;
private Interactive? GetTarget(IInputRoot root, Point local) private static Interactive? GetTarget(IInputRoot root, Point local)
{ {
var hit = root.InputHitTest(local) as Visual; var hit = root.InputHitTest(local) as Visual;
var target = hit?.GetSelfAndVisualAncestors()?.OfType<Interactive>()?.FirstOrDefault(); var target = hit?.GetSelfAndVisualAncestors()?.OfType<Interactive>()?.FirstOrDefault();
@ -20,7 +20,7 @@ namespace Avalonia.Input
return null; return null;
} }
private DragDropEffects RaiseDragEvent(Interactive? target, IInputRoot inputRoot, Point point, RoutedEvent<DragEventArgs> routedEvent, DragDropEffects operation, IDataObject data, KeyModifiers modifiers) private static DragDropEffects RaiseDragEvent(Interactive? target, IInputRoot inputRoot, Point point, RoutedEvent<DragEventArgs> routedEvent, DragDropEffects operation, IDataObject data, KeyModifiers modifiers)
{ {
if (target == null) if (target == null)
return DragDropEffects.None; return DragDropEffects.None;

2
src/Avalonia.Base/Input/KeyGesture.cs

@ -166,7 +166,7 @@ namespace Avalonia.Input
return EnumHelper.Parse<KeyModifiers>(modifier.ToString(), true); return EnumHelper.Parse<KeyModifiers>(modifier.ToString(), true);
} }
private Key ResolveNumPadOperationKey(Key key) private static Key ResolveNumPadOperationKey(Key key)
{ {
switch (key) switch (key)
{ {

2
src/Avalonia.Base/Input/KeyboardDevice.cs

@ -25,7 +25,7 @@ namespace Avalonia.Input
public IInputElement? FocusedElement => _focusedElement; public IInputElement? FocusedElement => _focusedElement;
private void ClearFocusWithinAncestors(IInputElement? element) private static void ClearFocusWithinAncestors(IInputElement? element)
{ {
var el = element; var el = element;

9
src/Avalonia.Base/Input/MouseDevice.cs

@ -1,12 +1,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Input.Raw; using Avalonia.Input.Raw;
using Avalonia.Interactivity;
using Avalonia.Platform; using Avalonia.Platform;
using Avalonia.Utilities; using Avalonia.Utilities;
using Avalonia.VisualTree;
namespace Avalonia.Input namespace Avalonia.Input
{ {
@ -34,7 +30,7 @@ namespace Avalonia.Input
ProcessRawEvent(margs); ProcessRawEvent(margs);
} }
int ButtonCount(PointerPointProperties props) static int ButtonCount(PointerPointProperties props)
{ {
var rv = 0; var rv = 0;
if (props.IsLeftButtonPressed) if (props.IsLeftButtonPressed)
@ -106,9 +102,10 @@ namespace Avalonia.Input
private void LeaveWindow() private void LeaveWindow()
{ {
} }
PointerPointProperties CreateProperties(RawPointerEventArgs args) static PointerPointProperties CreateProperties(RawPointerEventArgs args)
{ {
return new PointerPointProperties(args.InputModifiers, args.Type.ToUpdateKind()); return new PointerPointProperties(args.InputModifiers, args.Type.ToUpdateKind());
} }

2
src/Avalonia.Base/Input/PenDevice.cs

@ -99,7 +99,7 @@ namespace Avalonia.Input
return false; return false;
} }
private bool PenMove(Pointer pointer, ulong timestamp, private static bool PenMove(Pointer pointer, ulong timestamp,
IInputRoot root, Point p, PointerPointProperties properties, IInputRoot root, Point p, PointerPointProperties properties,
KeyModifiers inputModifiers, IInputElement? hitTest, KeyModifiers inputModifiers, IInputElement? hitTest,
Lazy<IReadOnlyList<RawPointerPoint>?>? intermediatePoints) Lazy<IReadOnlyList<RawPointerPoint>?>? intermediatePoints)

4
src/Avalonia.Base/Input/Pointer.cs

@ -19,7 +19,7 @@ namespace Avalonia.Input
public int Id { get; } public int Id { get; }
IInputElement? FindCommonParent(IInputElement? control1, IInputElement? control2) static IInputElement? FindCommonParent(IInputElement? control1, IInputElement? control2)
{ {
if (control1 is not Visual c1 || control2 is not Visual c2) if (control1 is not Visual c1 || control2 is not Visual c2)
return null; return null;
@ -54,7 +54,7 @@ namespace Avalonia.Input
v3.DetachedFromVisualTree += OnCaptureDetached; v3.DetachedFromVisualTree += OnCaptureDetached;
} }
IInputElement? GetNextCapture(Visual parent) static IInputElement? GetNextCapture(Visual parent)
{ {
return parent as IInputElement ?? parent.FindAncestorOfType<IInputElement>(); return parent as IInputElement ?? parent.FindAncestorOfType<IInputElement>();
} }

2
src/Avalonia.Base/Input/TouchDevice.cs

@ -21,7 +21,7 @@ namespace Avalonia.Input
private Rect _lastClickRect; private Rect _lastClickRect;
private ulong _lastClickTime; private ulong _lastClickTime;
RawInputModifiers GetModifiers(RawInputModifiers modifiers, bool isLeftButtonDown) static RawInputModifiers GetModifiers(RawInputModifiers modifiers, bool isLeftButtonDown)
{ {
var rv = modifiers &= RawInputModifiers.KeyboardMask; var rv = modifiers &= RawInputModifiers.KeyboardMask;
if (isLeftButtonDown) if (isLeftButtonDown)

2
src/Avalonia.Base/Layout/AttachedLayout.cs

@ -184,7 +184,7 @@ namespace Avalonia.Layout
/// </summary> /// </summary>
protected void InvalidateArrange() => ArrangeInvalidated?.Invoke(this, EventArgs.Empty); protected void InvalidateArrange() => ArrangeInvalidated?.Invoke(this, EventArgs.Empty);
private VirtualizingLayoutContext GetVirtualizingLayoutContext(LayoutContext context) private static VirtualizingLayoutContext GetVirtualizingLayoutContext(LayoutContext context)
{ {
if (context is VirtualizingLayoutContext virtualizingContext) if (context is VirtualizingLayoutContext virtualizingContext)
{ {

4
src/Avalonia.Base/Layout/StackLayout.cs

@ -335,7 +335,7 @@ namespace Avalonia.Layout
InvalidateLayout(); InvalidateLayout();
} }
private double GetAverageElementSize( private static double GetAverageElementSize(
Size availableSize, Size availableSize,
VirtualizingLayoutContext context, VirtualizingLayoutContext context,
StackLayoutState stackLayoutState) StackLayoutState stackLayoutState)
@ -359,6 +359,6 @@ namespace Avalonia.Layout
private void InvalidateLayout() => InvalidateMeasure(); private void InvalidateLayout() => InvalidateMeasure();
private FlowLayoutAlgorithm GetFlowAlgorithm(VirtualizingLayoutContext context) => ((StackLayoutState)context.LayoutState!).FlowAlgorithm; private static FlowLayoutAlgorithm GetFlowAlgorithm(VirtualizingLayoutContext context) => ((StackLayoutState)context.LayoutState!).FlowAlgorithm;
} }
} }

2
src/Avalonia.Base/Layout/UniformGridLayout.cs

@ -557,6 +557,6 @@ namespace Avalonia.Layout
private void InvalidateLayout() => InvalidateMeasure(); private void InvalidateLayout() => InvalidateMeasure();
private FlowLayoutAlgorithm GetFlowAlgorithm(VirtualizingLayoutContext context) => ((UniformGridLayoutState)context.LayoutState!).FlowAlgorithm; private static FlowLayoutAlgorithm GetFlowAlgorithm(VirtualizingLayoutContext context) => ((UniformGridLayoutState)context.LayoutState!).FlowAlgorithm;
} }
} }

12
src/Avalonia.Base/Media/PathMarkupParser.cs

@ -527,7 +527,7 @@ namespace Avalonia.Media
return span.Slice(i); return span.Slice(i);
} }
private bool ReadBool(ref ReadOnlySpan<char> span) private static bool ReadBool(ref ReadOnlySpan<char> span)
{ {
span = SkipWhitespace(span); span = SkipWhitespace(span);
@ -551,7 +551,7 @@ namespace Avalonia.Media
} }
} }
private double ReadDouble(ref ReadOnlySpan<char> span) private static double ReadDouble(ref ReadOnlySpan<char> span)
{ {
if (!ReadArgument(ref span, out var doubleValue)) if (!ReadArgument(ref span, out var doubleValue))
{ {
@ -561,7 +561,7 @@ namespace Avalonia.Media
return double.Parse(doubleValue.ToString(), CultureInfo.InvariantCulture); return double.Parse(doubleValue.ToString(), CultureInfo.InvariantCulture);
} }
private Size ReadSize(ref ReadOnlySpan<char> span) private static Size ReadSize(ref ReadOnlySpan<char> span)
{ {
var width = ReadDouble(ref span); var width = ReadDouble(ref span);
span = ReadSeparator(span); span = ReadSeparator(span);
@ -569,7 +569,7 @@ namespace Avalonia.Media
return new Size(width, height); return new Size(width, height);
} }
private Point ReadPoint(ref ReadOnlySpan<char> span) private static Point ReadPoint(ref ReadOnlySpan<char> span)
{ {
var x = ReadDouble(ref span); var x = ReadDouble(ref span);
span = ReadSeparator(span); span = ReadSeparator(span);
@ -577,7 +577,7 @@ namespace Avalonia.Media
return new Point(x, y); return new Point(x, y);
} }
private Point ReadRelativePoint(ref ReadOnlySpan<char> span, Point origin) private static Point ReadRelativePoint(ref ReadOnlySpan<char> span, Point origin)
{ {
var x = ReadDouble(ref span); var x = ReadDouble(ref span);
span = ReadSeparator(span); span = ReadSeparator(span);
@ -585,7 +585,7 @@ namespace Avalonia.Media
return new Point(origin.X + x, origin.Y + y); return new Point(origin.X + x, origin.Y + y);
} }
private bool ReadCommand(ref ReadOnlySpan<char> span, out Command command, out bool relative) private static bool ReadCommand(ref ReadOnlySpan<char> span, out Command command, out bool relative)
{ {
span = SkipWhitespace(span); span = SkipWhitespace(span);
if (span.IsEmpty) if (span.IsEmpty)

4
src/Avalonia.Base/Platform/AssetLoader.cs

@ -187,13 +187,13 @@ namespace Avalonia.Platform
throw new ArgumentException($"Unsupported url type: " + uri.Scheme, nameof(uri)); throw new ArgumentException($"Unsupported url type: " + uri.Scheme, nameof(uri));
} }
private (IAssemblyDescriptor asm, string path) GetResAsmAndPath(Uri uri) private static (IAssemblyDescriptor asm, string path) GetResAsmAndPath(Uri uri)
{ {
var asm = s_assemblyDescriptorResolver.GetAssembly(uri.Authority); var asm = s_assemblyDescriptorResolver.GetAssembly(uri.Authority);
return (asm, uri.GetUnescapeAbsolutePath()); return (asm, uri.GetUnescapeAbsolutePath());
} }
private IAssemblyDescriptor? GetAssembly(Uri? uri) private static IAssemblyDescriptor? GetAssembly(Uri? uri)
{ {
if (uri != null) if (uri != null)
{ {

12
src/Avalonia.Base/Rendering/Composition/Animations/KeyFrameAnimationInstance.cs

@ -87,7 +87,7 @@ namespace Avalonia.Rendering.Composition.Animations
if (elapsed < _delayTime) if (elapsed < _delayTime)
{ {
if (_delayBehavior == AnimationDelayBehavior.SetInitialValueBeforeDelay) if (_delayBehavior == AnimationDelayBehavior.SetInitialValueBeforeDelay)
return ExpressionVariant.Create(GetKeyFrame(ref ctx, _keyFrames[0])); return ExpressionVariant.Create(KeyFrameAnimationInstance<T>.GetKeyFrame(ref ctx, _keyFrames[0]));
return currentValue; return currentValue;
} }
@ -95,7 +95,7 @@ namespace Avalonia.Rendering.Composition.Animations
var iterationNumber = elapsed.Ticks / _duration.Ticks; var iterationNumber = elapsed.Ticks / _duration.Ticks;
if (_iterationBehavior == AnimationIterationBehavior.Count if (_iterationBehavior == AnimationIterationBehavior.Count
&& iterationNumber >= _iterationCount) && iterationNumber >= _iterationCount)
return ExpressionVariant.Create(GetKeyFrame(ref ctx, _keyFrames[_keyFrames.Length - 1])); return ExpressionVariant.Create(KeyFrameAnimationInstance<T>.GetKeyFrame(ref ctx, _keyFrames[_keyFrames.Length - 1]));
var evenIterationNumber = iterationNumber % 2 == 0; var evenIterationNumber = iterationNumber % 2 == 0;
@ -124,7 +124,7 @@ namespace Avalonia.Rendering.Composition.Animations
{ {
// this is the last frame // this is the last frame
if (c == _keyFrames.Length - 1) if (c == _keyFrames.Length - 1)
return ExpressionVariant.Create(GetKeyFrame(ref ctx, kf)); return ExpressionVariant.Create(KeyFrameAnimationInstance<T>.GetKeyFrame(ref ctx, kf));
left = kf; left = kf;
right = _keyFrames[c + 1]; right = _keyFrames[c + 1];
@ -147,13 +147,13 @@ namespace Avalonia.Rendering.Composition.Animations
return currentValue; return currentValue;
return ExpressionVariant.Create(_interpolator.Interpolate( return ExpressionVariant.Create(_interpolator.Interpolate(
GetKeyFrame(ref ctx, left), KeyFrameAnimationInstance<T>.GetKeyFrame(ref ctx, left),
GetKeyFrame(ref ctx, right), KeyFrameAnimationInstance<T>.GetKeyFrame(ref ctx, right),
easedKeyProgress easedKeyProgress
)); ));
} }
T GetKeyFrame(ref ExpressionEvaluationContext ctx, ServerKeyFrame<T> f) static T GetKeyFrame(ref ExpressionEvaluationContext ctx, ServerKeyFrame<T> f)
{ {
if (f.Expression != null) if (f.Expression != null)
return f.Expression.Evaluate(ref ctx).CastOrDefault<T>(); return f.Expression.Evaluate(ref ctx).CastOrDefault<T>();

2
src/Avalonia.Base/Rendering/Composition/CompositingRenderer.cs

@ -124,7 +124,7 @@ public class CompositingRenderer : IRendererWithCompositor
QueueUpdate(); QueueUpdate();
} }
private void SyncChildren(Visual v) private static void SyncChildren(Visual v)
{ {
//TODO: Optimize by moving that logic to Visual itself //TODO: Optimize by moving that logic to Visual itself
if(v.CompositionVisual == null) if(v.CompositionVisual == null)

4
src/Avalonia.Base/Rendering/Composition/CompositionTarget.cs

@ -62,7 +62,7 @@ namespace Avalonia.Rendering.Composition
return point * m; return point * m;
} }
bool TryGetInvertedTransform(CompositionVisual visual, out Matrix matrix) static bool TryGetInvertedTransform(CompositionVisual visual, out Matrix matrix)
{ {
var m = visual.TryGetServerGlobalTransform(); var m = visual.TryGetServerGlobalTransform();
if (m == null) if (m == null)
@ -75,7 +75,7 @@ namespace Avalonia.Rendering.Composition
return m33.TryInvert(out matrix); return m33.TryInvert(out matrix);
} }
bool TryTransformTo(CompositionVisual visual, Point globalPoint, out Point v) static bool TryTransformTo(CompositionVisual visual, Point globalPoint, out Point v)
{ {
v = default; v = default;
if (TryGetInvertedTransform(visual, out var m)) if (TryGetInvertedTransform(visual, out var m))

2
src/Avalonia.Base/Rendering/Composition/Drawing/CompositionDrawingContext.cs

@ -368,7 +368,7 @@ internal class CompositionDrawingContext : IDrawingContextImpl, IDrawingContextW
: null; : null;
} }
private IDisposable? CreateChildScene(IBrush? brush) private static IDisposable? CreateChildScene(IBrush? brush)
{ {
if (brush is VisualBrush visualBrush) if (brush is VisualBrush visualBrush)
{ {

2
src/Avalonia.Base/Rendering/DeferredRenderer.cs

@ -272,7 +272,7 @@ namespace Avalonia.Rendering
} }
} }
Scene? TryGetChildScene(IRef<IDrawOperation>? op) => (op?.Item as BrushDrawOperation)?.Aux as Scene; static Scene? TryGetChildScene(IRef<IDrawOperation>? op) => (op?.Item as BrushDrawOperation)?.Aux as Scene;
/// <inheritdoc/> /// <inheritdoc/>
Size IVisualBrushRenderer.GetRenderTargetSize(IVisualBrush brush) Size IVisualBrushRenderer.GetRenderTargetSize(IVisualBrush brush)

2
src/Avalonia.Base/Rendering/SceneGraph/SceneBuilder.cs

@ -318,7 +318,7 @@ namespace Avalonia.Rendering.SceneGraph
} }
} }
private void UpdateSize(Scene scene) private static void UpdateSize(Scene scene)
{ {
var renderRoot = scene.Root.Visual as IRenderRoot; var renderRoot = scene.Root.Visual as IRenderRoot;
var newSize = renderRoot?.ClientSize ?? scene.Root.Visual.Bounds.Size; var newSize = renderRoot?.ClientSize ?? scene.Root.Visual.Bounds.Size;

2
src/Avalonia.Controls.ColorPicker/ColorSlider/ColorSlider.cs

@ -154,7 +154,7 @@ namespace Avalonia.Controls.Primitives
/// </summary> /// </summary>
/// <param name="hsvColor">The <see cref="HsvColor"/> to round component values for.</param> /// <param name="hsvColor">The <see cref="HsvColor"/> to round component values for.</param>
/// <returns>A new <see cref="HsvColor"/> with rounded component values.</returns> /// <returns>A new <see cref="HsvColor"/> with rounded component values.</returns>
private HsvColor RoundComponentValues(HsvColor hsvColor) private static HsvColor RoundComponentValues(HsvColor hsvColor)
{ {
return new HsvColor( return new HsvColor(
Math.Round(hsvColor.A, 2, MidpointRounding.AwayFromZero), Math.Round(hsvColor.A, 2, MidpointRounding.AwayFromZero),

2
src/Avalonia.Controls.ColorPicker/ColorSpectrum/ColorSpectrum.cs

@ -1146,7 +1146,7 @@ namespace Avalonia.Controls.Primitives
}); });
} }
private void FillPixelForBox( private static void FillPixelForBox(
double x, double x,
double y, double y,
Hsv baseHsv, Hsv baseHsv,

2
src/Avalonia.Controls.DataGrid/DataGridTemplateColumn.cs

@ -56,7 +56,7 @@ namespace Avalonia.Controls
set => SetAndRaise(CellEditingTemplateProperty, ref _cellEditingCellTemplate, value); set => SetAndRaise(CellEditingTemplateProperty, ref _cellEditingCellTemplate, value);
} }
private void OnCellTemplateChanged(AvaloniaPropertyChangedEventArgs e) private static void OnCellTemplateChanged(AvaloniaPropertyChangedEventArgs e)
{ {
var oldValue = (IDataTemplate)e.OldValue; var oldValue = (IDataTemplate)e.OldValue;
var value = (IDataTemplate)e.NewValue; var value = (IDataTemplate)e.NewValue;

2
src/Avalonia.Controls/Automation/Peers/ComboBoxAutomationPeer.cs

@ -71,7 +71,7 @@ namespace Avalonia.Automation.Peers
} }
} }
private ExpandCollapseState ToState(bool value) private static ExpandCollapseState ToState(bool value)
{ {
return value ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed; return value ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed;
} }

2
src/Avalonia.Controls/Calendar/CalendarBlackoutDatesCollection.cs

@ -206,7 +206,7 @@ namespace Avalonia.Controls.Primitives
return true; return true;
} }
private void EnsureValidThread() private static void EnsureValidThread()
{ {
Dispatcher.UIThread.VerifyAccess(); Dispatcher.UIThread.VerifyAccess();
} }

3
src/Avalonia.Controls/Calendar/SelectedDatesCollection.cs

@ -6,7 +6,6 @@
using Avalonia.Threading; using Avalonia.Threading;
using System; using System;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Threading;
namespace Avalonia.Controls.Primitives namespace Avalonia.Controls.Primitives
{ {
@ -353,7 +352,7 @@ namespace Avalonia.Controls.Primitives
return true; return true;
} }
private void EnsureValidThread() private static void EnsureValidThread()
{ {
Dispatcher.UIThread.VerifyAccess(); Dispatcher.UIThread.VerifyAccess();
} }

8
src/Avalonia.Controls/Grid.cs

@ -1165,7 +1165,7 @@ namespace Avalonia.Controls
/// <remarks> /// <remarks>
/// For "Auto" definitions MinWidth is used in place of PreferredSize. /// For "Auto" definitions MinWidth is used in place of PreferredSize.
/// </remarks> /// </remarks>
private double GetMeasureSizeForRange( private static double GetMeasureSizeForRange(
IReadOnlyList<DefinitionBase> definitions, IReadOnlyList<DefinitionBase> definitions,
int start, int start,
int count) int count)
@ -1192,7 +1192,7 @@ namespace Avalonia.Controls
/// <param name="start">Starting index of the range.</param> /// <param name="start">Starting index of the range.</param>
/// <param name="count">Number of definitions included in the range.</param> /// <param name="count">Number of definitions included in the range.</param>
/// <returns>Length type for given range.</returns> /// <returns>Length type for given range.</returns>
private LayoutTimeSizeType GetLengthTypeForRange( private static LayoutTimeSizeType GetLengthTypeForRange(
IReadOnlyList<DefinitionBase> definitions, IReadOnlyList<DefinitionBase> definitions,
int start, int start,
int count) int count)
@ -1721,7 +1721,7 @@ namespace Avalonia.Controls
/// </summary> /// </summary>
/// <param name="definitions">Array of definitions to use for calculations.</param> /// <param name="definitions">Array of definitions to use for calculations.</param>
/// <returns>Desired size.</returns> /// <returns>Desired size.</returns>
private double CalculateDesiredSize( private static double CalculateDesiredSize(
IReadOnlyList<DefinitionBase> definitions) IReadOnlyList<DefinitionBase> definitions)
{ {
double desiredSize = 0; double desiredSize = 0;
@ -2281,7 +2281,7 @@ namespace Avalonia.Controls
/// <param name="start">Start of the range.</param> /// <param name="start">Start of the range.</param>
/// <param name="count">Number of items in the range.</param> /// <param name="count">Number of items in the range.</param>
/// <returns>Final size.</returns> /// <returns>Final size.</returns>
private double GetFinalSizeForRange( private static double GetFinalSizeForRange(
IReadOnlyList<DefinitionBase> definitions, IReadOnlyList<DefinitionBase> definitions,
int start, int start,
int count) int count)

2
src/Avalonia.Controls/GridSplitter.cs

@ -516,7 +516,7 @@ namespace Avalonia.Controls
/// <summary> /// <summary>
/// Retrieves the ActualWidth or ActualHeight of the definition depending on its type Column or Row. /// Retrieves the ActualWidth or ActualHeight of the definition depending on its type Column or Row.
/// </summary> /// </summary>
private double GetActualLength(DefinitionBase definition) private static double GetActualLength(DefinitionBase definition)
{ {
var column = definition as ColumnDefinition; var column = definition as ColumnDefinition;

4
src/Avalonia.Controls/Platform/InProcessDragSource.cs

@ -69,7 +69,7 @@ namespace Avalonia.Platform
return effect; return effect;
} }
private DragDropEffects GetPreferredEffect(DragDropEffects effect, RawInputModifiers modifiers) private static DragDropEffects GetPreferredEffect(DragDropEffects effect, RawInputModifiers modifiers)
{ {
if (effect == DragDropEffects.Copy || effect == DragDropEffects.Move || effect == DragDropEffects.Link || effect == DragDropEffects.None) if (effect == DragDropEffects.Copy || effect == DragDropEffects.Move || effect == DragDropEffects.Link || effect == DragDropEffects.None)
return effect; // No need to check for the modifiers. return effect; // No need to check for the modifiers.
@ -80,7 +80,7 @@ namespace Avalonia.Platform
return DragDropEffects.Move; return DragDropEffects.Move;
} }
private StandardCursorType GetCursorForDropEffect(DragDropEffects effects) private static StandardCursorType GetCursorForDropEffect(DragDropEffects effects)
{ {
if (effects.HasAllFlags(DragDropEffects.Copy)) if (effects.HasAllFlags(DragDropEffects.Copy))
return StandardCursorType.DragCopy; return StandardCursorType.DragCopy;

6
src/Avalonia.Controls/Primitives/Popup.cs

@ -1,6 +1,5 @@
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.Linq;
using System.Reactive.Disposables; using System.Reactive.Disposables;
using Avalonia.Automation.Peers; using Avalonia.Automation.Peers;
using Avalonia.Controls.Mixins; using Avalonia.Controls.Mixins;
@ -15,7 +14,6 @@ using Avalonia.Metadata;
using Avalonia.Platform; using Avalonia.Platform;
using Avalonia.VisualTree; using Avalonia.VisualTree;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Utilities;
namespace Avalonia.Controls.Primitives namespace Avalonia.Controls.Primitives
{ {
@ -639,7 +637,7 @@ namespace Avalonia.Controls.Primitives
return Disposable.Create((unsubscribe, target, handler), state => state.unsubscribe(state.target, state.handler)); return Disposable.Create((unsubscribe, target, handler), state => state.unsubscribe(state.target, state.handler));
} }
private void WindowManagerAddShadowHintChanged(IPopupHost host, bool hint) private static void WindowManagerAddShadowHintChanged(IPopupHost host, bool hint)
{ {
if(host is PopupRoot pr && pr.PlatformImpl is not null) if(host is PopupRoot pr && pr.PlatformImpl is not null)
{ {
@ -769,7 +767,7 @@ namespace Avalonia.Controls.Primitives
} }
} }
private void PassThroughEvent(PointerPressedEventArgs e) private static void PassThroughEvent(PointerPressedEventArgs e)
{ {
if (e.Source is LightDismissOverlayLayer layer && if (e.Source is LightDismissOverlayLayer layer &&
layer.GetVisualRoot() is InputElement root) layer.GetVisualRoot() is InputElement root)

2
src/Avalonia.Controls/Repeater/RecyclingElementFactory.cs

@ -87,7 +87,7 @@ namespace Avalonia.Controls
protected virtual string OnSelectTemplateKeyCore(object? dataContext, Control? owner) protected virtual string OnSelectTemplateKeyCore(object? dataContext, Control? owner)
{ {
if (SelectTemplateKey is object) if (SelectTemplateKey is not null)
{ {
_args ??= new SelectTemplateEventArgs(); _args ??= new SelectTemplateEventArgs();
_args.TemplateKey = null; _args.TemplateKey = null;

7
src/Avalonia.Controls/SplitView.cs

@ -1,14 +1,11 @@
using Avalonia.Controls.Metadata; using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives; using Avalonia.Controls.Primitives;
using Avalonia.Input; using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Interactivity; using Avalonia.Interactivity;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Metadata; using Avalonia.Metadata;
using Avalonia.Platform;
using Avalonia.VisualTree; using Avalonia.VisualTree;
using System; using System;
using System.Reactive.Disposables;
using Avalonia.Controls.Presenters; using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates; using Avalonia.Controls.Templates;
using Avalonia.LogicalTree; using Avalonia.LogicalTree;
@ -431,7 +428,7 @@ namespace Avalonia.Controls
} }
} }
private string GetPseudoClass(SplitViewDisplayMode mode) private static string GetPseudoClass(SplitViewDisplayMode mode)
{ {
return mode switch return mode switch
{ {
@ -443,7 +440,7 @@ namespace Avalonia.Controls
}; };
} }
private string GetPseudoClass(SplitViewPanePlacement placement) private static string GetPseudoClass(SplitViewPanePlacement placement)
{ {
return placement switch return placement switch
{ {

2
src/Avalonia.Controls/TextBox.cs

@ -1588,7 +1588,7 @@ namespace Avalonia.Controls
private int CoerceCaretIndex(int value) => CoerceCaretIndex(value, Text); private int CoerceCaretIndex(int value) => CoerceCaretIndex(value, Text);
private int CoerceCaretIndex(int value, string? text) private static int CoerceCaretIndex(int value, string? text)
{ {
if (text == null) if (text == null)
{ {

2
src/Avalonia.Controls/TopLevel.cs

@ -427,7 +427,7 @@ namespace Avalonia.Controls
LayoutHelper.InvalidateSelfAndChildrenMeasure(this); LayoutHelper.InvalidateSelfAndChildrenMeasure(this);
} }
private bool TransparencyLevelsMatch (WindowTransparencyLevel requested, WindowTransparencyLevel received) private static bool TransparencyLevelsMatch (WindowTransparencyLevel requested, WindowTransparencyLevel received)
{ {
if(requested == received) if(requested == received)
{ {

1
src/Avalonia.Controls/UserControl.cs

@ -1,4 +1,3 @@
using System;
using Avalonia.Styling; using Avalonia.Styling;
namespace Avalonia.Controls namespace Avalonia.Controls

2
src/Avalonia.Diagnostics/Diagnostics/Screenshots/FilePickerHandler.cs

@ -47,7 +47,7 @@ namespace Avalonia.Diagnostics.Screenshots
/// </summary> /// </summary>
public string Title { get; } = "Save Screenshot to ..."; public string Title { get; } = "Save Screenshot to ...";
Window GetWindow(Control control) static Window GetWindow(Control control)
{ {
var window = control.VisualRoot as Window; var window = control.VisualRoot as Window;
var app = Application.Current; var app = Application.Current;

14
src/Avalonia.Diagnostics/Diagnostics/ViewModels/ControlDetailsViewModel.cs

@ -82,7 +82,7 @@ namespace Avalonia.Diagnostics.ViewModels
{ {
var setterValue = regularSetter.Value; var setterValue = regularSetter.Value;
var resourceInfo = GetResourceInfo(setterValue); var resourceInfo = GetResourceInfo(setterValue);
SetterViewModel setterVm; SetterViewModel setterVm;
@ -121,7 +121,7 @@ namespace Avalonia.Diagnostics.ViewModels
public bool CanNavigateToParentProperty => _selectedEntitiesStack.Count >= 1; public bool CanNavigateToParentProperty => _selectedEntitiesStack.Count >= 1;
private (object resourceKey, bool isDynamic)? GetResourceInfo(object? value) private static (object resourceKey, bool isDynamic)? GetResourceInfo(object? value)
{ {
if (value is StaticResourceExtension staticResource) if (value is StaticResourceExtension staticResource)
{ {
@ -136,7 +136,7 @@ namespace Avalonia.Diagnostics.ViewModels
return null; return null;
} }
private bool IsBinding(object? value) private static bool IsBinding(object? value)
{ {
switch (value) switch (value)
{ {
@ -253,7 +253,7 @@ namespace Avalonia.Diagnostics.ViewModels
} }
} }
private IEnumerable<PropertyViewModel> GetAvaloniaProperties(object o) private static IEnumerable<PropertyViewModel> GetAvaloniaProperties(object o)
{ {
if (o is AvaloniaObject ao) if (o is AvaloniaObject ao)
{ {
@ -267,7 +267,7 @@ namespace Avalonia.Diagnostics.ViewModels
} }
} }
private IEnumerable<PropertyViewModel> GetClrProperties(object o, bool showImplementedInterfaces) private static IEnumerable<PropertyViewModel> GetClrProperties(object o, bool showImplementedInterfaces)
{ {
foreach (var p in GetClrProperties(o, o.GetType())) foreach (var p in GetClrProperties(o, o.GetType()))
{ {
@ -286,7 +286,7 @@ namespace Avalonia.Diagnostics.ViewModels
} }
} }
private IEnumerable<PropertyViewModel> GetClrProperties(object o, Type t) private static IEnumerable<PropertyViewModel> GetClrProperties(object o, Type t)
{ {
return t.GetProperties() return t.GetProperties()
.Where(x => x.GetIndexParameters().Length == 0) .Where(x => x.GetIndexParameters().Length == 0)
@ -411,7 +411,7 @@ namespace Avalonia.Diagnostics.ViewModels
} }
} }
private int GroupIndex(string? group) private static int GroupIndex(string? group)
{ {
switch (group) switch (group)
{ {

8
src/Avalonia.Dialogs/ManagedStorageProvider.cs

@ -29,7 +29,7 @@ public class ManagedStorageProvider<T> : BclStorageProvider where T : Window, ne
public override async Task<IReadOnlyList<IStorageFile>> OpenFilePickerAsync(FilePickerOpenOptions options) public override async Task<IReadOnlyList<IStorageFile>> OpenFilePickerAsync(FilePickerOpenOptions options)
{ {
var model = new ManagedFileChooserViewModel(options, _managedOptions); var model = new ManagedFileChooserViewModel(options, _managedOptions);
var results = await Show(model, _parent); var results = await ManagedStorageProvider<T>.Show(model, _parent);
return results.Select(f => new BclStorageFile(new FileInfo(f))).ToArray(); return results.Select(f => new BclStorageFile(new FileInfo(f))).ToArray();
} }
@ -37,7 +37,7 @@ public class ManagedStorageProvider<T> : BclStorageProvider where T : Window, ne
public override async Task<IStorageFile?> SaveFilePickerAsync(FilePickerSaveOptions options) public override async Task<IStorageFile?> SaveFilePickerAsync(FilePickerSaveOptions options)
{ {
var model = new ManagedFileChooserViewModel(options, _managedOptions); var model = new ManagedFileChooserViewModel(options, _managedOptions);
var results = await Show(model, _parent); var results = await ManagedStorageProvider<T>.Show(model, _parent);
return results.FirstOrDefault() is { } result return results.FirstOrDefault() is { } result
? new BclStorageFile(new FileInfo(result)) ? new BclStorageFile(new FileInfo(result))
@ -47,12 +47,12 @@ public class ManagedStorageProvider<T> : BclStorageProvider where T : Window, ne
public override async Task<IReadOnlyList<IStorageFolder>> OpenFolderPickerAsync(FolderPickerOpenOptions options) public override async Task<IReadOnlyList<IStorageFolder>> OpenFolderPickerAsync(FolderPickerOpenOptions options)
{ {
var model = new ManagedFileChooserViewModel(options, _managedOptions); var model = new ManagedFileChooserViewModel(options, _managedOptions);
var results = await Show(model, _parent); var results = await ManagedStorageProvider<T>.Show(model, _parent);
return results.Select(f => new BclStorageFolder(new DirectoryInfo(f))).ToArray(); return results.Select(f => new BclStorageFolder(new DirectoryInfo(f))).ToArray();
} }
private async Task<string[]> Show(ManagedFileChooserViewModel model, Window parent) private static async Task<string[]> Show(ManagedFileChooserViewModel model, Window parent)
{ {
var dialog = new T var dialog = new T
{ {

8
src/Avalonia.FreeDesktop/LinuxMountedVolumeInfoListener.cs

@ -34,14 +34,14 @@ namespace Avalonia.FreeDesktop
Poll(0); Poll(0);
} }
private string GetSymlinkTarget(string x) => Path.GetFullPath(Path.Combine(DevByLabelDir, NativeMethods.ReadLink(x))); private static string GetSymlinkTarget(string x) => Path.GetFullPath(Path.Combine(DevByLabelDir, NativeMethods.ReadLink(x)));
private string UnescapeString(string input, string regexText, int escapeBase) => private static string UnescapeString(string input, string regexText, int escapeBase) =>
new Regex(regexText).Replace(input, m => Convert.ToChar(Convert.ToByte(m.Groups[1].Value, escapeBase)).ToString()); new Regex(regexText).Replace(input, m => Convert.ToChar(Convert.ToByte(m.Groups[1].Value, escapeBase)).ToString());
private string UnescapePathFromProcMounts(string input) => UnescapeString(input, @"\\(\d{3})", 8); private static string UnescapePathFromProcMounts(string input) => UnescapeString(input, @"\\(\d{3})", 8);
private string UnescapeDeviceLabel(string input) => UnescapeString(input, @"\\x([0-9a-f]{2})", 16); private static string UnescapeDeviceLabel(string input) => UnescapeString(input, @"\\x([0-9a-f]{2})", 16);
private void Poll(long _) private void Poll(long _)
{ {

2
src/Avalonia.Native/AvaloniaNativeMenuExporter.cs

@ -65,7 +65,7 @@ namespace Avalonia.Native
} }
} }
private NativeMenu CreateDefaultAppMenu() private static NativeMenu CreateDefaultAppMenu()
{ {
var result = new NativeMenu(); var result = new NativeMenu();

3
src/Avalonia.Native/IAvnMenu.cs

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Collections.Specialized; using System.Collections.Specialized;
using System.Reactive.Disposables; using System.Reactive.Disposables;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Platform.Interop;
namespace Avalonia.Native.Interop namespace Avalonia.Native.Interop
{ {
@ -112,7 +111,7 @@ namespace Avalonia.Native.Interop.Impl
return result; return result;
} }
private __MicroComIAvnMenuItemProxy CreateNew(IAvaloniaNativeFactory factory, NativeMenuItemBase item) private static __MicroComIAvnMenuItemProxy CreateNew(IAvaloniaNativeFactory factory, NativeMenuItemBase item)
{ {
var nativeItem = (__MicroComIAvnMenuItemProxy)(item is NativeMenuItemSeparator ? var nativeItem = (__MicroComIAvnMenuItemProxy)(item is NativeMenuItemSeparator ?
factory.CreateMenuItemSeparator() : factory.CreateMenuItemSeparator() :

4
src/Avalonia.OpenGL/Controls/OpenGlControlBase.cs

@ -38,7 +38,7 @@ namespace Avalonia.OpenGL.Controls
base.Render(context); base.Render(context);
} }
private void CheckError(GlInterface gl) private static void CheckError(GlInterface gl)
{ {
int err; int err;
while ((err = gl.GetError()) != GL_NO_ERROR) while ((err = gl.GetError()) != GL_NO_ERROR)
@ -197,7 +197,7 @@ namespace Avalonia.OpenGL.Controls
} }
} }
private bool CheckFramebufferStatus(GlInterface gl) private static bool CheckFramebufferStatus(GlInterface gl)
{ {
var status = gl.CheckFramebufferStatus(GL_FRAMEBUFFER); var status = gl.CheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) if (status != GL_FRAMEBUFFER_COMPLETE)

2
src/Avalonia.X11/X11IconLoader.cs

@ -9,7 +9,7 @@ namespace Avalonia.X11
{ {
class X11IconLoader : IPlatformIconLoader class X11IconLoader : IPlatformIconLoader
{ {
IWindowIconImpl LoadIcon(Bitmap bitmap) static IWindowIconImpl LoadIcon(Bitmap bitmap)
{ {
var rv = new X11IconData(bitmap); var rv = new X11IconData(bitmap);
bitmap.Dispose(); bitmap.Dispose();

9
src/Avalonia.X11/X11Platform.cs

@ -5,7 +5,6 @@ using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Platform; using Avalonia.Controls.Platform;
using Avalonia.Dialogs;
using Avalonia.FreeDesktop; using Avalonia.FreeDesktop;
using Avalonia.FreeDesktop.DBusIme; using Avalonia.FreeDesktop.DBusIme;
using Avalonia.Input; using Avalonia.Input;
@ -85,7 +84,7 @@ namespace Avalonia.X11
.Bind<IMountedVolumeInfoProvider>().ToConstant(new LinuxMountedVolumeInfoProvider()) .Bind<IMountedVolumeInfoProvider>().ToConstant(new LinuxMountedVolumeInfoProvider())
.Bind<IPlatformLifetimeEventsImpl>().ToConstant(new X11PlatformLifetimeEvents(this)); .Bind<IPlatformLifetimeEventsImpl>().ToConstant(new X11PlatformLifetimeEvents(this));
X11Screens = Avalonia.X11.X11Screens.Init(this); X11Screens = X11.X11Screens.Init(this);
Screens = new X11Screens(X11Screens); Screens = new X11Screens(X11Screens);
if (Info.XInputVersion != null) if (Info.XInputVersion != null)
{ {
@ -143,7 +142,7 @@ namespace Avalonia.X11
throw new NotSupportedException(); throw new NotSupportedException();
} }
bool EnableIme(X11PlatformOptions options) static bool EnableIme(X11PlatformOptions options)
{ {
// Disable if explicitly asked by user // Disable if explicitly asked by user
var avaloniaImModule = Environment.GetEnvironmentVariable("AVALONIA_IM_MODULE"); var avaloniaImModule = Environment.GetEnvironmentVariable("AVALONIA_IM_MODULE");
@ -164,8 +163,8 @@ namespace Avalonia.X11
return isCjkLocale; return isCjkLocale;
} }
bool ShouldUseXim() static bool ShouldUseXim()
{ {
// Check if we are forbidden from using IME // Check if we are forbidden from using IME
if (Environment.GetEnvironmentVariable("AVALONIA_IM_MODULE") == "none" if (Environment.GetEnvironmentVariable("AVALONIA_IM_MODULE") == "none"

1
src/Avalonia.X11/X11Window.Ime.cs

@ -2,7 +2,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading.Tasks;
using Avalonia.FreeDesktop; using Avalonia.FreeDesktop;
using Avalonia.Input; using Avalonia.Input;
using Avalonia.Input.Raw; using Avalonia.Input.Raw;

4
src/Avalonia.X11/X11Window.cs

@ -1,9 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Reactive.Disposables;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Threading; using System.Threading;
@ -683,7 +681,7 @@ namespace Avalonia.X11
} }
RawInputModifiers TranslateModifiers(XModifierMask state) static RawInputModifiers TranslateModifiers(XModifierMask state)
{ {
var rv = default(RawInputModifiers); var rv = default(RawInputModifiers);
if (state.HasAllFlags(XModifierMask.Button1Mask)) if (state.HasAllFlags(XModifierMask.Button1Mask))

8
src/Markup/Avalonia.Markup.Xaml.Loader/CompilerExtensions/XamlIlAvaloniaPropertyHelper.cs

@ -1,11 +1,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Xml;
using Avalonia.Markup.Xaml.Parsers; using Avalonia.Markup.Xaml.Parsers;
using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers; using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers;
using Avalonia.Utilities; using Avalonia.Utilities;
using XamlX;
using XamlX.Ast; using XamlX.Ast;
using XamlX.Transform; using XamlX.Transform;
using XamlX.Transform.Transformers; using XamlX.Transform.Transformers;
@ -67,10 +65,8 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
string propertyName, IXamlAstTypeReference selectorTypeReference, IXamlLineInfo lineInfo) string propertyName, IXamlAstTypeReference selectorTypeReference, IXamlLineInfo lineInfo)
{ {
XamlAstNamePropertyReference forgedReference; XamlAstNamePropertyReference forgedReference;
var parser = new PropertyParser(); var parsedPropertyName = PropertyParser.Parse(new CharacterReader(propertyName.AsSpan()));
var parsedPropertyName = parser.Parse(new CharacterReader(propertyName.AsSpan()));
if(parsedPropertyName.owner == null) if(parsedPropertyName.owner == null)
forgedReference = new XamlAstNamePropertyReference(lineInfo, selectorTypeReference, forgedReference = new XamlAstNamePropertyReference(lineInfo, selectorTypeReference,
propertyName, selectorTypeReference); propertyName, selectorTypeReference);

8
src/Markup/Avalonia.Markup.Xaml/Converters/AvaloniaPropertyTypeConverter.cs

@ -3,7 +3,6 @@ using System.ComponentModel;
using System.Globalization; using System.Globalization;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Logging; using Avalonia.Logging;
using Avalonia.Markup.Parsers;
using Avalonia.Markup.Xaml.Parsers; using Avalonia.Markup.Xaml.Parsers;
using Avalonia.Markup.Xaml.Templates; using Avalonia.Markup.Xaml.Templates;
using Avalonia.Styling; using Avalonia.Styling;
@ -21,8 +20,7 @@ namespace Avalonia.Markup.Xaml.Converters
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{ {
var registry = AvaloniaPropertyRegistry.Instance; var registry = AvaloniaPropertyRegistry.Instance;
var parser = new PropertyParser(); var (ns, owner, propertyName) = PropertyParser.Parse(new CharacterReader(((string)value).AsSpan()));
var (ns, owner, propertyName) = parser.Parse(new CharacterReader(((string)value).AsSpan()));
var ownerType = TryResolveOwnerByName(context, ns, owner); var ownerType = TryResolveOwnerByName(context, ns, owner);
var targetType = context.GetFirstParent<ControlTemplate>()?.TargetType ?? var targetType = context.GetFirstParent<ControlTemplate>()?.TargetType ??
context.GetFirstParent<Style>()?.Selector?.TargetType ?? context.GetFirstParent<Style>()?.Selector?.TargetType ??
@ -37,7 +35,7 @@ namespace Avalonia.Markup.Xaml.Converters
if (effectiveOwner != targetType && if (effectiveOwner != targetType &&
!property.IsAttached && !property.IsAttached &&
!registry.IsRegistered(targetType, property)) !AvaloniaPropertyRegistry.Instance.IsRegistered(targetType, property))
{ {
Logger.TryGet(LogEventLevel.Warning, LogArea.Property)?.Log( Logger.TryGet(LogEventLevel.Warning, LogArea.Property)?.Log(
this, this,
@ -50,7 +48,7 @@ namespace Avalonia.Markup.Xaml.Converters
return property; return property;
} }
private Type TryResolveOwnerByName(ITypeDescriptorContext context, string ns, string owner) private static Type TryResolveOwnerByName(ITypeDescriptorContext context, string ns, string owner)
{ {
if (owner != null) if (owner != null)
{ {

2
src/Markup/Avalonia.Markup.Xaml/Converters/IconTypeConverter.cs

@ -32,7 +32,7 @@ namespace Avalonia.Markup.Xaml.Converters
throw new NotSupportedException(); throw new NotSupportedException();
} }
private WindowIcon CreateIconFromPath(ITypeDescriptorContext context, string s) private static WindowIcon CreateIconFromPath(ITypeDescriptorContext context, string s)
{ {
var uri = s.StartsWith("/") var uri = s.StartsWith("/")
? new Uri(s, UriKind.Relative) ? new Uri(s, UriKind.Relative)

2
src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/DynamicResourceExtension.cs

@ -68,7 +68,7 @@ namespace Avalonia.Markup.Xaml.MarkupExtensions
return null; return null;
} }
private Func<object?, object?>? GetConverter(AvaloniaProperty? targetProperty) private static Func<object?, object?>? GetConverter(AvaloniaProperty? targetProperty)
{ {
if (targetProperty?.PropertyType == typeof(IBrush)) if (targetProperty?.PropertyType == typeof(IBrush))
{ {

6
src/Markup/Avalonia.Markup.Xaml/Parsers/PropertyParser.cs

@ -1,13 +1,11 @@
using System; using Avalonia.Data.Core;
using Avalonia.Data.Core;
using Avalonia.Markup.Parsers;
using Avalonia.Utilities; using Avalonia.Utilities;
namespace Avalonia.Markup.Xaml.Parsers namespace Avalonia.Markup.Xaml.Parsers
{ {
internal class PropertyParser internal class PropertyParser
{ {
public (string ns, string owner, string name) Parse(CharacterReader r) public static (string ns, string owner, string name) Parse(CharacterReader r)
{ {
if (r.End) if (r.End)
{ {

6
src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/StringIndexerNode.cs

@ -113,7 +113,7 @@ namespace Avalonia.Markup.Parsers.Nodes
} }
private bool SetValueInArray(Array array, int[] indices, object? value) private static bool SetValueInArray(Array array, int[] indices, object? value)
{ {
if (ValidBounds(indices, array)) if (ValidBounds(indices, array))
{ {
@ -223,7 +223,7 @@ namespace Avalonia.Markup.Parsers.Nodes
return GetValueFromArray(array, intArgs); return GetValueFromArray(array, intArgs);
} }
private object? GetValueFromArray(Array array, int[] indices) private static object? GetValueFromArray(Array array, int[] indices)
{ {
if (ValidBounds(indices, array)) if (ValidBounds(indices, array))
{ {
@ -275,7 +275,7 @@ namespace Avalonia.Markup.Parsers.Nodes
return null; return null;
} }
private bool ValidBounds(int[] indices, Array array) private static bool ValidBounds(int[] indices, Array array)
{ {
if (indices.Length == array.Rank) if (indices.Length == array.Rank)
{ {

4
src/Skia/Avalonia.Skia/DrawingContextImpl.cs

@ -280,7 +280,7 @@ namespace Avalonia.Skia
} }
} }
SKRect AreaCastingShadowInHole( static SKRect AreaCastingShadowInHole(
SKRect hole_rect, SKRect hole_rect,
float shadow_blur, float shadow_blur,
float shadow_spread, float shadow_spread,
@ -689,7 +689,7 @@ namespace Avalonia.Skia
/// <param name="paintWrapper">Paint wrapper.</param> /// <param name="paintWrapper">Paint wrapper.</param>
/// <param name="targetSize">Target size.</param> /// <param name="targetSize">Target size.</param>
/// <param name="gradientBrush">Gradient brush.</param> /// <param name="gradientBrush">Gradient brush.</param>
private void ConfigureGradientBrush(ref PaintWrapper paintWrapper, Size targetSize, IGradientBrush gradientBrush) private static void ConfigureGradientBrush(ref PaintWrapper paintWrapper, Size targetSize, IGradientBrush gradientBrush)
{ {
var tileMode = gradientBrush.SpreadMethod.ToSKShaderTileMode(); var tileMode = gradientBrush.SpreadMethod.ToSKShaderTileMode();
var stopColors = gradientBrush.GradientStops.Select(s => s.Color.ToSKColor()).ToArray(); var stopColors = gradientBrush.GradientStops.Select(s => s.Color.ToSKColor()).ToArray();

7
src/Windows/Avalonia.Win32.Interop/Wpf/Direct2DImageSurface.cs

@ -113,7 +113,8 @@ namespace Avalonia.Win32.Interop.Wpf
[DllImport("user32.dll", SetLastError = false)] [DllImport("user32.dll", SetLastError = false)]
private static extern IntPtr GetDesktopWindow(); private static extern IntPtr GetDesktopWindow();
void EnsureDirectX()
static void EnsureDirectX()
{ {
if(s_d3DDevice != null) if(s_d3DDevice != null)
return; return;
@ -153,7 +154,7 @@ namespace Avalonia.Win32.Interop.Wpf
_oldDpi = dpi; _oldDpi = dpi;
} }
_impl.ImageSource = _image; _impl.ImageSource = _image;
RemoveAndDispose(ref _backBuffer); RemoveAndDispose(ref _backBuffer);
if (size == default(IntSize)) if (size == default(IntSize))
{ {
@ -167,7 +168,7 @@ namespace Avalonia.Win32.Interop.Wpf
return _backBuffer.Target; return _backBuffer.Target;
} }
void RemoveAndDispose<T>(ref T d) where T : IDisposable static void RemoveAndDispose<T>(ref T d) where T : IDisposable
{ {
d?.Dispose(); d?.Dispose();
d = default(T); d = default(T);

3
src/Windows/Avalonia.Win32.Interop/Wpf/WpfTopLevelImpl.cs

@ -142,8 +142,7 @@ namespace Avalonia.Win32.Interop.Wpf
protected override void OnLostFocus(RoutedEventArgs e) => LostFocus?.Invoke(); protected override void OnLostFocus(RoutedEventArgs e) => LostFocus?.Invoke();
static RawInputModifiers GetModifiers(MouseEventArgs e)
RawInputModifiers GetModifiers(MouseEventArgs e)
{ {
var state = Keyboard.Modifiers; var state = Keyboard.Modifiers;
var rv = default(RawInputModifiers); var rv = default(RawInputModifiers);

2
src/Windows/Avalonia.Win32/ClipboardImpl.cs

@ -16,7 +16,7 @@ namespace Avalonia.Win32
private const int OleRetryCount = 10; private const int OleRetryCount = 10;
private const int OleRetryDelay = 100; private const int OleRetryDelay = 100;
private async Task<IDisposable> OpenClipboard() private static async Task<IDisposable> OpenClipboard()
{ {
var i = OleRetryCount; var i = OleRetryCount;

2
src/Windows/Avalonia.Win32/CursorFactory.cs

@ -107,7 +107,7 @@ namespace Avalonia.Win32
return new CursorImpl(UnmanagedMethods.CreateIconIndirect(ref info), true); return new CursorImpl(UnmanagedMethods.CreateIconIndirect(ref info), true);
} }
private SdBitmap LoadSystemDrawingBitmap(IBitmapImpl bitmap) private static SdBitmap LoadSystemDrawingBitmap(IBitmapImpl bitmap)
{ {
using var memoryStream = new MemoryStream(); using var memoryStream = new MemoryStream();
bitmap.Save(memoryStream); bitmap.Save(memoryStream);

8
src/Windows/Avalonia.Win32/DataObject.cs

@ -291,7 +291,7 @@ namespace Avalonia.Win32
return WriteBytesToHGlobal(ref hGlobal, SerializeObject(data)); return WriteBytesToHGlobal(ref hGlobal, SerializeObject(data));
} }
private byte[] SerializeObject(object data) private static byte[] SerializeObject(object data)
{ {
using (var ms = new MemoryStream()) using (var ms = new MemoryStream())
{ {
@ -302,7 +302,7 @@ namespace Avalonia.Win32
} }
} }
private unsafe uint WriteBytesToHGlobal(ref IntPtr hGlobal, ReadOnlySpan<byte> data) private static unsafe uint WriteBytesToHGlobal(ref IntPtr hGlobal, ReadOnlySpan<byte> data)
{ {
int required = data.Length; int required = data.Length;
if (hGlobal == IntPtr.Zero) if (hGlobal == IntPtr.Zero)
@ -326,7 +326,7 @@ namespace Avalonia.Win32
} }
} }
private uint WriteFileListToHGlobal(ref IntPtr hGlobal, IEnumerable<string> files) private static uint WriteFileListToHGlobal(ref IntPtr hGlobal, IEnumerable<string> files)
{ {
if (!files?.Any() ?? false) if (!files?.Any() ?? false)
return unchecked((int)UnmanagedMethods.HRESULT.S_OK); return unchecked((int)UnmanagedMethods.HRESULT.S_OK);
@ -358,7 +358,7 @@ namespace Avalonia.Win32
} }
} }
private uint WriteStringToHGlobal(ref IntPtr hGlobal, string data) private static uint WriteStringToHGlobal(ref IntPtr hGlobal, string data)
{ {
int required = (data.Length + 1) * sizeof(char); int required = (data.Length + 1) * sizeof(char);
if (hGlobal == IntPtr.Zero) if (hGlobal == IntPtr.Zero)

6
src/Windows/Avalonia.Win32/PopupImpl.cs

@ -92,7 +92,7 @@ namespace Avalonia.Win32
IntPtr.Zero); IntPtr.Zero);
s_parentHandle = IntPtr.Zero; s_parentHandle = IntPtr.Zero;
EnableBoxShadow(result, _dropShadowHint); PopupImpl.EnableBoxShadow(result, _dropShadowHint);
return result; return result;
} }
@ -139,7 +139,7 @@ namespace Avalonia.Win32
//TODO: We ignore the scaling override for now //TODO: We ignore the scaling override for now
} }
private void EnableBoxShadow (IntPtr hwnd, bool enabled) private static void EnableBoxShadow (IntPtr hwnd, bool enabled)
{ {
var classes = (int)UnmanagedMethods.GetClassLongPtr(hwnd, (int)UnmanagedMethods.ClassLongIndex.GCL_STYLE); var classes = (int)UnmanagedMethods.GetClassLongPtr(hwnd, (int)UnmanagedMethods.ClassLongIndex.GCL_STYLE);
@ -161,7 +161,7 @@ namespace Avalonia.Win32
if (Handle != null) if (Handle != null)
{ {
EnableBoxShadow(Handle.Handle, enabled); PopupImpl.EnableBoxShadow(Handle.Handle, enabled);
} }
} }

32
src/Windows/Avalonia.Win32/Win32Platform.cs

@ -184,16 +184,16 @@ namespace Avalonia.Win32
public bool HasMessages() public bool HasMessages()
{ {
UnmanagedMethods.MSG msg; UnmanagedMethods.MSG msg;
return UnmanagedMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, 0); return PeekMessage(out msg, IntPtr.Zero, 0, 0, 0);
} }
public void ProcessMessage() public void ProcessMessage()
{ {
if (UnmanagedMethods.GetMessage(out var msg, IntPtr.Zero, 0, 0) > -1) if (GetMessage(out var msg, IntPtr.Zero, 0, 0) > -1)
{ {
UnmanagedMethods.TranslateMessage(ref msg); TranslateMessage(ref msg);
UnmanagedMethods.DispatchMessage(ref msg); DispatchMessage(ref msg);
} }
else else
{ {
@ -207,10 +207,10 @@ namespace Avalonia.Win32
{ {
var result = 0; var result = 0;
while (!cancellationToken.IsCancellationRequested while (!cancellationToken.IsCancellationRequested
&& (result = UnmanagedMethods.GetMessage(out var msg, IntPtr.Zero, 0, 0)) > 0) && (result = GetMessage(out var msg, IntPtr.Zero, 0, 0)) > 0)
{ {
UnmanagedMethods.TranslateMessage(ref msg); TranslateMessage(ref msg);
UnmanagedMethods.DispatchMessage(ref msg); DispatchMessage(ref msg);
} }
if (result < 0) if (result < 0)
{ {
@ -224,7 +224,7 @@ namespace Avalonia.Win32
UnmanagedMethods.TimerProc timerDelegate = UnmanagedMethods.TimerProc timerDelegate =
(hWnd, uMsg, nIDEvent, dwTime) => callback(); (hWnd, uMsg, nIDEvent, dwTime) => callback();
IntPtr handle = UnmanagedMethods.SetTimer( IntPtr handle = SetTimer(
IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero, IntPtr.Zero,
(uint)interval.TotalMilliseconds, (uint)interval.TotalMilliseconds,
@ -236,7 +236,7 @@ namespace Avalonia.Win32
return Disposable.Create(() => return Disposable.Create(() =>
{ {
_delegates.Remove(timerDelegate); _delegates.Remove(timerDelegate);
UnmanagedMethods.KillTimer(IntPtr.Zero, handle); KillTimer(IntPtr.Zero, handle);
}); });
} }
@ -245,9 +245,9 @@ namespace Avalonia.Win32
public void Signal(DispatcherPriority prio) public void Signal(DispatcherPriority prio)
{ {
UnmanagedMethods.PostMessage( PostMessage(
_hwnd, _hwnd,
(int) UnmanagedMethods.WindowsMessage.WM_DISPATCH_WORK_ITEM, (int)WindowsMessage.WM_DISPATCH_WORK_ITEM,
new IntPtr(SignalW), new IntPtr(SignalW),
new IntPtr(SignalL)); new IntPtr(SignalL));
} }
@ -261,7 +261,7 @@ namespace Avalonia.Win32
[SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Using Win32 naming for consistency.")] [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Using Win32 naming for consistency.")]
private IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) private IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{ {
if (msg == (int) UnmanagedMethods.WindowsMessage.WM_DISPATCH_WORK_ITEM && wParam.ToInt64() == SignalW && lParam.ToInt64() == SignalL) if (msg == (int)WindowsMessage.WM_DISPATCH_WORK_ITEM && wParam.ToInt64() == SignalW && lParam.ToInt64() == SignalL)
{ {
Signaled?.Invoke(null); Signaled?.Invoke(null);
} }
@ -283,7 +283,7 @@ namespace Avalonia.Win32
TrayIconImpl.ProcWnd(hWnd, msg, wParam, lParam); TrayIconImpl.ProcWnd(hWnd, msg, wParam, lParam);
return UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam); return DefWindowProc(hWnd, msg, wParam, lParam);
} }
private void CreateMessageWindow() private void CreateMessageWindow()
@ -295,18 +295,18 @@ namespace Avalonia.Win32
{ {
cbSize = Marshal.SizeOf<UnmanagedMethods.WNDCLASSEX>(), cbSize = Marshal.SizeOf<UnmanagedMethods.WNDCLASSEX>(),
lpfnWndProc = _wndProcDelegate, lpfnWndProc = _wndProcDelegate,
hInstance = UnmanagedMethods.GetModuleHandle(null), hInstance = GetModuleHandle(null),
lpszClassName = "AvaloniaMessageWindow " + Guid.NewGuid(), lpszClassName = "AvaloniaMessageWindow " + Guid.NewGuid(),
}; };
ushort atom = UnmanagedMethods.RegisterClassEx(ref wndClassEx); ushort atom = RegisterClassEx(ref wndClassEx);
if (atom == 0) if (atom == 0)
{ {
throw new Win32Exception(); throw new Win32Exception();
} }
_hwnd = UnmanagedMethods.CreateWindowEx(0, atom, null, 0, 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); _hwnd = CreateWindowEx(0, atom, null, 0, 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if (_hwnd == IntPtr.Zero) if (_hwnd == IntPtr.Zero)
{ {

4
src/Windows/Avalonia.Win32/WindowImpl.AppWndProc.cs

@ -377,7 +377,7 @@ namespace Avalonia.Win32
RawPointerEventType.XButton1Down : RawPointerEventType.XButton1Down :
RawPointerEventType.XButton2Down, RawPointerEventType.XButton2Down,
}, },
PointToClient(PointFromLParam(lParam)), GetMouseModifiers(wParam)); PointToClient(WindowImpl.PointFromLParam(lParam)), GetMouseModifiers(wParam));
break; break;
} }
case WindowsMessage.WM_TOUCH: case WindowsMessage.WM_TOUCH:
@ -1035,7 +1035,7 @@ namespace Avalonia.Win32
return new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16)) / RenderScaling; return new Point((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16)) / RenderScaling;
} }
private PixelPoint PointFromLParam(IntPtr lParam) private static PixelPoint PointFromLParam(IntPtr lParam)
{ {
return new PixelPoint((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16)); return new PixelPoint((short)(ToInt32(lParam) & 0xffff), (short)(ToInt32(lParam) >> 16));
} }

4
src/Windows/Avalonia.Win32/WindowImpl.CustomCaptionProc.cs

@ -13,7 +13,7 @@ namespace Avalonia.Win32
private HitTestValues HitTestNCA(IntPtr hWnd, IntPtr wParam, IntPtr lParam) private HitTestValues HitTestNCA(IntPtr hWnd, IntPtr wParam, IntPtr lParam)
{ {
// Get the point coordinates for the hit test (screen space). // Get the point coordinates for the hit test (screen space).
var ptMouse = PointFromLParam(lParam); var ptMouse = WindowImpl.PointFromLParam(lParam);
// Get the window rectangle. // Get the window rectangle.
GetWindowRect(hWnd, out var rcWindow); GetWindowRect(hWnd, out var rcWindow);
@ -105,7 +105,7 @@ namespace Avalonia.Win32
if (hittestResult == HitTestValues.HTCAPTION) if (hittestResult == HitTestValues.HTCAPTION)
{ {
var position = PointToClient(PointFromLParam(lParam)); var position = PointToClient(WindowImpl.PointFromLParam(lParam));
if (_owner is Window window) if (_owner is Window window)
{ {

7
src/Windows/Avalonia.Win32/WindowImpl.cs

@ -666,7 +666,7 @@ namespace Avalonia.Win32
public Point PointToClient(PixelPoint point) public Point PointToClient(PixelPoint point)
{ {
var p = new POINT { X = point.X, Y = point.Y }; var p = new POINT { X = point.X, Y = point.Y };
UnmanagedMethods.ScreenToClient(_hwnd, ref p); ScreenToClient(_hwnd, ref p);
return new Point(p.X, p.Y) / RenderScaling; return new Point(p.X, p.Y) / RenderScaling;
} }
@ -1347,12 +1347,13 @@ namespace Avalonia.Win32
private const int MF_DISABLED = 0x2; private const int MF_DISABLED = 0x2;
private const int SC_CLOSE = 0xF060; private const int SC_CLOSE = 0xF060;
void DisableCloseButton(IntPtr hwnd) static void DisableCloseButton(IntPtr hwnd)
{ {
EnableMenuItem(GetSystemMenu(hwnd, false), SC_CLOSE, EnableMenuItem(GetSystemMenu(hwnd, false), SC_CLOSE,
MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
} }
void EnableCloseButton(IntPtr hwnd)
static void EnableCloseButton(IntPtr hwnd)
{ {
EnableMenuItem(GetSystemMenu(hwnd, false), SC_CLOSE, EnableMenuItem(GetSystemMenu(hwnd, false), SC_CLOSE,
MF_BYCOMMAND | MF_ENABLED); MF_BYCOMMAND | MF_ENABLED);

2
src/iOS/Avalonia.iOS/CombinedSpan3.cs

@ -16,7 +16,7 @@ internal ref struct CombinedSpan3<T>
public int Length => Span1.Length + Span2.Length + Span3.Length; public int Length => Span1.Length + Span2.Length + Span3.Length;
void CopyFromSpan(ReadOnlySpan<T> from, int offset, ref Span<T> to) static void CopyFromSpan(ReadOnlySpan<T> from, int offset, ref Span<T> to)
{ {
if(to.Length == 0) if(to.Length == 0)
return; return;

2
src/iOS/Avalonia.iOS/TouchHandler.cs

@ -19,7 +19,7 @@ namespace Avalonia.iOS
_tl = tl; _tl = tl;
} }
ulong Ts(UIEvent evt) => (ulong) (evt.Timestamp * 1000); static ulong Ts(UIEvent evt) => (ulong) (evt.Timestamp * 1000);
private IInputRoot Root => _view.InputRoot; private IInputRoot Root => _view.InputRoot;
private static long _nextTouchPointId = 1; private static long _nextTouchPointId = 1;
private Dictionary<UITouch, long> _knownTouches = new Dictionary<UITouch, long>(); private Dictionary<UITouch, long> _knownTouches = new Dictionary<UITouch, long>();

4
src/tools/DevGenerators/CompositionGenerator/Generator.ListProxy.cs

@ -92,7 +92,7 @@ class Template
}} }}
"; ";
private ClassDeclarationSyntax AppendListProxy(GList list, ClassDeclarationSyntax cl) private static ClassDeclarationSyntax AppendListProxy(GList list, ClassDeclarationSyntax cl)
{ {
var itemType = list.ItemType; var itemType = list.ItemType;
@ -120,4 +120,4 @@ class Template
} }
} }
} }

13
src/tools/DevGenerators/CompositionGenerator/Generator.Utils.cs

@ -37,12 +37,11 @@ namespace Avalonia.SourceGenerator.CompositionGenerator
unit.NormalizeWhitespace().ToFullString(); unit.NormalizeWhitespace().ToFullString();
_output.AddSource(string.Join("_", path), text); _output.AddSource(string.Join("_", path), text);
} }
SyntaxToken Semicolon() => Token(SyntaxKind.SemicolonToken);
static SyntaxToken Semicolon() => Token(SyntaxKind.SemicolonToken);
FieldDeclarationSyntax DeclareConstant(string type, string name, LiteralExpressionSyntax value)
static FieldDeclarationSyntax DeclareConstant(string type, string name, LiteralExpressionSyntax value)
=> FieldDeclaration( => FieldDeclaration(
VariableDeclaration(ParseTypeName(type), VariableDeclaration(ParseTypeName(type),
SingletonSeparatedList( SingletonSeparatedList(
@ -51,10 +50,10 @@ namespace Avalonia.SourceGenerator.CompositionGenerator
).WithSemicolonToken(Semicolon()) ).WithSemicolonToken(Semicolon())
.WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ConstKeyword))); .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ConstKeyword)));
FieldDeclarationSyntax DeclareField(string type, string name, params SyntaxKind[] modifiers) => static FieldDeclarationSyntax DeclareField(string type, string name, params SyntaxKind[] modifiers) =>
DeclareField(type, name, null, modifiers); DeclareField(type, name, null, modifiers);
FieldDeclarationSyntax DeclareField(string type, string name, EqualsValueClauseSyntax? initializer, static FieldDeclarationSyntax DeclareField(string type, string name, EqualsValueClauseSyntax? initializer,
params SyntaxKind[] modifiers) => params SyntaxKind[] modifiers) =>
FieldDeclaration( FieldDeclaration(
VariableDeclaration(ParseTypeName(type), VariableDeclaration(ParseTypeName(type),

56
src/tools/DevGenerators/CompositionGenerator/Generator.cs

@ -35,16 +35,14 @@ namespace Avalonia.SourceGenerator.CompositionGenerator
GenerateAnimations(); GenerateAnimations();
} }
static string ServerName(string? c) => c != null ? ("Server" + c) : "ServerObject";
static string ChangesName(string? c) => c != null ? (c + "Changes") : "ChangeSet";
string ServerName(string? c) => c != null ? ("Server" + c) : "ServerObject"; static string ChangedFieldsTypeName(GClass c) => c.Name + "ChangedFields";
string ChangesName(string? c) => c != null ? (c + "Changes") : "ChangeSet"; static string ChangedFieldsFieldName(GClass c) => "_changedFieldsOf" + c.Name;
string ChangedFieldsTypeName(GClass c) => c.Name + "ChangedFields"; static string PropertyBackingFieldName(GProperty prop) => "_" + prop.Name.WithLowerFirst();
string ChangedFieldsFieldName(GClass c) => "_changedFieldsOf" + c.Name; static string CompositionPropertyField(GProperty prop) => "s_IdOf" + prop.Name + "Property";
string PropertyBackingFieldName(GProperty prop) => "_" + prop.Name.WithLowerFirst();
string CompositionPropertyField(GProperty prop) => "s_IdOf" + prop.Name + "Property"; static ExpressionSyntax ClientProperty(GClass c, GProperty p) =>
ExpressionSyntax ClientProperty(GClass c, GProperty p) =>
MemberAccess(ServerName(c.Name), CompositionPropertyField(p)); MemberAccess(ServerName(c.Name), CompositionPropertyField(p));
void GenerateClass(GClass cl) void GenerateClass(GClass cl)
@ -313,7 +311,7 @@ namespace Avalonia.SourceGenerator.CompositionGenerator
"Server", "Server" + cl.Name + ".generated.cs"); "Server", "Server" + cl.Name + ".generated.cs");
} }
private ClassDeclarationSyntax GenerateClientProperty(ClassDeclarationSyntax client, GClass cl, GProperty prop, private static ClassDeclarationSyntax GenerateClientProperty(ClassDeclarationSyntax client, GClass cl, GProperty prop,
TypeSyntax propType, bool isObject, bool isNullable) TypeSyntax propType, bool isObject, bool isNullable)
{ {
var fieldName = PropertyBackingFieldName(prop); var fieldName = PropertyBackingFieldName(prop);
@ -346,7 +344,7 @@ namespace Avalonia.SourceGenerator.CompositionGenerator
.AddModifiers(SyntaxKind.PartialKeyword).WithSemicolonToken(Semicolon())); .AddModifiers(SyntaxKind.PartialKeyword).WithSemicolonToken(Semicolon()));
} }
EnumDeclarationSyntax GenerateChangedFieldsEnum(GClass cl) static EnumDeclarationSyntax GenerateChangedFieldsEnum(GClass cl)
{ {
var changedFieldsEnum = EnumDeclaration(Identifier(ChangedFieldsTypeName(cl))); var changedFieldsEnum = EnumDeclaration(Identifier(ChangedFieldsTypeName(cl)));
int count = 0; int count = 0;
@ -373,7 +371,7 @@ namespace Avalonia.SourceGenerator.CompositionGenerator
.AddAttributeLists(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("System.Flags"))))); .AddAttributeLists(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("System.Flags")))));
} }
StatementSyntax GeneratePropertySetterAssignment(GClass cl, GProperty prop, bool isObject, bool isNullable) static StatementSyntax GeneratePropertySetterAssignment(GClass cl, GProperty prop, bool isObject, bool isNullable)
{ {
var code = @$" var code = @$"
// Update the backing value // Update the backing value
@ -406,8 +404,8 @@ namespace Avalonia.SourceGenerator.CompositionGenerator
return ParseStatement("{\n" + code + "\n}"); return ParseStatement("{\n" + code + "\n}");
} }
BlockSyntax ApplyStartAnimation(BlockSyntax body, GClass cl, GProperty prop) static BlockSyntax ApplyStartAnimation(BlockSyntax body, GClass cl, GProperty prop)
{ {
var code = $@" var code = $@"
if (propertyName == ""{prop.Name}"") if (propertyName == ""{prop.Name}"")
@ -437,8 +435,8 @@ return;
"Color", "Color",
"Avalonia.Media.Color" "Avalonia.Media.Color"
}; };
BlockSyntax ApplyGetProperty(BlockSyntax body, GProperty prop, string? expr = null) static BlockSyntax ApplyGetProperty(BlockSyntax body, GProperty prop, string? expr = null)
{ {
if (VariantPropertyTypes.Contains(prop.Type)) if (VariantPropertyTypes.Contains(prop.Type))
return body.AddStatements( return body.AddStatements(
@ -448,7 +446,7 @@ return;
return body; return body;
} }
private BlockSyntax SerializeChangesPrologue(GClass cl) private static BlockSyntax SerializeChangesPrologue(GClass cl)
{ {
return Block( return Block(
ParseStatement("base.SerializeChangesCore(writer);"), ParseStatement("base.SerializeChangesCore(writer);"),
@ -456,10 +454,10 @@ return;
); );
} }
private BlockSyntax SerializeChangesEpilogue(GClass cl) => private static BlockSyntax SerializeChangesEpilogue(GClass cl) =>
Block(ParseStatement(ChangedFieldsFieldName(cl) + " = default;")); Block(ParseStatement(ChangedFieldsFieldName(cl) + " = default;"));
BlockSyntax ApplySerializeField(BlockSyntax body, GClass cl, GProperty prop, bool isObject, bool isPassthrough) static BlockSyntax ApplySerializeField(BlockSyntax body, GClass cl, GProperty prop, bool isObject, bool isPassthrough)
{ {
var changedFields = ChangedFieldsFieldName(cl); var changedFields = ChangedFieldsFieldName(cl);
var changedFieldsType = ChangedFieldsTypeName(cl); var changedFieldsType = ChangedFieldsTypeName(cl);
@ -480,7 +478,7 @@ return;
return body.AddStatements(ParseStatement(code)); return body.AddStatements(ParseStatement(code));
} }
private BlockSyntax DeserializeChangesPrologue(GClass cl) private static BlockSyntax DeserializeChangesPrologue(GClass cl)
{ {
return Block(ParseStatement($@" return Block(ParseStatement($@"
base.DeserializeChangesCore(reader, commitedAt); base.DeserializeChangesCore(reader, commitedAt);
@ -489,12 +487,12 @@ var changed = reader.Read<{ChangedFieldsTypeName(cl)}>();
")); "));
} }
private BlockSyntax ApplyDeserializeChangesEpilogue(BlockSyntax body, GClass cl) private static BlockSyntax ApplyDeserializeChangesEpilogue(BlockSyntax body, GClass cl)
{ {
return body.AddStatements(ParseStatement("OnFieldsDeserialized(changed);")); return body.AddStatements(ParseStatement("OnFieldsDeserialized(changed);"));
} }
BlockSyntax ApplyDeserializeField(BlockSyntax body, GClass cl, GProperty prop, string serverType, bool isObject) static BlockSyntax ApplyDeserializeField(BlockSyntax body, GClass cl, GProperty prop, string serverType, bool isObject)
{ {
var changedFieldsType = ChangedFieldsTypeName(cl); var changedFieldsType = ChangedFieldsTypeName(cl);
var code = ""; var code = "";
@ -516,7 +514,7 @@ var changed = reader.Read<{ChangedFieldsTypeName(cl)}>();
return body.AddStatements(ParseStatement(code)); return body.AddStatements(ParseStatement(code));
} }
ClassDeclarationSyntax WithGetPropertyForAnimation(ClassDeclarationSyntax cl, BlockSyntax body) static ClassDeclarationSyntax WithGetPropertyForAnimation(ClassDeclarationSyntax cl, BlockSyntax body)
{ {
if (body.Statements.Count == 0) if (body.Statements.Count == 0)
return cl; return cl;
@ -528,8 +526,8 @@ var changed = reader.Read<{ChangedFieldsTypeName(cl)}>();
return cl.AddMembers(method); return cl.AddMembers(method);
} }
ClassDeclarationSyntax WithGetCompositionProperty(ClassDeclarationSyntax cl, BlockSyntax body) static ClassDeclarationSyntax WithGetCompositionProperty(ClassDeclarationSyntax cl, BlockSyntax body)
{ {
if (body.Statements.Count == 0) if (body.Statements.Count == 0)
return cl; return cl;
@ -542,7 +540,7 @@ var changed = reader.Read<{ChangedFieldsTypeName(cl)}>();
return cl.AddMembers(method); return cl.AddMembers(method);
} }
ClassDeclarationSyntax WithStartAnimation(ClassDeclarationSyntax cl, BlockSyntax body) static ClassDeclarationSyntax WithStartAnimation(ClassDeclarationSyntax cl, BlockSyntax body)
{ {
body = body.AddStatements( body = body.AddStatements(
ExpressionStatement(InvocationExpression(MemberAccess("base", "StartAnimation"), ExpressionStatement(InvocationExpression(MemberAccess("base", "StartAnimation"),

2
tests/Avalonia.Base.UnitTests/Data/Core/ExpressionObserverTests_Lifetime.cs

@ -104,7 +104,7 @@ namespace Avalonia.Base.UnitTests.Data.Core
GC.KeepAlive(data); GC.KeepAlive(data);
} }
private Recorded<Notification<T>> OnNext<T>(long time, T value) private static Recorded<Notification<T>> OnNext<T>(long time, T value)
{ {
return new Recorded<Notification<T>>(time, Notification.CreateOnNext<T>(value)); return new Recorded<Notification<T>>(time, Notification.CreateOnNext<T>(value));
} }

2
tests/Avalonia.Base.UnitTests/Data/Core/ExpressionObserverTests_Property.cs

@ -730,7 +730,7 @@ namespace Avalonia.Base.UnitTests.Data.Core
{ {
} }
private Recorded<Notification<T>> OnNext<T>(long time, T value) private static Recorded<Notification<T>> OnNext<T>(long time, T value)
{ {
return new Recorded<Notification<T>>(time, Notification.CreateOnNext<T>(value)); return new Recorded<Notification<T>>(time, Notification.CreateOnNext<T>(value));
} }

2
tests/Avalonia.Base.UnitTests/Data/Core/ExpressionObserverTests_Task.cs

@ -143,7 +143,7 @@ namespace Avalonia.Base.UnitTests.Data.Core
} }
} }
private Task TaskFromException(Exception e) private static Task TaskFromException(Exception e)
{ {
var tcs = new TaskCompletionSource<object>(); var tcs = new TaskCompletionSource<object>();
tcs.SetException(e); tcs.SetException(e);

2
tests/Avalonia.Base.UnitTests/Input/GesturesTests.cs

@ -167,7 +167,7 @@ namespace Avalonia.Base.UnitTests.Input
Assert.False(raised); Assert.False(raised);
} }
private void AddHandlers( private static void AddHandlers(
Decorator decorator, Decorator decorator,
Border border, Border border,
IList<string> result, IList<string> result,

2
tests/Avalonia.Base.UnitTests/Interactivity/InteractiveTests.cs

@ -378,7 +378,7 @@ namespace Avalonia.Base.UnitTests.Interactivity
Assert.Equal(new[] { "3", "2b", "1" }, invoked); Assert.Equal(new[] { "3", "2b", "1" }, invoked);
} }
private TestInteractive CreateTree( private static TestInteractive CreateTree(
RoutedEvent ev, RoutedEvent ev,
EventHandler<RoutedEventArgs> handler, EventHandler<RoutedEventArgs> handler,
RoutingStrategies handlerRoutes, RoutingStrategies handlerRoutes,

12
tests/Avalonia.Base.UnitTests/Layout/LayoutableTests_EffectiveViewportChanged.cs

@ -336,21 +336,21 @@ namespace Avalonia.Base.UnitTests.Layout
}); });
} }
private TestRoot CreateRoot() => new TestRoot { Width = 1200, Height = 900 }; private static TestRoot CreateRoot() => new TestRoot { Width = 1200, Height = 900 };
private Task ExecuteInitialLayoutPass(TestRoot root) private static Task ExecuteInitialLayoutPass(TestRoot root)
{ {
root.LayoutManager.ExecuteInitialLayoutPass(); root.LayoutManager.ExecuteInitialLayoutPass();
return Task.CompletedTask; return Task.CompletedTask;
} }
private Task ExecuteLayoutPass(TestRoot root) private static Task ExecuteLayoutPass(TestRoot root)
{ {
root.LayoutManager.ExecuteLayoutPass(); root.LayoutManager.ExecuteLayoutPass();
return Task.CompletedTask; return Task.CompletedTask;
} }
private Task ExecuteScrollerLayoutPass( private static Task ExecuteScrollerLayoutPass(
TestRoot root, TestRoot root,
ScrollViewer scroller, ScrollViewer scroller,
Control target, Control target,
@ -365,7 +365,7 @@ namespace Avalonia.Base.UnitTests.Layout
root.LayoutManager.ExecuteLayoutPass(); root.LayoutManager.ExecuteLayoutPass();
return Task.CompletedTask; return Task.CompletedTask;
} }
private IControlTemplate ScrollViewerTemplate() private static IControlTemplate ScrollViewerTemplate()
{ {
return new FuncControlTemplate<ScrollViewer>((control, scope) => new Grid return new FuncControlTemplate<ScrollViewer>((control, scope) => new Grid
{ {
@ -415,7 +415,7 @@ namespace Avalonia.Base.UnitTests.Layout
}); });
} }
private void AssertArePixelEqual(Rect expected, Rect actual) private static void AssertArePixelEqual(Rect expected, Rect actual)
{ {
var expectedRounded = new Rect((int)expected.X, (int)expected.Y, (int)expected.Width, (int)expected.Height); var expectedRounded = new Rect((int)expected.X, (int)expected.Y, (int)expected.Width, (int)expected.Height);
var actualRounded = new Rect((int)actual.X, (int)actual.Y, (int)actual.Width, (int)actual.Height); var actualRounded = new Rect((int)actual.X, (int)actual.Y, (int)actual.Width, (int)actual.Height);

2
tests/Avalonia.Base.UnitTests/Layout/NonVirtualizingStackLayoutTests.cs

@ -310,7 +310,7 @@ namespace Avalonia.Base.UnitTests.Layout
Assert.Equal(new Size(10, 10), arrangeSize); Assert.Equal(new Size(10, 10), arrangeSize);
} }
private NonVirtualizingLayoutContext CreateContext(Control[] children) private static NonVirtualizingLayoutContext CreateContext(Control[] children)
{ {
return new TestLayoutContext(children); return new TestLayoutContext(children);
} }

4
tests/Avalonia.Base.UnitTests/MatrixTests.cs

@ -19,7 +19,7 @@ public class MatrixTests
/// </summary> /// </summary>
/// <param name="expected">The expected vector</param> /// <param name="expected">The expected vector</param>
/// <param name="actual">The actual transformed point</param> /// <param name="actual">The actual transformed point</param>
private void AssertCoordinatesEqualWithReducedPrecision(Vector2 expected, Point actual) private static void AssertCoordinatesEqualWithReducedPrecision(Vector2 expected, Point actual)
{ {
double ReducePrecision(double input) => Math.Truncate(input * 10000); double ReducePrecision(double input) => Math.Truncate(input * 10000);
@ -86,7 +86,7 @@ public class MatrixTests
var matrix = Matrix.CreateSkew(30, 20); var matrix = Matrix.CreateSkew(30, 20);
var point = new Point(1, 1); var point = new Point(1, 1);
var actual = matrix.Transform(point); var actual = matrix.Transform(point);
AssertCoordinatesEqualWithReducedPrecision(expected, actual); AssertCoordinatesEqualWithReducedPrecision(expected, actual);
} }
} }

2
tests/Avalonia.Base.UnitTests/Media/RectangleGeometryTests.cs

@ -23,7 +23,7 @@ namespace Avalonia.Base.UnitTests.Media
} }
} }
private TestServices GetServices() private static TestServices GetServices()
{ {
var context = Mock.Of<IStreamGeometryContextImpl>(); var context = Mock.Of<IStreamGeometryContextImpl>();
var transformedGeometry = new Mock<ITransformedGeometryImpl>(); var transformedGeometry = new Mock<ITransformedGeometryImpl>();

2
tests/Avalonia.Base.UnitTests/Rendering/CompositorHitTestingTests.cs

@ -460,7 +460,7 @@ public class CompositorHitTestingTests : CompositorTestsBase
} }
} }
private IDisposable TestApplication() private static IDisposable TestApplication()
{ {
return UnitTestApplication.Start(TestServices.MockPlatformRenderInterface); return UnitTestApplication.Start(TestServices.MockPlatformRenderInterface);
} }

2
tests/Avalonia.Base.UnitTests/Rendering/DeferredRendererTests_HitTesting.cs

@ -569,7 +569,7 @@ namespace Avalonia.Base.UnitTests.Rendering
} }
} }
private IDisposable TestApplication() private static IDisposable TestApplication()
{ {
return UnitTestApplication.Start(TestServices.MockPlatformRenderInterface); return UnitTestApplication.Start(TestServices.MockPlatformRenderInterface);
} }

2
tests/Avalonia.Base.UnitTests/Rendering/ImmediateRendererTests_HitTesting.cs

@ -450,7 +450,7 @@ namespace Avalonia.Base.UnitTests.Rendering
} }
} }
private IDisposable TestApplication() private static IDisposable TestApplication()
{ {
return UnitTestApplication.Start(TestServices.MockPlatformRenderInterface); return UnitTestApplication.Start(TestServices.MockPlatformRenderInterface);
} }

2
tests/Avalonia.Base.UnitTests/Styling/StyledElementTests_Resources.cs

@ -198,7 +198,7 @@ namespace Avalonia.Base.UnitTests.Styling
Assert.True(raised); Assert.True(raised);
} }
private IControlTemplate ContentControlTemplate() private static IControlTemplate ContentControlTemplate()
{ {
return new FuncControlTemplate<ContentControl>((x, scope) => return new FuncControlTemplate<ContentControl>((x, scope) =>
new ContentPresenter new ContentPresenter

2
tests/Avalonia.Base.UnitTests/VisualTree/VisualExtensions_GetVisualsAt.cs

@ -96,7 +96,7 @@ namespace Avalonia.Base.UnitTests.VisualTree
} }
} }
private IDisposable TestApplication() private static IDisposable TestApplication()
{ {
return UnitTestApplication.Start(TestServices.MockPlatformRenderInterface); return UnitTestApplication.Start(TestServices.MockPlatformRenderInterface);
} }

2
tests/Avalonia.Base.UnitTests/WeakEventHandlerManagerTests.cs

@ -79,7 +79,7 @@ namespace Avalonia.Base.UnitTests
Assert.False(handled); Assert.False(handled);
} }
private void AddCollectableSubscriber(EventSource source, string name, Action func) private static void AddCollectableSubscriber(EventSource source, string name, Action func)
{ {
WeakEventHandlerManager.Subscribe<EventSource, EventArgs, Subscriber>(source, name, new Subscriber(func).OnEvent); WeakEventHandlerManager.Subscribe<EventSource, EventArgs, Subscriber>(source, name, new Subscriber(func).OnEvent);
} }

2
tests/Avalonia.Base.UnitTests/WeakEventTests.cs

@ -67,7 +67,7 @@ namespace Avalonia.Base.UnitTests
Assert.False(handled); Assert.False(handled);
} }
private void AddSubscriber(EventSource source, Action func) private static void AddSubscriber(EventSource source, Action func)
{ {
EventSource.WeakEv.Subscribe(source, new Subscriber(func)); EventSource.WeakEv.Subscribe(source, new Subscriber(func));
} }

2
tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs

@ -455,7 +455,7 @@ namespace Avalonia.Controls.UnitTests
/// Creates a large list of strings for AutoCompleteBox testing. /// Creates a large list of strings for AutoCompleteBox testing.
/// </summary> /// </summary>
/// <returns>Returns a new List of string values.</returns> /// <returns>Returns a new List of string values.</returns>
private IList<string> CreateSimpleStringArray() private static IList<string> CreateSimpleStringArray()
{ {
return new List<string> return new List<string>
{ {

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save