From 16945e35a09ff2efb962a732ef8452da64b891ed Mon Sep 17 00:00:00 2001 From: indigo-san Date: Sun, 31 Dec 2023 18:09:16 +0900 Subject: [PATCH 1/4] =?UTF-8?q?=E3=83=97=E3=83=A9=E3=82=A4=E3=83=9E?= =?UTF-8?q?=E3=83=AA=E3=82=B3=E3=83=B3=E3=82=B9=E3=83=88=E3=83=A9=E3=82=AF?= =?UTF-8?q?=E3=82=BF=E3=80=81=E3=82=B3=E3=83=AC=E3=82=AF=E3=82=B7=E3=83=A7?= =?UTF-8?q?=E3=83=B3=E3=83=AA=E3=83=86=E3=83=A9=E3=83=AB=E3=82=92=E4=BD=BF?= =?UTF-8?q?=E3=81=86=E3=82=88=E3=81=86=E3=81=AB=E3=81=97=E3=81=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .editorconfig | 2 +- .../generators/ResourcesGenerator/Program.cs | 36 ++--- nukebuild/Build.cs | 12 +- src/Beutl.Api/BeutlApiApplication.cs | 2 +- src/Beutl.Api/MyAsyncLock.cs | 11 +- src/Beutl.Api/Objects/AuthorizedUser.cs | 36 ++--- .../Services/AcceptedLicenseManager.cs | 2 +- src/Beutl.Api/Services/DiscoverService.cs | 49 +++--- src/Beutl.Api/Services/ExtensionProvider.cs | 6 +- .../Services/ExtensionSettingsStore.cs | 2 +- .../Services/InstalledPackageRepository.cs | 6 +- src/Beutl.Api/Services/LibraryService.cs | 33 ++-- src/Beutl.Api/Services/LocalPackage.cs | 4 +- src/Beutl.Api/Services/PackageChangesQueue.cs | 4 +- src/Beutl.Api/Services/PackageCleanContext.cs | 12 +- .../Services/PackageInstallContext.cs | 15 +- .../Services/PackageInstaller.Clean.cs | 2 +- .../Services/PackageInstaller.Uninstall.cs | 2 +- src/Beutl.Api/Services/PackageInstaller.cs | 8 +- src/Beutl.Api/Services/PackageLoader.cs | 5 +- src/Beutl.Api/Services/PackageManager.cs | 31 ++-- src/Beutl.Api/Services/PackageUpdate.cs | 15 +- .../Services/PluginDependencyResolver.cs | 6 +- src/Beutl.Api/Services/PluginLoadContext.cs | 12 +- .../LibraryNameValidation.cs | 12 +- src/Beutl.Configuration/ExtensionConfig.cs | 13 +- src/Beutl.Configuration/FontConfig.cs | 10 +- src/Beutl.Configuration/ViewConfig.cs | 10 +- src/Beutl.Controls/DirectoryTreeView.cs | 18 +-- .../PropertyEditors/AlignmentXEditor.cs | 2 +- .../PropertyEditors/AlignmentYEditor.cs | 2 +- .../PropertyEditors/DataValidationMessages.cs | 4 +- .../PropertyEditors/NumberEditor.cs | 2 +- .../PropertyEditors/RelativePointEditor.cs | 2 +- .../PropertyEditors/StringEditor.cs | 2 +- .../PropertyEditors/Vector2Editor.cs | 4 +- .../PropertyEditors/Vector3Editor.cs | 4 +- .../PropertyEditors/Vector4Editor.cs | 4 +- src/Beutl.Core/CollectionBatchExtension.cs | 69 +++----- src/Beutl.Core/Collections/CoreDictionary.cs | 4 +- src/Beutl.Core/Collections/CoreList.cs | 23 +-- .../NotifyCollectionChangedExtensions.cs | 16 +- .../Collections/Pooled/PooledList.cs | 13 +- src/Beutl.Core/Collections/PooledArray.cs | 23 +-- src/Beutl.Core/CommandExecutedEventArgs.cs | 12 +- src/Beutl.Core/Commands/AddCommand.cs | 15 +- src/Beutl.Core/Commands/AddCommand{T}.cs | 15 +- .../Commands/ChangePropertyCommand.cs | 18 +-- .../Commands/ChangePropertyCommand{T}.cs | 18 +-- src/Beutl.Core/Commands/MoveCommand.cs | 33 ++-- src/Beutl.Core/Commands/MoveCommand{T}.cs | 41 ++--- src/Beutl.Core/CoreObject.cs | 6 +- src/Beutl.Core/CoreObjectExtensions.cs | 20 +-- src/Beutl.Core/CoreProperty.cs | 21 +-- src/Beutl.Core/CorePropertyBuilder.cs | 4 +- .../CorePropertyChangedEventArgs.cs | 41 +++-- .../Hierarchy/HierarchyAttachmentEventArgs.cs | 12 +- src/Beutl.Core/IRecordableCommand.cs | 44 ++---- src/Beutl.Core/JsonHelper.cs | 2 +- src/Beutl.Core/NotifiableAttribute.cs | 9 +- src/Beutl.Core/OnceEnumerable.cs | 22 +-- src/Beutl.Core/Optional.cs | 28 ++-- src/Beutl.Core/Project.cs | 2 +- src/Beutl.Core/ProjectItemContainer.cs | 2 +- src/Beutl.Core/PropertyChangeTracker.cs | 23 +-- src/Beutl.Core/PropertyRegistry.cs | 14 +- src/Beutl.Core/Rational.cs | 12 +- .../Reactive/LightweightObservableBase.cs | 8 +- src/Beutl.Core/RingStack.cs | 23 +-- .../Serialization/ArrayTypeHelpers.cs | 4 +- .../Serialization/DummyTypeAttribute.cs | 9 +- .../Serialization/JsonSerializationContext.cs | 25 ++- .../RelaySerializationErrorNotifier.cs | 12 +- .../SerializationErrorCollector.cs | 2 +- .../Serialization/StringValuePair.cs | 25 +-- src/Beutl.Core/Services/LibraryService.cs | 48 ++---- src/Beutl.Core/StaticProperty.cs | 22 +-- src/Beutl.Core/TypeFormat.cs | 40 ++--- .../Validation/MultipleValidator.cs | 9 +- .../Validation/ValidationContext.cs | 12 +- src/Beutl.Engine/Animation/Animatable.cs | 2 +- .../Animation/AnimatorRegistry.cs | 6 +- .../Animation/KeyFrameAnimation.cs | 2 +- src/Beutl.Engine/Audio/Effects/Delay.cs | 16 +- .../Audio/Effects/SoundEffectGroup.cs | 2 +- .../Audio/Effects/SoundProcessorGroup.cs | 4 +- .../Audio/Platforms/XAudio2/XAudioSource.cs | 10 +- src/Beutl.Engine/Audio/SoundNode.cs | 9 +- src/Beutl.Engine/Graphics/BrushConstructor.cs | 18 +-- src/Beutl.Engine/Graphics/ColorMatrix.cs | 123 +++++---------- src/Beutl.Engine/Graphics/CubeFile.cs | 6 +- src/Beutl.Engine/Graphics/DrawableGroup.cs | 3 +- .../Graphics/FilterEffects/DynamicEnumTest.cs | 16 +- .../FilterEffects/FilterEffectContext.cs | 13 +- .../FilterEffects/FilterEffectGroup.cs | 2 +- src/Beutl.Engine/Graphics/Matrix.cs | 82 ++++------ .../Graphics/Operations/AlphaMapOperation.cs | 13 +- .../Operations/AlphaSubtractOperation.cs | 13 +- .../Graphics/Operations/ConvertOperation.cs | 15 +- .../Graphics/Operations/CropOperation.cs | 19 +-- .../Graphics/Operations/ReplaceOperation.cs | 17 +- src/Beutl.Engine/Graphics/Point.cs | 21 +-- src/Beutl.Engine/Graphics/Rect.cs | 6 +- src/Beutl.Engine/Graphics/RelativePoint.cs | 22 +-- src/Beutl.Engine/Graphics/RelativeRect.cs | 2 +- .../Graphics/Rendering/BlendModeNode.cs | 9 +- .../Graphics/Rendering/ClearNode.cs | 10 +- .../Graphics/Rendering/ContainerNode.cs | 2 +- .../Graphics/Rendering/DeferradCanvas.cs | 38 ++--- .../Graphics/Rendering/DrawableNode.cs | 9 +- .../Graphics/Rendering/EllipseNode.cs | 11 +- .../Graphics/Rendering/FilterEffectNode.cs | 9 +- .../Graphics/Rendering/GeometryClipNode.cs | 15 +- .../Graphics/Rendering/GeometryNode.cs | 14 +- .../Graphics/Rendering/ImageSourceNode.cs | 11 +- .../Graphics/Rendering/LayerNode.cs | 9 +- .../Graphics/Rendering/OpacityMaskNode.cs | 15 +- .../Graphics/Rendering/RectClipNode.cs | 12 +- .../Graphics/Rendering/RectangleNode.cs | 11 +- .../Graphics/Rendering/RenderSceneBrush.cs | 16 +- .../Graphics/Rendering/TextNode.cs | 11 +- .../Graphics/Rendering/TransformNode.cs | 12 +- .../Graphics/Rendering/VideoSourceNode.cs | 15 +- src/Beutl.Engine/Graphics/Shapes/TextBlock.cs | 2 +- .../Graphics/Shapes/TextElementsBuilder.cs | 61 +++----- src/Beutl.Engine/Graphics/Size.cs | 22 +-- .../Graphics/Transformation/TransformGroup.cs | 2 +- .../Transformation/TransformParser.cs | 29 ++-- src/Beutl.Engine/Graphics/Vector.cs | 21 +-- src/Beutl.Engine/Media/Bitmap.cs | 18 +-- .../Media/Brushes/GradientBrush.cs | 2 +- src/Beutl.Engine/Media/Color.cs | 17 +- .../Media/Decoding/DecoderRegistry.cs | 4 +- .../Media/Encoding/EncoderRegistry.cs | 2 +- src/Beutl.Engine/Media/Font/FontFamily.cs | 9 +- src/Beutl.Engine/Media/Font/FontManager.cs | 6 +- src/Beutl.Engine/Media/Font/Typeface.cs | 19 +-- .../Media/Geometry/PathGeometry.cs | 2 +- .../Media/Immutable/ImmutableGradientStop.cs | 12 +- .../Media/Immutable/ImmutablePen.cs | 47 +++--- .../Immutable/ImmutablePerlinNoiseBrush.cs | 47 +++--- .../Immutable/ImmutableSolidColorBrush.cs | 20 +-- .../Media/Immutable/ImmutableTransform.cs | 12 +- src/Beutl.Engine/Media/KnownColors.cs | 2 +- src/Beutl.Engine/Media/Music/Sample.cs | 12 +- .../Music/Samples/Monaural16BitInteger.cs | 9 +- .../Media/Music/Samples/Monaural32BitFloat.cs | 9 +- .../Music/Samples/Monaural32BitInteger.cs | 9 +- .../Media/Music/Samples/Stereo16BitInteger.cs | 12 +- .../Media/Music/Samples/Stereo32BitFloat.cs | 12 +- .../Media/Music/Samples/Stereo32BitInteger.cs | 12 +- src/Beutl.Engine/Media/Pixel/Bgr565.cs | 9 +- src/Beutl.Engine/Media/Pixel/Bgr888.cs | 15 +- src/Beutl.Engine/Media/Pixel/Bgra4444.cs | 9 +- src/Beutl.Engine/Media/Pixel/Bgra8888.cs | 18 +-- src/Beutl.Engine/Media/Pixel/Grayscale8.cs | 9 +- src/Beutl.Engine/Media/PixelPoint.cs | 22 +-- src/Beutl.Engine/Media/PixelSize.cs | 22 +-- src/Beutl.Engine/Media/Source/SoundSource.cs | 33 ++-- .../TextFormatting/FormattedTextTokenizer.cs | 17 +- .../Rendering/Cache/RenderCache.cs | 9 +- .../Rendering/Cache/RenderCacheContext.cs | 2 +- src/Beutl.Engine/Rendering/FpsText.cs | 43 ++--- .../Rendering/GlContexts/Cgl/CglContext.cs | 8 +- .../Rendering/GlContexts/Glx/Glx.cs | 4 +- .../Rendering/GlContexts/Glx/GlxContext.cs | 10 +- .../Rendering/GlContexts/Wgl/Wgl.cs | 2 +- .../Rendering/GlContexts/Wgl/WglContext.cs | 8 +- src/Beutl.Engine/Rendering/RenderLayer.cs | 28 +--- src/Beutl.Engine/Rendering/RenderScene.cs | 11 +- src/Beutl.Engine/Styling/SetterInstance.cs | 12 +- src/Beutl.Engine/Styling/Style.cs | 2 +- src/Beutl.Engine/Styling/StyleInstance.cs | 21 +-- src/Beutl.Engine/Styling/StyleSerializer.cs | 7 +- src/Beutl.Engine/Styling/Styleable.cs | 2 +- src/Beutl.Extensibility/IAbstractProperty.cs | 25 +-- .../Decoding/FFmpegDecoderInfo.cs | 11 +- .../Decoding/FFmpegReader.cs | 4 +- .../Encoding/FFmpegWriter.cs | 4 +- src/Beutl.Language/LocalizeService.cs | 4 +- .../Configure/AnimatableCorePropertyImpl.cs | 31 ++-- .../Configure/CorePropertyImpl.cs | 12 +- .../Configure/Effects/FilterEffectOperator.cs | 2 +- .../Configure/Transform/TransformOperator.cs | 2 +- src/Beutl.PackageTools/KurukuruProgress.cs | 13 +- .../PackageIdArgumentParser.cs | 12 +- src/Beutl.PackageTools/UninstallCommand.cs | 4 +- .../ChangeSetterValueCommand.cs | 17 +- .../NodeTree/Connection.cs | 12 +- .../NodeTree/ElementNodeTreeModel.cs | 4 +- src/Beutl.ProjectSystem/NodeTree/NodeGroup.cs | 2 +- .../NodeTree/NodeRegistry.cs | 4 +- .../Nodes/Brushes/GradientBrushNode.cs | 2 +- .../NodeTree/Nodes/ConfigureNode.cs | 12 +- .../Nodes/Filters/FilterEffectNode.cs | 9 +- .../NodeTree/Nodes/Group/GroupNode.cs | 6 +- .../NodeTree/Nodes/Transform/TransformNode.cs | 9 +- .../NodeTree/OutputSocket.cs | 2 +- .../NodeTree/SetterPropertyImpl.cs | 18 +-- .../SocketConnectionChangedEventArgs.cs | 12 +- .../Operation/CorePropertyImpl.cs | 12 +- .../Operation/SourceStyler.cs | 12 +- .../Operation/StylingOperator.cs | 20 +-- .../ProjectSystem/Elements.cs | 11 +- .../ProjectSystem/Scene.cs | 148 ++++++------------ src/Beutl.ProjectSystem/SceneComposer.cs | 18 +-- .../SceneGraphicsEvaluator.cs | 28 ++-- src/Beutl.Threading/OperationQueue.cs | 6 +- src/Beutl.Threading/TimerQueue.cs | 4 +- src/Beutl.Threading/YieldTask.cs | 24 +-- .../PooledArrayBufferWriter.cs | 4 +- src/Beutl.Utilities/StringFormats.cs | 2 +- src/Beutl.Utilities/WeakEvent.cs | 2 +- src/Beutl/AppHelpers.cs | 6 +- src/Beutl/Beutl.csproj | 5 + src/Beutl/Helpers/BindingHelper.cs | 31 +--- src/Beutl/Helpers/ColorGenerator.cs | 2 +- src/Beutl/Pages/EditPage.axaml.cs | 2 +- src/Beutl/Pages/ExtensionsPage.axaml.cs | 6 +- src/Beutl/Pages/OutputPage.axaml.cs | 2 +- src/Beutl/Pages/SettingsPage.axaml.cs | 6 +- src/Beutl/Services/ObjectSearcher.cs | 2 +- src/Beutl/Services/OutputService.cs | 11 +- src/Beutl/Services/PropertyEditorService.cs | 6 +- .../AfterLoadingExtensionsTask.cs | 2 +- .../LoadInstalledExtensionTask.cs | 2 +- .../LoadPrimitiveExtensionTask.cs | 12 +- .../StartupTasks/LoadSideloadExtensionTask.cs | 2 +- src/Beutl/Services/StartupTasks/Startup.cs | 2 +- src/Beutl/Services/Telemetry.cs | 2 +- .../Dialogs/SelectAssetViewModel.cs | 2 +- .../Dialogs/SelectImageAssetViewModel.cs | 2 +- .../SelectLibraryItemDialogViewModel.cs | 6 +- src/Beutl/ViewModels/EditViewModel.cs | 40 ++--- .../Editors/AlignmentXEditorViewModel.cs | 7 +- .../Editors/AlignmentYEditorViewModel.cs | 7 +- .../ViewModels/Editors/BaseEditorViewModel.cs | 51 ++---- .../Editors/BooleanEditorViewModel.cs | 7 +- .../Editors/BrushEditorViewModel.cs | 17 +- .../Editors/DynamicEnumEditorViewModel.cs | 4 +- .../ViewModels/Editors/EnumEditorViewModel.cs | 7 +- .../Editors/FontFamilyEditorViewModel.cs | 7 +- .../Editors/GradientStopsEditorViewModel.cs | 4 +- .../Editors/ImageSourceEditorViewModel.cs | 48 ++---- .../ViewModels/Editors/ListEditorViewModel.cs | 2 +- .../Editors/NumberEditorViewModel.cs | 7 +- .../ViewModels/Editors/PenEditorViewModel.cs | 4 +- .../Editors/PropertiesEditorViewModel.cs | 4 +- .../Editors/PropertyEditorGroupContext.cs | 25 +-- .../Editors/SoundSourceEditorViewModel.cs | 48 ++---- .../Editors/StringEditorViewModel.cs | 7 +- .../Editors/VideoSourceEditorViewModel.cs | 48 ++---- src/Beutl/ViewModels/ElementScopeViewModel.cs | 2 +- src/Beutl/ViewModels/ElementViewModel.cs | 2 +- .../ViewModels/ExtensionsPageViewModel.cs | 4 +- .../ExtensionsPages/DevelopPageViewModel.cs | 4 +- .../DevelopPages/DataContextFactory.cs | 25 ++- .../PackageDetailsPageViewModel.cs | 2 +- .../PackageReleasesPageViewModel.cs | 2 +- .../PackageSettingsPageViewModel.cs | 4 +- .../DevelopPages/ReleasePageViewModel.cs | 2 +- .../ExtensionsPages/DiscoverPageViewModel.cs | 8 +- .../DiscoverPages/DataContextFactory.cs | 17 +- .../PublicPackageDetailsPageViewModel.cs | 4 +- .../DiscoverPages/RankingPageViewModel.cs | 10 +- .../DiscoverPages/SearchPageViewModel.cs | 6 +- .../DiscoverPages/UserProfilePageViewModel.cs | 4 +- .../ExtensionsPages/LibraryPageViewModel.cs | 6 +- .../LocalYourPackageViewModel.cs | 2 +- .../RemoteYourPackageViewModel.cs | 2 +- .../GraphEditorKeyFrameViewModel.cs | 65 +++----- src/Beutl/ViewModels/GraphEditorViewModel.cs | 26 +-- .../ViewModels/GraphEditorViewViewModel.cs | 4 +- .../GraphEditorViewViewModelFactory.Impl.cs | 72 ++++----- .../GraphEditorViewViewModelFactory.Impl.tt | 18 +-- .../GraphEditorViewViewModelFactory.cs | 18 +-- .../InlineAnimationLayerViewModel.cs | 44 ++---- .../ViewModels/InlineKeyFrameViewModel.cs | 2 +- src/Beutl/ViewModels/LayerHeaderViewModel.cs | 15 +- src/Beutl/ViewModels/LibraryViewModel.cs | 10 +- src/Beutl/ViewModels/MainViewModel.cs | 6 +- .../ViewModels/MenuBarViewModel.Files.cs | 4 +- .../ViewModels/NodeTree/NodeInputViewModel.cs | 4 +- .../NodeTree/NodeTreeInputTabViewModel.cs | 2 +- .../NodeTree/NodeTreeInputViewModel.cs | 4 +- .../NodeTree/NodeTreeTabViewModel.cs | 4 +- .../ViewModels/NodeTree/NodeTreeViewModel.cs | 4 +- .../ViewModels/NodeTree/NodeViewModel.cs | 4 +- .../NodeTree/OutputSocketViewModel.cs | 8 +- .../ViewModels/NodeTree/SocketViewModel.cs | 30 +--- src/Beutl/ViewModels/PlayerViewModel.cs | 2 +- .../AccountSettingsPageViewModel.cs | 2 +- .../AnExtensionSettingsPageViewModel.cs | 4 +- .../EditorExtensionPriorityPageViewModel.cs | 6 +- .../StorageDetailPageViewModel.cs | 2 +- .../TelemetrySettingsPageViewModel.cs | 2 +- .../ViewSettingsPageViewModel.cs | 8 +- src/Beutl/ViewModels/TimelineViewModel.cs | 44 +++--- .../Tools/ObjectPropertyEditorViewModel.cs | 2 +- .../Tools/SceneSettingsTabViewModel.cs | 28 +--- .../Tools/SourceOperatorViewModel.cs | 23 +-- .../Tools/SourceOperatorsTabViewModel.cs | 2 +- src/Beutl/Views/Cache.cs | 9 +- .../Views/EditView.axaml.MouseControl.cs | 18 +-- src/Beutl/Views/EditView.axaml.cs | 6 +- src/Beutl/Views/Editors/ListEditor.axaml.cs | 6 +- .../Views/Editors/NavigateButton.axaml.cs | 4 +- src/Beutl/Views/ElementView.axaml.cs | 4 +- src/Beutl/Views/GraphEditorView.axaml.cs | 2 +- src/Beutl/Views/LayerHeader.axaml.cs | 8 +- .../Views/MainView.axaml.InitializeMenuBar.cs | 4 +- .../Views/MainView.axaml.InitializePages.cs | 2 +- src/Beutl/Views/MainView.axaml.cs | 2 +- .../Views/NodeTree/NodeTreeView.axaml.cs | 4 +- src/Beutl/Views/NodeTree/SocketPoint.cs | 12 +- src/Beutl/Views/NodeTree/SocketView.axaml.cs | 2 +- src/Beutl/Views/Timeline.axaml.cs | 4 +- .../Views/Tools/SceneSettingsTab.axaml.cs | 2 +- .../Views/Tools/SourceOperatorView.axaml.cs | 6 +- tests/Beutl.Engine.UnitTests/ShapeTests.cs | 5 +- tests/Beutl.Engine.UnitTests/StyleTests.cs | 13 +- .../TextElementsTests.cs | 6 +- .../TypefaceProvider.cs | 6 +- tests/KeySplineEditor/MainWindow.axaml.cs | 17 +- .../EditWellKnownSizeTabViewModel.cs | 17 +- .../WellKnownSizesProvider.cs | 6 +- tests/PackageSample/SSETExtenison.cs | 12 +- tests/PackageSample/SampleEditorExtension.cs | 8 +- tests/PackageSample/SamplePageExtension.cs | 6 +- 329 files changed, 1465 insertions(+), 2908 deletions(-) diff --git a/.editorconfig b/.editorconfig index 8d493fcb4..e5ff807e5 100644 --- a/.editorconfig +++ b/.editorconfig @@ -39,7 +39,7 @@ csharp_indent_switch_labels = true csharp_indent_labels = one_less_than_current # Modifier preferences -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion +csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async:suggestion # avoid this. unless absolutely necessary dotnet_style_qualification_for_field = false:suggestion diff --git a/build/generators/ResourcesGenerator/Program.cs b/build/generators/ResourcesGenerator/Program.cs index 1b69b329d..b9593aef9 100644 --- a/build/generators/ResourcesGenerator/Program.cs +++ b/build/generators/ResourcesGenerator/Program.cs @@ -95,7 +95,7 @@ List GetOrCreate(string key, Dictionary(); + value = []; dict[key] = value; return value; } @@ -186,9 +186,9 @@ namespace ResourcesGenerator { public class HierarchizedList { - public List Items { get; set; } = new(); + public List Items { get; set; } = []; - public Dictionary Children { get; } = new(); + public Dictionary Children { get; } = []; } public interface IResourceItem @@ -204,20 +204,13 @@ public interface IResourceItem void GenerateGetObservableCode(Span indentStr, StringBuilder sb, string rootNamespace, Dictionary redirects); } - public class StaticResource : IResourceItem + public class StaticResource(string rawKey, string key, string target) : IResourceItem { - public StaticResource(string rawKey, string key, string target) - { - RawKey = rawKey; - Key = key; - Target = target; - } - - public string RawKey { get; set; } + public string RawKey { get; set; } = rawKey; - public string Key { get; set; } + public string Key { get; set; } = key; - public string Target { get; set; } + public string Target { get; set; } = target; public void GenerateGetObservableCode(Span indentStr, StringBuilder sb, string rootNamespace, Dictionary redirects) { @@ -249,20 +242,13 @@ public string GetPath() } } - public class StringResource : IResourceItem + public class StringResource(string rawKey, string key, string value) : IResourceItem { - public StringResource(string rawKey, string key, string value) - { - RawKey = rawKey; - Key = key; - Value = value; - } - - public string RawKey { get; set; } + public string RawKey { get; set; } = rawKey; - public string Key { get; set; } + public string Key { get; set; } = key; - public string Value { get; set; } + public string Value { get; set; } = value; public void GenerateGetObservableCode(Span indentStr, StringBuilder sb, string rootNamespace, Dictionary redirects) { diff --git a/nukebuild/Build.cs b/nukebuild/Build.cs index 782f0ecf1..cfe61e7d1 100644 --- a/nukebuild/Build.cs +++ b/nukebuild/Build.cs @@ -87,12 +87,12 @@ partial class Build : NukeBuild .SetOutput(mainOutput) .SetProperty("NukePublish", true)); - string[] subProjects = new string[] - { + string[] subProjects = + [ "Beutl.ExceptionHandler", "Beutl.PackageTools", "Beutl.WaitingDialog", - }; + ]; foreach (string item in subProjects) { AbsolutePath output = OutputDirectory / item; @@ -108,14 +108,14 @@ partial class Build : NukeBuild .ForEach(t => CopyFile(t.Source, t.Target)); } - string[] asmsToCopy = new string[] - { + string[] asmsToCopy = + [ "FluentTextTable", "Kokuban", "Kurukuru", "Sharprompt", "DeviceId", - }; + ]; foreach (string asm in asmsToCopy) { foreach (string item in subProjects) diff --git a/src/Beutl.Api/BeutlApiApplication.cs b/src/Beutl.Api/BeutlApiApplication.cs index b1977f982..d29e7e3c5 100644 --- a/src/Beutl.Api/BeutlApiApplication.cs +++ b/src/Beutl.Api/BeutlApiApplication.cs @@ -20,7 +20,7 @@ public class BeutlApiApplication private const string BaseUrl = "https://beutl.beditor.net"; private readonly HttpClient _httpClient; private readonly ReactivePropertySlim _authorizedUser = new(); - private readonly Dictionary> _services = new(); + private readonly Dictionary> _services = []; public BeutlApiApplication(HttpClient httpClient) { diff --git a/src/Beutl.Api/MyAsyncLock.cs b/src/Beutl.Api/MyAsyncLock.cs index c6d4feaa7..da4ca766d 100644 --- a/src/Beutl.Api/MyAsyncLock.cs +++ b/src/Beutl.Api/MyAsyncLock.cs @@ -47,18 +47,11 @@ public Task LockAsync(CancellationToken cancellationToken = default } } - private sealed class Releaser : IDisposable + private sealed class Releaser(MyAsyncLock toRelease) : IDisposable { - private readonly MyAsyncLock _mutex; - - public Releaser(MyAsyncLock toRelease) - { - _mutex = toRelease; - } - public void Dispose() { - _mutex._semaphore.Release(); + toRelease._semaphore.Release(); } } } diff --git a/src/Beutl.Api/Objects/AuthorizedUser.cs b/src/Beutl.Api/Objects/AuthorizedUser.cs index 21015d792..499dd9524 100644 --- a/src/Beutl.Api/Objects/AuthorizedUser.cs +++ b/src/Beutl.Api/Objects/AuthorizedUser.cs @@ -3,49 +3,37 @@ namespace Beutl.Api.Objects; -public class AuthorizedUser +public class AuthorizedUser(Profile profile, AuthResponse response, BeutlApiApplication clients, HttpClient httpClient) { - private readonly BeutlApiApplication _clients; - private readonly HttpClient _httpClient; - private AuthResponse _response; + public Profile Profile { get; } = profile; - public AuthorizedUser(Profile profile, AuthResponse response, BeutlApiApplication clients, HttpClient httpClient) - { - Profile = profile; - _response = response; - _clients = clients; - _httpClient = httpClient; - } - - public Profile Profile { get; } - - public string Token => _response.Token; + public string Token => response.Token; - public string RefreshToken => _response.Refresh_token; + public string RefreshToken => response.Refresh_token; - public DateTimeOffset Expiration => _response.Expiration; + public DateTimeOffset Expiration => response.Expiration; public bool IsExpired => Expiration < DateTimeOffset.UtcNow; - public MyAsyncLock Lock => _clients.Lock; + public MyAsyncLock Lock => clients.Lock; public async ValueTask RefreshAsync(bool force = false) { - using Activity? activity = _clients.ActivitySource.StartActivity("AuthorizedUser.Refresh", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("AuthorizedUser.Refresh", ActivityKind.Client); activity?.SetTag("force", force); activity?.SetTag("is_expired", IsExpired); if (force || IsExpired) { - _response = await _clients.Account.RefreshAsync(new RefeshTokenRequest(RefreshToken, Token)) + response = await clients.Account.RefreshAsync(new RefeshTokenRequest(RefreshToken, Token)) .ConfigureAwait(false); activity?.AddEvent(new("Refreshed")); - _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token); + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token); - if (_clients.AuthorizedUser.Value == this) + if (clients.AuthorizedUser.Value == this) { - _clients.SaveUser(); + clients.SaveUser(); activity?.AddEvent(new("Saved")); } } @@ -53,6 +41,6 @@ public async ValueTask RefreshAsync(bool force = false) public async Task StorageUsageAsync() { - return await _clients.Account.StorageUsageAsync(); + return await clients.Account.StorageUsageAsync(); } } diff --git a/src/Beutl.Api/Services/AcceptedLicenseManager.cs b/src/Beutl.Api/Services/AcceptedLicenseManager.cs index dfe225550..b2a012832 100644 --- a/src/Beutl.Api/Services/AcceptedLicenseManager.cs +++ b/src/Beutl.Api/Services/AcceptedLicenseManager.cs @@ -9,7 +9,7 @@ namespace Beutl.Api.Services; public class AcceptedLicenseManager : IBeutlApiResource { - private readonly Dictionary _accepted = new(); + private readonly Dictionary _accepted = []; private const string FileName = "accepted-licenses.json"; public AcceptedLicenseManager() diff --git a/src/Beutl.Api/Services/DiscoverService.cs b/src/Beutl.Api/Services/DiscoverService.cs index cd03c10dc..f7f436569 100644 --- a/src/Beutl.Api/Services/DiscoverService.cs +++ b/src/Beutl.Api/Services/DiscoverService.cs @@ -4,42 +4,35 @@ namespace Beutl.Api.Services; -public class DiscoverService : IBeutlApiResource +public class DiscoverService(BeutlApiApplication clients) : IBeutlApiResource { - private readonly BeutlApiApplication _clients; - - public DiscoverService(BeutlApiApplication clients) - { - _clients = clients; - } - - public MyAsyncLock Lock => _clients.Lock; + public MyAsyncLock Lock => clients.Lock; public async Task GetPackage(string name) { - using Activity? activity = _clients.ActivitySource.StartActivity("DiscoverService.GetPackage", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("DiscoverService.GetPackage", ActivityKind.Client); - PackageResponse package = await _clients.Packages.GetPackageAsync(name).ConfigureAwait(false); + PackageResponse package = await clients.Packages.GetPackageAsync(name).ConfigureAwait(false); Profile owner = await GetProfile(package.Owner.Name).ConfigureAwait(false); - return new Package(owner, package, _clients); + return new Package(owner, package, clients); } public async Task GetProfile(string name) { - using Activity? activity = _clients.ActivitySource.StartActivity("DiscoverService.GetProfile", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("DiscoverService.GetProfile", ActivityKind.Client); - ProfileResponse response = await _clients.Users.GetUserAsync(name).ConfigureAwait(false); - return new Profile(response, _clients); + ProfileResponse response = await clients.Users.GetUserAsync(name).ConfigureAwait(false); + return new Profile(response, clients); } public async Task GetDailyRanking(int start = 0, int count = 30) { - using Activity? activity = _clients.ActivitySource.StartActivity("DiscoverService.GetDailyRanking", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("DiscoverService.GetDailyRanking", ActivityKind.Client); activity?.SetTag("start", start); activity?.SetTag("count", count); - return await (await _clients.Discover.GetDailyAsync(start, count).ConfigureAwait(false)) + return await (await clients.Discover.GetDailyAsync(start, count).ConfigureAwait(false)) .ToAsyncEnumerable() .SelectAwait(async x => await GetPackage(x.Name).ConfigureAwait(false)) .ToArrayAsync() @@ -48,11 +41,11 @@ public async Task GetDailyRanking(int start = 0, int count = 30) public async Task GetWeeklyRanking(int start = 0, int count = 30) { - using Activity? activity = _clients.ActivitySource.StartActivity("DiscoverService.GetWeeklyRanking", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("DiscoverService.GetWeeklyRanking", ActivityKind.Client); activity?.SetTag("start", start); activity?.SetTag("count", count); - return await (await _clients.Discover.GetWeeklyAsync(start, count).ConfigureAwait(false)) + return await (await clients.Discover.GetWeeklyAsync(start, count).ConfigureAwait(false)) .ToAsyncEnumerable() .SelectAwait(async x => await GetPackage(x.Name).ConfigureAwait(false)) .ToArrayAsync() @@ -61,11 +54,11 @@ public async Task GetWeeklyRanking(int start = 0, int count = 30) public async Task GetOverallRanking(int start = 0, int count = 30) { - using Activity? activity = _clients.ActivitySource.StartActivity("DiscoverService.GetOverallRanking", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("DiscoverService.GetOverallRanking", ActivityKind.Client); activity?.SetTag("start", start); activity?.SetTag("count", count); - return await (await _clients.Discover.GetOverallAsync(start, count).ConfigureAwait(false)) + return await (await clients.Discover.GetOverallAsync(start, count).ConfigureAwait(false)) .ToAsyncEnumerable() .SelectAwait(async x => await GetPackage(x.Name).ConfigureAwait(false)) .ToArrayAsync() @@ -74,11 +67,11 @@ public async Task GetOverallRanking(int start = 0, int count = 30) public async Task GetRecentlyRanking(int start = 0, int count = 30) { - using Activity? activity = _clients.ActivitySource.StartActivity("DiscoverService.GetRecentlyRanking", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("DiscoverService.GetRecentlyRanking", ActivityKind.Client); activity?.SetTag("start", start); activity?.SetTag("count", count); - return await (await _clients.Discover.GetRecentlyAsync(start, count).ConfigureAwait(false)) + return await (await clients.Discover.GetRecentlyAsync(start, count).ConfigureAwait(false)) .ToAsyncEnumerable() .SelectAwait(async x => await GetPackage(x.Name).ConfigureAwait(false)) .ToArrayAsync() @@ -87,11 +80,11 @@ public async Task GetRecentlyRanking(int start = 0, int count = 30) public async Task SearchPackages(string query, int start = 0, int count = 30) { - using Activity? activity = _clients.ActivitySource.StartActivity("DiscoverService.SearchPackages", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("DiscoverService.SearchPackages", ActivityKind.Client); activity?.SetTag("start", start); activity?.SetTag("count", count); - return await (await _clients.Discover.SearchPackagesAsync(query, start, count).ConfigureAwait(false)) + return await (await clients.Discover.SearchPackagesAsync(query, start, count).ConfigureAwait(false)) .ToAsyncEnumerable() .SelectAwait(async x => await GetPackage(x.Name).ConfigureAwait(false)) .ToArrayAsync() @@ -100,11 +93,11 @@ public async Task SearchPackages(string query, int start = 0, int cou public async Task SearchUsers(string query, int start = 0, int count = 30) { - using Activity? activity = _clients.ActivitySource.StartActivity("DiscoverService.SearchUsers", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("DiscoverService.SearchUsers", ActivityKind.Client); activity?.SetTag("start", start); activity?.SetTag("count", count); - return await (await _clients.Discover.SearchUsersAsync(query, start, count).ConfigureAwait(false)) + return await (await clients.Discover.SearchUsersAsync(query, start, count).ConfigureAwait(false)) .ToAsyncEnumerable() .SelectAwait(async x => await GetProfile(x.Name).ConfigureAwait(false)) .ToArrayAsync() @@ -113,7 +106,7 @@ public async Task SearchUsers(string query, int start = 0, int count public async Task Search(string query, int start = 0, int count = 30) { - return await (await _clients.Discover.SearchAsync(query, start, count).ConfigureAwait(false)) + return await (await clients.Discover.SearchAsync(query, start, count).ConfigureAwait(false)) .ToAsyncEnumerable() .SelectAwait(async x => await GetPackage(x.Name).ConfigureAwait(false)) .ToArrayAsync() diff --git a/src/Beutl.Api/Services/ExtensionProvider.cs b/src/Beutl.Api/Services/ExtensionProvider.cs index 078d28b4e..aeb093326 100644 --- a/src/Beutl.Api/Services/ExtensionProvider.cs +++ b/src/Beutl.Api/Services/ExtensionProvider.cs @@ -8,10 +8,10 @@ namespace Beutl.Api.Services; public sealed class ExtensionProvider : IBeutlApiResource { - private readonly Dictionary _allExtensions = new(); + private readonly Dictionary _allExtensions = []; private readonly ExtensionConfig _config = GlobalConfiguration.Instance.ExtensionConfig; - private readonly Dictionary _cache = new(); - private readonly CoreList _extensions = new(); + private readonly Dictionary _cache = []; + private readonly CoreList _extensions = []; private readonly object _lock = new(); private bool _cacheInvalidated; diff --git a/src/Beutl.Api/Services/ExtensionSettingsStore.cs b/src/Beutl.Api/Services/ExtensionSettingsStore.cs index 2cf0d7cdc..bf9fd280f 100644 --- a/src/Beutl.Api/Services/ExtensionSettingsStore.cs +++ b/src/Beutl.Api/Services/ExtensionSettingsStore.cs @@ -8,7 +8,7 @@ namespace Beutl.Api.Services; public sealed class ExtensionSettingsStore { private const string FileName = "extensionsSettings.json"; - private JsonObject _json = new(); + private JsonObject _json = []; public ExtensionSettingsStore() { diff --git a/src/Beutl.Api/Services/InstalledPackageRepository.cs b/src/Beutl.Api/Services/InstalledPackageRepository.cs index 7912df2ce..072c41b16 100644 --- a/src/Beutl.Api/Services/InstalledPackageRepository.cs +++ b/src/Beutl.Api/Services/InstalledPackageRepository.cs @@ -11,7 +11,7 @@ namespace Beutl.Api.Services; public class InstalledPackageRepository : IBeutlApiResource { - private readonly HashSet _packages = new(); + private readonly HashSet _packages = []; private readonly Subject<(PackageIdentity Package, bool Exists)> _subject = new(); private const string FileName = "installedPackages.json"; @@ -32,7 +32,7 @@ public IEnumerable GetLocalPackages(string name) public void UpgradePackages(PackageIdentity package) { - PackageIdentity[] removedItems = Array.Empty(); + PackageIdentity[] removedItems = []; if (_subject.HasObservers) { removedItems = GetLocalPackages(package.Id).ToArray(); @@ -99,7 +99,7 @@ public void RemovePackage(PackageIdentity package) public void RemovePackages(string name) { - PackageIdentity[] removed = Array.Empty(); + PackageIdentity[] removed = []; if (_subject.HasObservers) { removed = GetLocalPackages(name).ToArray(); diff --git a/src/Beutl.Api/Services/LibraryService.cs b/src/Beutl.Api/Services/LibraryService.cs index 2c157b424..65bb0d027 100644 --- a/src/Beutl.Api/Services/LibraryService.cs +++ b/src/Beutl.Api/Services/LibraryService.cs @@ -4,38 +4,31 @@ namespace Beutl.Api.Services; -public class LibraryService : IBeutlApiResource +public class LibraryService(BeutlApiApplication clients) : IBeutlApiResource { - private readonly BeutlApiApplication _clients; - - public LibraryService(BeutlApiApplication clients) - { - _clients = clients; - } - public async Task GetPackage(string name) { - using Activity? activity = _clients.ActivitySource.StartActivity("LibraryService.GetPackage", ActivityKind.Client); - PackageResponse package = await _clients.Packages.GetPackageAsync(name); + using Activity? activity = clients.ActivitySource.StartActivity("LibraryService.GetPackage", ActivityKind.Client); + PackageResponse package = await clients.Packages.GetPackageAsync(name); Profile owner = await GetProfile(package.Owner.Name); - return new Package(owner, package, _clients); + return new Package(owner, package, clients); } public async Task GetProfile(string name) { - using Activity? activity = _clients.ActivitySource.StartActivity("LibraryService.GetProfile", ActivityKind.Client); - ProfileResponse response = await _clients.Users.GetUserAsync(name); - return new Profile(response, _clients); + using Activity? activity = clients.ActivitySource.StartActivity("LibraryService.GetProfile", ActivityKind.Client); + ProfileResponse response = await clients.Users.GetUserAsync(name); + return new Profile(response, clients); } public async Task GetPackages(int start = 0, int count = 30) { - using Activity? activity = _clients.ActivitySource.StartActivity("LibraryService.GetPackages", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("LibraryService.GetPackages", ActivityKind.Client); activity?.SetTag("start", start); activity?.SetTag("count", count); - return await (await _clients.Library.GetLibraryAsync(start, count)) + return await (await clients.Library.GetLibraryAsync(start, count)) .ToAsyncEnumerable() .SelectAwait(async x => await GetPackage(x.Package.Name)) .ToArrayAsync(); @@ -43,9 +36,9 @@ public async Task GetPackages(int start = 0, int count = 30) public async Task GetPackage(Package package) { - using Activity? activity = _clients.ActivitySource.StartActivity("LibraryService.GetPackage", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("LibraryService.GetPackage", ActivityKind.Client); - GotPackageResponse response = await _clients.Library.GetPackageAsync(new GetPackageRequest(package.Id)); + GotPackageResponse response = await clients.Library.GetPackageAsync(new GetPackageRequest(package.Id)); if (response.Latest_release == null) throw new Exception("No release"); @@ -54,8 +47,8 @@ public async Task GetPackage(Package package) public async Task RemovePackage(Package package) { - using Activity? activity = _clients.ActivitySource.StartActivity("LibraryService.RemovePackage", ActivityKind.Client); + using Activity? activity = clients.ActivitySource.StartActivity("LibraryService.RemovePackage", ActivityKind.Client); - (await _clients.Library.DeletePackageAsync(package.Name)).Dispose(); + (await clients.Library.DeletePackageAsync(package.Name)).Dispose(); } } diff --git a/src/Beutl.Api/Services/LocalPackage.cs b/src/Beutl.Api/Services/LocalPackage.cs index 85cb2230f..8559cf621 100644 --- a/src/Beutl.Api/Services/LocalPackage.cs +++ b/src/Beutl.Api/Services/LocalPackage.cs @@ -46,7 +46,7 @@ public LocalPackage(NuspecReader nuspecReader) } //Logo = nuspecReader.GetIcon(); - Tags = nuspecReader.GetTags().Split(' ', ';').ToList(); + Tags = [.. nuspecReader.GetTags().Split(' ', ';')]; } public string Name { get; set; } = string.Empty; @@ -68,7 +68,7 @@ public LocalPackage(NuspecReader nuspecReader) // VersionRange public string? TargetVersion { get; set; } - public List Tags { get; set; } = new List(); + public List Tags { get; set; } = []; [AllowNull] public string InstalledPath { get; internal set; } diff --git a/src/Beutl.Api/Services/PackageChangesQueue.cs b/src/Beutl.Api/Services/PackageChangesQueue.cs index 7ccca77a7..edd803fe8 100644 --- a/src/Beutl.Api/Services/PackageChangesQueue.cs +++ b/src/Beutl.Api/Services/PackageChangesQueue.cs @@ -9,8 +9,8 @@ namespace Beutl.Api.Services; public class PackageChangesQueue : IBeutlApiResource { - private readonly HashSet _installs = new(); - private readonly HashSet _uninstalls = new(); + private readonly HashSet _installs = []; + private readonly HashSet _uninstalls = []; private readonly Subject<(PackageIdentity Package, EventType Type)> _subject = new(); diff --git a/src/Beutl.Api/Services/PackageCleanContext.cs b/src/Beutl.Api/Services/PackageCleanContext.cs index 7f86271db..288e328fe 100644 --- a/src/Beutl.Api/Services/PackageCleanContext.cs +++ b/src/Beutl.Api/Services/PackageCleanContext.cs @@ -4,17 +4,11 @@ namespace Beutl.Api.Services; -public class PackageCleanContext +public class PackageCleanContext(PackageIdentity[] unnecessaryPackages, long sizeToBeReleased) { - public PackageCleanContext(PackageIdentity[] unnecessaryPackages, long sizeToBeReleased) - { - UnnecessaryPackages = unnecessaryPackages; - SizeToBeReleased = sizeToBeReleased; - } + public PackageIdentity[] UnnecessaryPackages { get; } = unnecessaryPackages; - public PackageIdentity[] UnnecessaryPackages { get; } - - public long SizeToBeReleased { get; } + public long SizeToBeReleased { get; } = sizeToBeReleased; [AllowNull] public IReadOnlyList FailedPackages { get; internal set; } diff --git a/src/Beutl.Api/Services/PackageInstallContext.cs b/src/Beutl.Api/Services/PackageInstallContext.cs index c0b515f1b..ca4dd1ed4 100644 --- a/src/Beutl.Api/Services/PackageInstallContext.cs +++ b/src/Beutl.Api/Services/PackageInstallContext.cs @@ -18,23 +18,16 @@ public enum PackageInstallPhase ResolvedDependencies = 5 } -public class PackageInstallContext +public class PackageInstallContext(string packageName, string version, string downloadUrl) { private PackageInstallPhase _phase; private IReadOnlyList? _installedPaths; - public PackageInstallContext(string packageName, string version, string downloadUrl) - { - PackageName = packageName; - Version = version; - DownloadUrl = downloadUrl; - } - - public string PackageName { get; } + public string PackageName { get; } = packageName; - public string Version { get; } + public string Version { get; } = version; - public string DownloadUrl { get; } + public string DownloadUrl { get; } = downloadUrl; public string? NuGetPackageFile { get; internal set; } diff --git a/src/Beutl.Api/Services/PackageInstaller.Clean.cs b/src/Beutl.Api/Services/PackageInstaller.Clean.cs index 46e9fae2a..cd9c2b005 100644 --- a/src/Beutl.Api/Services/PackageInstaller.Clean.cs +++ b/src/Beutl.Api/Services/PackageInstaller.Clean.cs @@ -11,7 +11,7 @@ private PackageIdentity[] UnnecessaryPackages(IEnumerable? inst { if (!Directory.Exists(Helper.InstallPath)) { - return Array.Empty(); + return []; } NuGetFramework framework = Helper.GetFrameworkName(); diff --git a/src/Beutl.Api/Services/PackageInstaller.Uninstall.cs b/src/Beutl.Api/Services/PackageInstaller.Uninstall.cs index 95cce7c0e..d4ab20c82 100644 --- a/src/Beutl.Api/Services/PackageInstaller.Uninstall.cs +++ b/src/Beutl.Api/Services/PackageInstaller.Uninstall.cs @@ -13,7 +13,7 @@ public PackageUninstallContext PrepareForUninstall( cancellationToken.ThrowIfCancellationRequested(); PackageIdentity uninstallPackage = new PackageFolderReader(installedPath).GetIdentity(); - PackageIdentity[] unnecessaryPackages = { uninstallPackage }; + PackageIdentity[] unnecessaryPackages = [uninstallPackage]; if (clean) { diff --git a/src/Beutl.Api/Services/PackageInstaller.cs b/src/Beutl.Api/Services/PackageInstaller.cs index adc83e9ea..454bdb75e 100644 --- a/src/Beutl.Api/Services/PackageInstaller.cs +++ b/src/Beutl.Api/Services/PackageInstaller.cs @@ -30,7 +30,7 @@ public partial class PackageInstaller : IBeutlApiResource private readonly SourceCacheContext _cacheContext; private readonly PackageResolver _resolver; - private readonly Dictionary _installingContexts = new(); + private readonly Dictionary _installingContexts = []; private readonly Subject<(PackageIdentity Package, EventType Type)> _subject = new(); @@ -176,7 +176,6 @@ public async Task DownloadPackageFile( } } -#pragma warning disable CA1822 // メンバーを static に設定します public async Task VerifyPackageFile( PackageInstallContext context, IProgress? progress = null, @@ -238,11 +237,11 @@ static string ByteArrayToString(byte[] bytes) using var sha384 = SHA384.Create(); using var sha512 = SHA512.Create(); (HashAlgorithm, string?)[] items = - { + [ (sha256, asset.Sha256), (sha384, asset.Sha384), (sha512, asset.Sha512), - }; + ]; long totalLength = items.Count(x => !string.IsNullOrWhiteSpace(x.Item2)) * stream.Length; if (totalLength == 0) @@ -269,7 +268,6 @@ static string ByteArrayToString(byte[] bytes) } } } -#pragma warning restore CA1822 // メンバーを static に設定します public async Task ResolveDependencies( PackageInstallContext context, diff --git a/src/Beutl.Api/Services/PackageLoader.cs b/src/Beutl.Api/Services/PackageLoader.cs index 3b5c2e674..882c3f5b7 100644 --- a/src/Beutl.Api/Services/PackageLoader.cs +++ b/src/Beutl.Api/Services/PackageLoader.cs @@ -45,9 +45,6 @@ protected Assembly[] SideLoad(string installedPath) string name = Path.GetFileName(mainDirectory); string asmFile = Path.Combine(mainDirectory, $"{name}.dll"); - return new Assembly[] - { - loadContext.LoadFromAssemblyPath(asmFile) - }; + return [loadContext.LoadFromAssemblyPath(asmFile)]; } } diff --git a/src/Beutl.Api/Services/PackageManager.cs b/src/Beutl.Api/Services/PackageManager.cs index ae3ed0ec6..8b4bd4485 100644 --- a/src/Beutl.Api/Services/PackageManager.cs +++ b/src/Beutl.Api/Services/PackageManager.cs @@ -15,27 +15,18 @@ namespace Beutl.Api.Services; -public sealed class PackageManager : PackageLoader +public sealed class PackageManager( + InstalledPackageRepository installedPackageRepository, + ExtensionProvider extensionProvider, + BeutlApiApplication apiApplication) : PackageLoader { - private readonly ConcurrentBag _loadedPackage = new(); - private readonly InstalledPackageRepository _installedPackageRepository; - private readonly BeutlApiApplication _apiApplication; + private readonly ConcurrentBag _loadedPackage = []; private readonly ExtensionSettingsStore _settingsStore = new(); private readonly Subject<(PackageIdentity Package, bool Loaded)> _subject = new(); - public PackageManager( - InstalledPackageRepository installedPackageRepository, - ExtensionProvider extensionProvider, - BeutlApiApplication apiApplication) - { - ExtensionProvider = extensionProvider; - _installedPackageRepository = installedPackageRepository; - _apiApplication = apiApplication; - } - public IEnumerable LoadedPackage => _loadedPackage; - public ExtensionProvider ExtensionProvider { get; } + public ExtensionProvider ExtensionProvider { get; } = extensionProvider; public IObservable GetObservable(string name, string? version = null) { @@ -81,10 +72,10 @@ public async Task> CheckUpdate() { using (Activity? activity = Telemetry.ActivitySource.StartActivity("CheckUpdate")) { - PackageIdentity[] packages = _installedPackageRepository.GetLocalPackages().ToArray(); + PackageIdentity[] packages = installedPackageRepository.GetLocalPackages().ToArray(); var updates = new List(packages.Length); - DiscoverService discover = _apiApplication.GetResource(); + DiscoverService discover = apiApplication.GetResource(); for (int i = 0; i < packages.Length; i++) { @@ -124,7 +115,7 @@ public async Task> CheckUpdate() { using (Activity? activity = Telemetry.ActivitySource.StartActivity("CheckUpdate")) { - DiscoverService discover = _apiApplication.GetResource(); + DiscoverService discover = apiApplication.GetResource(); LocalPackage? pkg = _loadedPackage.FirstOrDefault(v => !v.SideLoad && StringComparer.OrdinalIgnoreCase.Equals(v.Name, name)); if (pkg != null) @@ -157,7 +148,7 @@ public Task> GetPackages() { using (Activity? activity = Telemetry.ActivitySource.StartActivity("GetPackages")) { - PackageIdentity[] packages = _installedPackageRepository.GetLocalPackages().ToArray(); + PackageIdentity[] packages = installedPackageRepository.GetLocalPackages().ToArray(); activity?.SetTag("Packages_Count", packages.Length); var list = new List(packages.Length); @@ -235,7 +226,7 @@ public Assembly[] Load(LocalPackage package) activity?.AddEvent(new ActivityEvent("Loaded_Extensions")); - ExtensionProvider.AddExtensions(package.LocalId, extensions.ToArray()); + ExtensionProvider.AddExtensions(package.LocalId, [.. extensions]); _loadedPackage.Add(package); diff --git a/src/Beutl.Api/Services/PackageUpdate.cs b/src/Beutl.Api/Services/PackageUpdate.cs index b9452902e..1ffabe3cb 100644 --- a/src/Beutl.Api/Services/PackageUpdate.cs +++ b/src/Beutl.Api/Services/PackageUpdate.cs @@ -2,18 +2,11 @@ namespace Beutl.Api.Services; -public sealed class PackageUpdate +public sealed class PackageUpdate(Package package, Release? oldVersion, Release newVersion) { - public PackageUpdate(Package package, Release? oldVersion, Release newVersion) - { - Package = package; - OldVersion = oldVersion; - NewVersion = newVersion; - } + public Package Package { get; } = package; - public Package Package { get; } + public Release? OldVersion { get; } = oldVersion; - public Release? OldVersion { get; } - - public Release NewVersion { get; } + public Release NewVersion { get; } = newVersion; } diff --git a/src/Beutl.Api/Services/PluginDependencyResolver.cs b/src/Beutl.Api/Services/PluginDependencyResolver.cs index 3f25cc002..f5a571286 100644 --- a/src/Beutl.Api/Services/PluginDependencyResolver.cs +++ b/src/Beutl.Api/Services/PluginDependencyResolver.cs @@ -15,8 +15,8 @@ internal sealed class PluginDependencyResolver private const string ResourceAssemblyExtension = ".dll"; private readonly Dictionary _assemblyPaths = new(StringComparer.OrdinalIgnoreCase); - private readonly HashSet _nativeSearchPaths = new(); - private readonly HashSet _resourceSearchPaths = new(); + private readonly HashSet _nativeSearchPaths = []; + private readonly HashSet _resourceSearchPaths = []; private readonly string[] _assemblyDirectorySearchPaths; public PluginDependencyResolver(string mainDirectory, PackageFolderReader? reader) @@ -64,7 +64,7 @@ public PluginDependencyResolver(string mainDirectory, PackageFolderReader? reade } } - _assemblyDirectorySearchPaths = new string[1] { mainDirectory }; + _assemblyDirectorySearchPaths = [mainDirectory]; } private void GetPackageDependencies( diff --git a/src/Beutl.Api/Services/PluginLoadContext.cs b/src/Beutl.Api/Services/PluginLoadContext.cs index e07d4b3cd..a542b0f5a 100644 --- a/src/Beutl.Api/Services/PluginLoadContext.cs +++ b/src/Beutl.Api/Services/PluginLoadContext.cs @@ -5,16 +5,10 @@ namespace Beutl.Api.Services; -public class PluginLoadContext : AssemblyLoadContext +public class PluginLoadContext(string mainDirectory, PackageFolderReader? reader = null) : AssemblyLoadContext(isCollectible: true) { - private readonly AssemblyDependencyResolver _resolver; - private readonly PluginDependencyResolver _pluginResolver; - - public PluginLoadContext(string mainDirectory, PackageFolderReader? reader = null) : base(isCollectible: true) - { - _resolver = new AssemblyDependencyResolver(AppContext.BaseDirectory); - _pluginResolver = new PluginDependencyResolver(mainDirectory, reader); - } + private readonly AssemblyDependencyResolver _resolver = new AssemblyDependencyResolver(AppContext.BaseDirectory); + private readonly PluginDependencyResolver _pluginResolver = new PluginDependencyResolver(mainDirectory, reader); protected override Assembly? Load(AssemblyName name) { diff --git a/src/Beutl.Api/System.Runtime.Loader/LibraryNameValidation.cs b/src/Beutl.Api/System.Runtime.Loader/LibraryNameValidation.cs index abf8b3cb4..103e04951 100644 --- a/src/Beutl.Api/System.Runtime.Loader/LibraryNameValidation.cs +++ b/src/Beutl.Api/System.Runtime.Loader/LibraryNameValidation.cs @@ -3,15 +3,9 @@ namespace System.Runtime.Loader { - internal partial struct LibraryNameVariation + internal partial struct LibraryNameVariation(string prefix, string suffix) { - public string Prefix; - public string Suffix; - - public LibraryNameVariation(string prefix, string suffix) - { - Prefix = prefix; - Suffix = suffix; - } + public string Prefix = prefix; + public string Suffix = suffix; } } diff --git a/src/Beutl.Configuration/ExtensionConfig.cs b/src/Beutl.Configuration/ExtensionConfig.cs index ab8ebe872..8ed0fbbd8 100644 --- a/src/Beutl.Configuration/ExtensionConfig.cs +++ b/src/Beutl.Configuration/ExtensionConfig.cs @@ -13,25 +13,20 @@ public ExtensionConfig() DecoderPriority.CollectionChanged += (_, _) => OnChanged(); } - public struct TypeLazy + public struct TypeLazy(string formattedTypeName) { private Type? _type = null; - public TypeLazy(string formattedTypeName) - { - FormattedTypeName = formattedTypeName; - } - - public string FormattedTypeName { get; init; } + public string FormattedTypeName { get; init; } = formattedTypeName; public Type? Type => _type ??= TypeFormat.ToType(FormattedTypeName); } // Keyには拡張子を含める - public CoreDictionary> EditorExtensions { get; } = new(); + public CoreDictionary> EditorExtensions { get; } = []; // Keyには拡張子を含める - public CoreList DecoderPriority { get; } = new(); + public CoreList DecoderPriority { get; } = []; [ObsoleteSerializationApi] public override void ReadFromJson(JsonObject json) diff --git a/src/Beutl.Configuration/FontConfig.cs b/src/Beutl.Configuration/FontConfig.cs index 1c4066b45..b13ea4f92 100644 --- a/src/Beutl.Configuration/FontConfig.cs +++ b/src/Beutl.Configuration/FontConfig.cs @@ -31,7 +31,7 @@ public override void ReadFromJson(JsonObject json) if (GetNode("directories", nameof(FontDirectories)) is JsonArray dirsArray) { string[] array = dirsArray.Select(i => (string?)i).Where(i => i != null).ToArray()!; - string[] fontDirs = FontDirectories.ToArray(); + string[] fontDirs = [.. FontDirectories]; foreach (string item in array.Except(fontDirs)) { @@ -56,8 +56,8 @@ public override void Deserialize(ICoreSerializationContext context) { base.Deserialize(context); - string[] array = context.GetValue(nameof(FontDirectories)) ?? Array.Empty(); - string[] fontDirs = FontDirectories.ToArray(); + string[] array = context.GetValue(nameof(FontDirectories)) ?? []; + string[] fontDirs = [.. FontDirectories]; foreach (string item in array.Except(fontDirs)) { @@ -115,8 +115,6 @@ static IEnumerable MacOS() e = MacOS(); } - return e != null ? - new ObservableCollection(e) : - new ObservableCollection(); + return e != null ? [.. e] : []; } } diff --git a/src/Beutl.Configuration/ViewConfig.cs b/src/Beutl.Configuration/ViewConfig.cs index f7222dbda..2a5d7560a 100644 --- a/src/Beutl.Configuration/ViewConfig.cs +++ b/src/Beutl.Configuration/ViewConfig.cs @@ -22,12 +22,12 @@ public sealed class ViewConfig : ConfigurationBase public static readonly CoreProperty> PrimaryPropertiesProperty; public static readonly CoreProperty> RecentFilesProperty; public static readonly CoreProperty> RecentProjectsProperty; - private readonly CoreList _primaryProperties = new() - { + private readonly CoreList _primaryProperties = + [ "AlignmentX", "AlignmentY", "TransformOrigin", "BlendMode" - }; - private readonly CoreList _recentFiles = new(); - private readonly CoreList _recentProjects = new(); + ]; + private readonly CoreList _recentFiles = []; + private readonly CoreList _recentProjects = []; private bool _showExactBoundaries = false; static ViewConfig() diff --git a/src/Beutl.Controls/DirectoryTreeView.cs b/src/Beutl.Controls/DirectoryTreeView.cs index fe2057645..1f3644ba4 100644 --- a/src/Beutl.Controls/DirectoryTreeView.cs +++ b/src/Beutl.Controls/DirectoryTreeView.cs @@ -21,7 +21,7 @@ namespace Beutl.Controls; public sealed class DirectoryTreeView : TreeView { private readonly FileSystemWatcher _watcher; - private readonly AvaloniaList _items = new(); + private readonly AvaloniaList _items = []; private readonly DirectoryInfo _directoryInfo; private readonly MenuItem _open; private readonly MenuItem _copy; @@ -99,8 +99,8 @@ public DirectoryTreeView(FileSystemWatcher watcher, Func context _rename.Click += Rename; _addfolder.Click += AddDirectory; - _menuItem = new List - { + _menuItem = + [ _open, new MenuItem { @@ -114,7 +114,7 @@ public DirectoryTreeView(FileSystemWatcher watcher, Func context _remove, _rename, new Separator() - }; + ]; //foreach (var (asm, menus) in PluginManager.Default.FileMenus) //{ @@ -453,8 +453,8 @@ static string Func(TreeViewItem item) } } - FileTreeItem[] fileArray = _items.OfType().OrderBy(Func).ToArray(); - DirectoryTreeItem[] dirArray = _items.OfType().OrderBy(Func).ToArray(); + FileTreeItem[] fileArray = [.. _items.OfType().OrderBy(Func)]; + DirectoryTreeItem[] dirArray = [.. _items.OfType().OrderBy(Func)]; _items.Clear(); _items.AddRange(dirArray); _items.AddRange(fileArray); @@ -610,7 +610,7 @@ private void FileTreeItem_DoubleTapped(object sender, RoutedEventArgs e) public sealed class DirectoryTreeItem : TreeViewItem { - private readonly AvaloniaList _items = new(); + private readonly AvaloniaList _items = []; private readonly FileSystemWatcher _watcher; private readonly Func _contextFactory; // //サブフォルダを作成済みかどうか @@ -705,8 +705,8 @@ static string Func(TreeViewItem item) if (!_isAdd) return; - FileTreeItem[] fileArray = _items.OfType().OrderBy(Func).ToArray(); - DirectoryTreeItem[] dirArray = _items.OfType().OrderBy(Func).ToArray(); + FileTreeItem[] fileArray = [.. _items.OfType().OrderBy(Func)]; + DirectoryTreeItem[] dirArray = [.. _items.OfType().OrderBy(Func)]; _items.Clear(); _items.AddRange(dirArray); _items.AddRange(fileArray); diff --git a/src/Beutl.Controls/PropertyEditors/AlignmentXEditor.cs b/src/Beutl.Controls/PropertyEditors/AlignmentXEditor.cs index 25184cd64..f3ea5a7cb 100644 --- a/src/Beutl.Controls/PropertyEditors/AlignmentXEditor.cs +++ b/src/Beutl.Controls/PropertyEditors/AlignmentXEditor.cs @@ -25,7 +25,7 @@ public class AlignmentXEditor : PropertyEditor private const string LeftSelected = ":left-selected"; private const string CenterSelected = ":center-selected"; private const string RightSelected = ":right-selected"; - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private AlignmentX _value; public AlignmentXEditor() diff --git a/src/Beutl.Controls/PropertyEditors/AlignmentYEditor.cs b/src/Beutl.Controls/PropertyEditors/AlignmentYEditor.cs index 1c59c407c..a3c92d120 100644 --- a/src/Beutl.Controls/PropertyEditors/AlignmentYEditor.cs +++ b/src/Beutl.Controls/PropertyEditors/AlignmentYEditor.cs @@ -25,7 +25,7 @@ public class AlignmentYEditor : PropertyEditor private const string TopSelected = ":top-selected"; private const string CenterSelected = ":center-selected"; private const string BottomSelected = ":bottom-selected"; - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private AlignmentY _value; public AlignmentYEditor() diff --git a/src/Beutl.Controls/PropertyEditors/DataValidationMessages.cs b/src/Beutl.Controls/PropertyEditors/DataValidationMessages.cs index 9570429c2..b25f9460e 100644 --- a/src/Beutl.Controls/PropertyEditors/DataValidationMessages.cs +++ b/src/Beutl.Controls/PropertyEditors/DataValidationMessages.cs @@ -4,6 +4,6 @@ namespace Beutl.Controls.PropertyEditors; internal static class DataValidationMessages { - public static readonly object[] InvalidString = new object[] { Message.InvalidString }; - public static readonly object[] FileDoesNotExist = new object[] { Message.FileDoesNotExist }; + public static readonly object[] InvalidString = [Message.InvalidString]; + public static readonly object[] FileDoesNotExist = [Message.FileDoesNotExist]; } diff --git a/src/Beutl.Controls/PropertyEditors/NumberEditor.cs b/src/Beutl.Controls/PropertyEditors/NumberEditor.cs index 49a1c2a0e..50b3fe45e 100644 --- a/src/Beutl.Controls/PropertyEditors/NumberEditor.cs +++ b/src/Beutl.Controls/PropertyEditors/NumberEditor.cs @@ -26,7 +26,7 @@ public class NumberEditor : StringEditor defaultBindingMode: BindingMode.TwoWay); private TValue _value; private TValue _oldValue; - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private bool _headerPressed; private Point _headerDragStart; private TextBlock _headerText; diff --git a/src/Beutl.Controls/PropertyEditors/RelativePointEditor.cs b/src/Beutl.Controls/PropertyEditors/RelativePointEditor.cs index 13766667f..83e4a65dd 100644 --- a/src/Beutl.Controls/PropertyEditors/RelativePointEditor.cs +++ b/src/Beutl.Controls/PropertyEditors/RelativePointEditor.cs @@ -30,7 +30,7 @@ public class RelativePointEditor : Vector2Editor (o, v) => o.Unit = v, defaultBindingMode: BindingMode.TwoWay); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private float _firstValue; private float _oldFirstValue; private float _secondValue; diff --git a/src/Beutl.Controls/PropertyEditors/StringEditor.cs b/src/Beutl.Controls/PropertyEditors/StringEditor.cs index 76019bbd6..b601f6c45 100644 --- a/src/Beutl.Controls/PropertyEditors/StringEditor.cs +++ b/src/Beutl.Controls/PropertyEditors/StringEditor.cs @@ -22,7 +22,7 @@ public class StringEditor : PropertyEditor (o, v) => o.Text = v, defaultBindingMode: BindingMode.TwoWay); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private string _text; private string _oldValue; diff --git a/src/Beutl.Controls/PropertyEditors/Vector2Editor.cs b/src/Beutl.Controls/PropertyEditors/Vector2Editor.cs index 02afe0b91..6564170f0 100644 --- a/src/Beutl.Controls/PropertyEditors/Vector2Editor.cs +++ b/src/Beutl.Controls/PropertyEditors/Vector2Editor.cs @@ -26,7 +26,7 @@ public class Vector2Editor : Vector2Editor o => o.SecondValue, (o, v) => o.SecondValue = v); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private TElement _firstValue; private TElement _oldFirstValue; private TElement _secondValue; @@ -364,7 +364,7 @@ public class Vector2Editor : PropertyEditor private const string FocusSecondTextBox = ":focus-2nd-textbox"; private const string BorderPointerOver = ":border-pointerover"; private const string Uniform = ":uniform"; - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private Border _backgroundBorder; private string _firstText; private string _secondText; diff --git a/src/Beutl.Controls/PropertyEditors/Vector3Editor.cs b/src/Beutl.Controls/PropertyEditors/Vector3Editor.cs index 629669e66..1ec9df9ab 100644 --- a/src/Beutl.Controls/PropertyEditors/Vector3Editor.cs +++ b/src/Beutl.Controls/PropertyEditors/Vector3Editor.cs @@ -31,7 +31,7 @@ public class Vector3Editor : Vector3Editor o => o.ThirdValue, (o, v) => o.ThirdValue = v); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private TElement _firstValue; private TElement _oldFirstValue; private TElement _secondValue; @@ -421,7 +421,7 @@ public class Vector3Editor : PropertyEditor private const string FocusThirdTextBox = ":focus-3rd-textbox"; private const string BorderPointerOver = ":border-pointerover"; private const string Uniform = ":uniform"; - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private Border _backgroundBorder; private string _firstText; private string _secondText; diff --git a/src/Beutl.Controls/PropertyEditors/Vector4Editor.cs b/src/Beutl.Controls/PropertyEditors/Vector4Editor.cs index 8a2745eb0..34c0baebe 100644 --- a/src/Beutl.Controls/PropertyEditors/Vector4Editor.cs +++ b/src/Beutl.Controls/PropertyEditors/Vector4Editor.cs @@ -47,7 +47,7 @@ public class Vector4Editor : Vector4Editor defaultBindingMode: BindingMode.TwoWay); #pragma warning restore AVP1002 // AvaloniaProperty objects should not be owned by a generic type - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private TElement _firstValue; private TElement _oldFirstValue; private TElement _secondValue; @@ -450,7 +450,7 @@ public class Vector4Editor : PropertyEditor private const string FocusFourthTextBox = ":focus-4th-textbox"; private const string BorderPointerOver = ":border-pointerover"; private const string Uniform = ":uniform"; - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private Border _backgroundBorder; private string _firstText; private string _secondText; diff --git a/src/Beutl.Core/CollectionBatchExtension.cs b/src/Beutl.Core/CollectionBatchExtension.cs index 0f615613a..3135e2d5b 100644 --- a/src/Beutl.Core/CollectionBatchExtension.cs +++ b/src/Beutl.Core/CollectionBatchExtension.cs @@ -50,140 +50,121 @@ public interface ICollectionBatchChanges IRecordableCommand ToCommand(); } - private sealed class CollectionBatchChanges : ICollectionBatchChanges + private sealed class CollectionBatchChanges(IList list) : ICollectionBatchChanges { - private readonly List _commands = new(); - private readonly IList _list; - - public CollectionBatchChanges(IList list) - { - _list = list; - } + private readonly List _commands = []; public ICollectionBatchChanges Add(object? item) { - _commands.Add(new AddCommand(_list, item, _list.Count)); + _commands.Add(new AddCommand(list, item, list.Count)); return this; } public ICollectionBatchChanges Clear() { - _commands.Add(new ClearCommand(_list)); + _commands.Add(new ClearCommand(list)); return this; } public ICollectionBatchChanges Insert(int index, object? item) { - _commands.Add(new AddCommand(_list, item, index)); + _commands.Add(new AddCommand(list, item, index)); return this; } public ICollectionBatchChanges Move(int oldIndex, int newIndex) { - _commands.Add(new MoveCommand(_list, newIndex, oldIndex)); + _commands.Add(new MoveCommand(list, newIndex, oldIndex)); return this; } public ICollectionBatchChanges Remove(object? item) { - _commands.Add(new RemoveCommand(_list, item)); + _commands.Add(new RemoveCommand(list, item)); return this; } public ICollectionBatchChanges RemoveAt(int index) { - _commands.Add(new RemoveCommand(_list, index)); + _commands.Add(new RemoveCommand(list, index)); return this; } public IRecordableCommand ToCommand() { - return new Command(_commands.ToArray()); + return new Command([.. _commands]); } } - private sealed class CollectionBatchChanges : ICollectionBatchChanges + private sealed class CollectionBatchChanges(IList list) : ICollectionBatchChanges { - private readonly List _commands = new(); - private readonly IList _list; - - public CollectionBatchChanges(IList list) - { - _list = list; - } + private readonly List _commands = []; public ICollectionBatchChanges Add(T item) { - _commands.Add(new AddCommand(_list, item, _list.Count)); + _commands.Add(new AddCommand(list, item, list.Count)); return this; } public ICollectionBatchChanges Clear() { - _commands.Add(new ClearCommand(_list)); + _commands.Add(new ClearCommand(list)); return this; } public ICollectionBatchChanges Insert(int index, T item) { - _commands.Add(new AddCommand(_list, item, index)); + _commands.Add(new AddCommand(list, item, index)); return this; } public ICollectionBatchChanges Move(int oldIndex, int newIndex) { - _commands.Add(new MoveCommand(_list, newIndex, oldIndex)); + _commands.Add(new MoveCommand(list, newIndex, oldIndex)); return this; } public ICollectionBatchChanges Remove(T item) { - _commands.Add(new RemoveCommand(_list, item)); + _commands.Add(new RemoveCommand(list, item)); return this; } public ICollectionBatchChanges RemoveAt(int index) { - _commands.Add(new RemoveCommand(_list, index)); + _commands.Add(new RemoveCommand(list, index)); return this; } public IRecordableCommand ToCommand() { - return new Command(_commands.ToArray()); + return new Command([.. _commands]); } } - private sealed class Command : IRecordableCommand + private sealed class Command(IRecordableCommand[] commands) : IRecordableCommand { - private readonly IRecordableCommand[] _commands; - - public Command(IRecordableCommand[] commands) - { - _commands = commands; - } - public void Do() { - for (int i = 0; i < _commands.Length; i++) + for (int i = 0; i < commands.Length; i++) { - _commands[i].Do(); + commands[i].Do(); } } public void Redo() { - for (int i = 0; i < _commands.Length; i++) + for (int i = 0; i < commands.Length; i++) { - _commands[i].Redo(); + commands[i].Redo(); } } public void Undo() { - for (int i = _commands.Length - 1; i >= 0; i--) + for (int i = commands.Length - 1; i >= 0; i--) { - _commands[i].Undo(); + commands[i].Undo(); } } } diff --git a/src/Beutl.Core/Collections/CoreDictionary.cs b/src/Beutl.Core/Collections/CoreDictionary.cs index 5c27146c7..b81edfec8 100644 --- a/src/Beutl.Core/Collections/CoreDictionary.cs +++ b/src/Beutl.Core/Collections/CoreDictionary.cs @@ -15,7 +15,7 @@ public class CoreDictionary : IDictionary, public CoreDictionary() { - _inner = new Dictionary(); + _inner = []; } public event NotifyCollectionChangedEventHandler? CollectionChanged; @@ -84,7 +84,7 @@ public void Clear() { Dictionary old = _inner; - _inner = new Dictionary(); + _inner = []; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item")); diff --git a/src/Beutl.Core/Collections/CoreList.cs b/src/Beutl.Core/Collections/CoreList.cs index 7b5ce719c..7c6d0d3a1 100644 --- a/src/Beutl.Core/Collections/CoreList.cs +++ b/src/Beutl.Core/Collections/CoreList.cs @@ -41,7 +41,7 @@ public class CoreList : ICoreList public CoreList() { - Inner = new List(); + Inner = []; } public CoreList(int capacity) @@ -141,7 +141,7 @@ public virtual void AddRange(ReadOnlySpan items) { InsertRange(Inner.Count, items); } - + public virtual void AddRange(T[] items) { InsertRange(Inner.Count, items); @@ -157,7 +157,7 @@ public virtual void Clear() if ((CollectionChanged != null && ResetBehavior == ResetBehavior.Remove) || Detached != null) { - items = Inner.ToList(); + items = [.. Inner]; } if (CollectionChanged != null) @@ -186,7 +186,7 @@ public virtual void Clear() public virtual void Replace(IList source) { Span span = CollectionsMarshal.AsSpan(Inner); - T[] oldItems = Count > 0 ? span.ToArray() : Array.Empty(); + T[] oldItems = Count > 0 ? span.ToArray() : []; if (!oldItems.SequenceEqual(source)) { Inner.Clear(); @@ -300,9 +300,7 @@ public virtual void InsertRange(int index, IEnumerable items) if (en.MoveNext()) { // Avoid allocating list for collection notification if there is no event subscriptions. - List? notificationItems = willRaiseCollectionChanged ? - new List() : - null; + List? notificationItems = willRaiseCollectionChanged ? [] : null; int insertIndex = index; @@ -339,7 +337,7 @@ public virtual void InsertRange(int index, ReadOnlySpan items) NotifyAdd(items, index); } } - + public virtual void InsertRange(int index, T[] items) { if (items.Length > 0) @@ -673,14 +671,9 @@ private void NotifyRemove(T item, int index) NotifyCountChanged(); } - public struct Enumerator : IEnumerator + public struct Enumerator(List inner) : IEnumerator { - private List.Enumerator _innerEnumerator; - - public Enumerator(List inner) - { - _innerEnumerator = inner.GetEnumerator(); - } + private List.Enumerator _innerEnumerator = inner.GetEnumerator(); public bool MoveNext() { diff --git a/src/Beutl.Core/Collections/NotifyCollectionChangedExtensions.cs b/src/Beutl.Core/Collections/NotifyCollectionChangedExtensions.cs index 04001b4c6..91e22e616 100644 --- a/src/Beutl.Core/Collections/NotifyCollectionChangedExtensions.cs +++ b/src/Beutl.Core/Collections/NotifyCollectionChangedExtensions.cs @@ -36,16 +36,10 @@ public static IDisposable WeakSubscribe( return collection.GetWeakCollectionChangedObservable().Subscribe(handler); } - private class WeakCollectionChangedObservable : LightweightObservableBase, - IWeakEventSubscriber + private class WeakCollectionChangedObservable(WeakReference source) + : LightweightObservableBase, + IWeakEventSubscriber { - private readonly WeakReference _sourceReference; - - public WeakCollectionChangedObservable(WeakReference source) - { - _sourceReference = source; - } - public void OnEvent(object? sender, WeakEvent ev, NotifyCollectionChangedEventArgs e) { PublishNext(e); @@ -53,7 +47,7 @@ public void OnEvent(object? sender, WeakEvent ev, NotifyCollectionChangedEventAr protected override void Initialize() { - if (_sourceReference.TryGetTarget(out INotifyCollectionChanged? instance)) + if (source.TryGetTarget(out INotifyCollectionChanged? instance)) { WeakEvents.CollectionChanged.Subscribe(instance, this); } @@ -61,7 +55,7 @@ protected override void Initialize() protected override void Deinitialize() { - if (_sourceReference.TryGetTarget(out INotifyCollectionChanged? instance)) + if (source.TryGetTarget(out INotifyCollectionChanged? instance)) { WeakEvents.CollectionChanged.Unsubscribe(instance, this); } diff --git a/src/Beutl.Core/Collections/Pooled/PooledList.cs b/src/Beutl.Core/Collections/Pooled/PooledList.cs index bdcc5aaa7..e65f28641 100644 --- a/src/Beutl.Core/Collections/Pooled/PooledList.cs +++ b/src/Beutl.Core/Collections/Pooled/PooledList.cs @@ -16,7 +16,7 @@ public class PooledList : IList, IReadOnlyList, IList, IDisposable, IDe // internal constant copied from Array.MaxArrayLength private const int MaxArrayLength = 0x7FEFFFFF; private const int DefaultCapacity = 4; - private static readonly T[] s_emptyArray = Array.Empty(); + private static readonly T[] s_emptyArray = []; [NonSerialized] private ArrayPool _pool; @@ -1498,15 +1498,8 @@ void IEnumerator.Reset() } } - private readonly struct Comparer : IComparer + private readonly struct Comparer(Func comparison) : IComparer { - private readonly Func _comparison; - - public Comparer(Func comparison) - { - _comparison = comparison; - } - - public int Compare(T? x, T? y) => _comparison(x, y); + public int Compare(T? x, T? y) => comparison(x, y); } } diff --git a/src/Beutl.Core/Collections/PooledArray.cs b/src/Beutl.Core/Collections/PooledArray.cs index 8498e3b00..fde0ab49d 100644 --- a/src/Beutl.Core/Collections/PooledArray.cs +++ b/src/Beutl.Core/Collections/PooledArray.cs @@ -133,16 +133,9 @@ IEnumerator IEnumerable.GetEnumerator() return _array.GetEnumerator(); } - public struct ArrayEnumerator : IEnumerator + public struct ArrayEnumerator(PooledArray array) : IEnumerator { - private PooledArray _array; - private int _index; - - public ArrayEnumerator(PooledArray array) - { - _array = array; - _index = -1; - } + private int _index = -1; public ref T Current { @@ -150,9 +143,9 @@ public ref T Current { if (_index == -1) throw new InvalidOperationException(); - if (_index >= _array!.Length) + if (_index >= array!.Length) throw new InvalidOperationException(); - return ref _array[_index]; + return ref array[_index]; } } @@ -162,14 +155,14 @@ public ref T Current public bool MoveNext() { - if (_index < (_array!.Length - 1)) + if (_index < (array!.Length - 1)) { _index++; return true; } else { - _index = _array.Length; + _index = array.Length; } return false; @@ -177,8 +170,8 @@ public bool MoveNext() public void Dispose() { - _index = _array.Length; - _array = default; + _index = array.Length; + array = default; } public void Reset() diff --git a/src/Beutl.Core/CommandExecutedEventArgs.cs b/src/Beutl.Core/CommandExecutedEventArgs.cs index 10d93121a..fac85847d 100644 --- a/src/Beutl.Core/CommandExecutedEventArgs.cs +++ b/src/Beutl.Core/CommandExecutedEventArgs.cs @@ -1,14 +1,8 @@ namespace Beutl; -public class CommandExecutedEventArgs : EventArgs +public class CommandExecutedEventArgs(IRecordableCommand command, CommandType type) : EventArgs { - public CommandExecutedEventArgs(IRecordableCommand command, CommandType type) - { - Command = command; - Type = type; - } + public IRecordableCommand Command { get; } = command; - public IRecordableCommand Command { get; } - - public CommandType Type { get; } + public CommandType Type { get; } = type; } diff --git a/src/Beutl.Core/Commands/AddCommand.cs b/src/Beutl.Core/Commands/AddCommand.cs index 9c16942f5..7a865f741 100644 --- a/src/Beutl.Core/Commands/AddCommand.cs +++ b/src/Beutl.Core/Commands/AddCommand.cs @@ -2,20 +2,13 @@ namespace Beutl.Commands; -internal sealed class AddCommand : IRecordableCommand +internal sealed class AddCommand(IList list, object? item, int index) : IRecordableCommand { - public AddCommand(IList list, object? item, int index) - { - List = list; - Item = item; - Index = index; - } - - public IList List { get; } + public IList List { get; } = list; - public object? Item { get; } + public object? Item { get; } = item; - public int Index { get; } + public int Index { get; } = index; public void Do() { diff --git a/src/Beutl.Core/Commands/AddCommand{T}.cs b/src/Beutl.Core/Commands/AddCommand{T}.cs index 9dbf9e9df..1398efae0 100644 --- a/src/Beutl.Core/Commands/AddCommand{T}.cs +++ b/src/Beutl.Core/Commands/AddCommand{T}.cs @@ -1,19 +1,12 @@ namespace Beutl.Commands; -internal sealed class AddCommand : IRecordableCommand +internal sealed class AddCommand(IList list, T item, int index) : IRecordableCommand { - public AddCommand(IList list, T item, int index) - { - List = list; - Item = item; - Index = index; - } - - public IList List { get; } + public IList List { get; } = list; - public T Item { get; } + public T Item { get; } = item; - public int Index { get; } + public int Index { get; } = index; public void Do() { diff --git a/src/Beutl.Core/Commands/ChangePropertyCommand.cs b/src/Beutl.Core/Commands/ChangePropertyCommand.cs index 393035fcb..c2fcc90c3 100644 --- a/src/Beutl.Core/Commands/ChangePropertyCommand.cs +++ b/src/Beutl.Core/Commands/ChangePropertyCommand.cs @@ -1,22 +1,14 @@ namespace Beutl.Commands; -public sealed class ChangePropertyCommand : IRecordableCommand +public sealed class ChangePropertyCommand(ICoreObject obj, CoreProperty property, object? newValue, object? oldValue) : IRecordableCommand { - public ChangePropertyCommand(ICoreObject obj, CoreProperty property, object? newValue, object? oldValue) - { - Object = obj; - Property = property; - NewValue = newValue; - OldValue = oldValue; - } - - public ICoreObject Object { get; } + public ICoreObject Object { get; } = obj; - public CoreProperty Property { get; } + public CoreProperty Property { get; } = property; - public object? NewValue { get; } + public object? NewValue { get; } = newValue; - public object? OldValue { get; } + public object? OldValue { get; } = oldValue; public void Do() { diff --git a/src/Beutl.Core/Commands/ChangePropertyCommand{T}.cs b/src/Beutl.Core/Commands/ChangePropertyCommand{T}.cs index a287e5fb7..26babdb3f 100644 --- a/src/Beutl.Core/Commands/ChangePropertyCommand{T}.cs +++ b/src/Beutl.Core/Commands/ChangePropertyCommand{T}.cs @@ -1,22 +1,14 @@ namespace Beutl.Commands; -public sealed class ChangePropertyCommand : IRecordableCommand +public sealed class ChangePropertyCommand(ICoreObject obj, CoreProperty property, T? newValue, T? oldValue) : IRecordableCommand { - public ChangePropertyCommand(ICoreObject obj, CoreProperty property, T? newValue, T? oldValue) - { - Object = obj; - Property = property; - NewValue = newValue; - OldValue = oldValue; - } - - public ICoreObject Object { get; } + public ICoreObject Object { get; } = obj; - public CoreProperty Property { get; } + public CoreProperty Property { get; } = property; - public T? NewValue { get; } + public T? NewValue { get; } = newValue; - public T? OldValue { get; } + public T? OldValue { get; } = oldValue; public void Do() { diff --git a/src/Beutl.Core/Commands/MoveCommand.cs b/src/Beutl.Core/Commands/MoveCommand.cs index ccb62b16c..47dfcc310 100644 --- a/src/Beutl.Core/Commands/MoveCommand.cs +++ b/src/Beutl.Core/Commands/MoveCommand.cs @@ -4,30 +4,19 @@ namespace Beutl.Commands; -internal sealed class MoveCommand : IRecordableCommand +internal sealed class MoveCommand(IList list, int newIndex, int oldIndex) : IRecordableCommand { - private readonly IList _list; - private readonly int _newIndex; - private readonly int _oldIndex; - - public MoveCommand(IList list, int newIndex, int oldIndex) - { - _list = list; - _newIndex = newIndex; - _oldIndex = oldIndex; - } - public void Do() { - if (_list is ICoreList coreList) + if (list is ICoreList coreList) { - coreList.Move(_oldIndex, _newIndex); + coreList.Move(oldIndex, newIndex); } else { - object? item = _list[_oldIndex]; - _list.RemoveAt(_oldIndex); - _list.Insert(_newIndex, item); + object? item = list[oldIndex]; + list.RemoveAt(oldIndex); + list.Insert(newIndex, item); } } @@ -38,15 +27,15 @@ public void Redo() public void Undo() { - if (_list is ICoreList coreList) + if (list is ICoreList coreList) { - coreList.Move(_newIndex, _oldIndex); + coreList.Move(newIndex, oldIndex); } else { - object? item = _list[_newIndex]; - _list.RemoveAt(_newIndex); - _list.Insert(_oldIndex, item); + object? item = list[newIndex]; + list.RemoveAt(newIndex); + list.Insert(oldIndex, item); } } } diff --git a/src/Beutl.Core/Commands/MoveCommand{T}.cs b/src/Beutl.Core/Commands/MoveCommand{T}.cs index 341f6b943..4c1170dff 100644 --- a/src/Beutl.Core/Commands/MoveCommand{T}.cs +++ b/src/Beutl.Core/Commands/MoveCommand{T}.cs @@ -4,34 +4,23 @@ namespace Beutl.Commands; -internal sealed class MoveCommand : IRecordableCommand +internal sealed class MoveCommand(IList list, int newIndex, int oldIndex) : IRecordableCommand { - private readonly IList _list; - private readonly int _newIndex; - private readonly int _oldIndex; - - public MoveCommand(IList list, int newIndex, int oldIndex) - { - _list = list; - _newIndex = newIndex; - _oldIndex = oldIndex; - } - public void Do() { - if (_list is ICoreList coreList) + if (list is ICoreList coreList) { - coreList.Move(_oldIndex, _newIndex); + coreList.Move(oldIndex, newIndex); } - else if (_list is ObservableCollection observableCollection) + else if (list is ObservableCollection observableCollection) { - observableCollection.Move(_oldIndex, _newIndex); + observableCollection.Move(oldIndex, newIndex); } else { - T item = _list[_oldIndex]; - _list.RemoveAt(_oldIndex); - _list.Insert(_newIndex, item); + T item = list[oldIndex]; + list.RemoveAt(oldIndex); + list.Insert(newIndex, item); } } @@ -42,19 +31,19 @@ public void Redo() public void Undo() { - if (_list is ICoreList coreList) + if (list is ICoreList coreList) { - coreList.Move(_newIndex, _oldIndex); + coreList.Move(newIndex, oldIndex); } - else if (_list is ObservableCollection observableCollection) + else if (list is ObservableCollection observableCollection) { - observableCollection.Move(_newIndex, _oldIndex); + observableCollection.Move(newIndex, oldIndex); } else { - T item = _list[_newIndex]; - _list.RemoveAt(_newIndex); - _list.Insert(_oldIndex, item); + T item = list[newIndex]; + list.RemoveAt(newIndex); + list.Insert(oldIndex, item); } } } diff --git a/src/Beutl.Core/CoreObject.cs b/src/Beutl.Core/CoreObject.cs index 38dbdbaed..569a5a7af 100644 --- a/src/Beutl.Core/CoreObject.cs +++ b/src/Beutl.Core/CoreObject.cs @@ -101,11 +101,11 @@ public string Name public bool BatchUpdate => _batchUpdateCount > 0; - private Dictionary Values => _values ??= new(); + private Dictionary Values => _values ??= []; - private Dictionary BatchChanges => _batchChanges ??= new(); + private Dictionary BatchChanges => _batchChanges ??= []; - private Dictionary Errors => _errors ??= new(); + private Dictionary Errors => _errors ??= []; public bool HasErrors => _errors?.Count > 0; diff --git a/src/Beutl.Core/CoreObjectExtensions.cs b/src/Beutl.Core/CoreObjectExtensions.cs index 419a8d8ca..7ca8c48bc 100644 --- a/src/Beutl.Core/CoreObjectExtensions.cs +++ b/src/Beutl.Core/CoreObjectExtensions.cs @@ -29,7 +29,7 @@ public static IObservable GetObservable(this ICoreObject obj, CoreProperty public static object? Find(this ICoreObject obj, Predicate predicate, bool includeSelf = true) { - return obj.Find(predicate, includeSelf, new HashSet()); + return obj.Find(predicate, includeSelf, []); } public static object? Find(this ICoreObject obj, Predicate predicate, bool includeSelf, HashSet hashSet) @@ -91,20 +91,12 @@ public static IObservable GetObservable(this ICoreObject obj, CoreProperty return null; } - private sealed class CorePropertyChangedObservable : LightweightObservableBase> + private sealed class CorePropertyChangedObservable(ICoreObject o, CoreProperty property) + : LightweightObservableBase> { - private readonly CoreProperty _property; - private readonly ICoreObject _object; - - public CorePropertyChangedObservable(ICoreObject o, CoreProperty property) - { - _object = o; - _property = property; - } - private void Object_PropertyChanged(object? sender, PropertyChangedEventArgs e) { - if (e is CorePropertyChangedEventArgs a && a.Property == _property) + if (e is CorePropertyChangedEventArgs a && a.Property == property) { PublishNext(a); } @@ -112,12 +104,12 @@ private void Object_PropertyChanged(object? sender, PropertyChangedEventArgs e) protected override void Deinitialize() { - _object.PropertyChanged -= Object_PropertyChanged; + o.PropertyChanged -= Object_PropertyChanged; } protected override void Initialize() { - _object.PropertyChanged += Object_PropertyChanged; + o.PropertyChanged += Object_PropertyChanged; } } } diff --git a/src/Beutl.Core/CoreProperty.cs b/src/Beutl.Core/CoreProperty.cs index a62057c9c..213d6b5bc 100644 --- a/src/Beutl.Core/CoreProperty.cs +++ b/src/Beutl.Core/CoreProperty.cs @@ -14,8 +14,8 @@ public abstract class CoreProperty : ICoreProperty { private static int s_nextId = 0; private readonly ICorePropertyMetadata _defaultMetadata; - private readonly Dictionary _metadata = new(); - private readonly Dictionary _metadataCache = new(); + private readonly Dictionary _metadata = []; + private readonly Dictionary _metadataCache = []; private bool _hasMetadataOverrides; private bool _isTryedToGetPropertyInfo; @@ -196,18 +196,13 @@ public override int GetHashCode() } } -public class CoreProperty : CoreProperty +public class CoreProperty( + string name, + Type ownerType, + CorePropertyMetadata metadata) + : CoreProperty(name, typeof(T), ownerType, metadata) { - private readonly Subject> _changed; - - public CoreProperty( - string name, - Type ownerType, - CorePropertyMetadata metadata) - : base(name, typeof(T), ownerType, metadata) - { - _changed = new(); - } + private readonly Subject> _changed = new(); public new IObservable> Changed => _changed; diff --git a/src/Beutl.Core/CorePropertyBuilder.cs b/src/Beutl.Core/CorePropertyBuilder.cs index 8dc4200e5..1f3eaac3f 100644 --- a/src/Beutl.Core/CorePropertyBuilder.cs +++ b/src/Beutl.Core/CorePropertyBuilder.cs @@ -24,7 +24,7 @@ public CorePropertyBuilder(string name, bool isAttached = false) } else { - _attributes = Array.Empty(); + _attributes = []; } } @@ -42,7 +42,7 @@ memberExp.Member is PropertyInfo propInfo && ParameterExpression valueParam = Expression.Parameter(typeof(T), "v"); MemberExpression? memberAccess = Expression.MakeMemberAccess(ownerParam, propInfo); BinaryExpression? assign = Expression.Assign(memberAccess, valueParam); - Expression> lambda1 = Expression.Lambda>(assign, new[] { ownerParam, valueParam }); + Expression> lambda1 = Expression.Lambda>(assign, [ownerParam, valueParam]); _setter = lambda1.Compile(); _attributes = _propertyInfo.GetCustomAttributes().ToArray(); diff --git a/src/Beutl.Core/CorePropertyChangedEventArgs.cs b/src/Beutl.Core/CorePropertyChangedEventArgs.cs index fa3f8d852..5736e3990 100644 --- a/src/Beutl.Core/CorePropertyChangedEventArgs.cs +++ b/src/Beutl.Core/CorePropertyChangedEventArgs.cs @@ -2,20 +2,17 @@ namespace Beutl; -public abstract class CorePropertyChangedEventArgs : PropertyChangedEventArgs +public abstract class CorePropertyChangedEventArgs( + CoreObject sender, + CoreProperty property, + CorePropertyMetadata metadata) + : PropertyChangedEventArgs(property.Name) { - protected CorePropertyChangedEventArgs(CoreObject sender, CoreProperty property, CorePropertyMetadata metadata) - : base(property.Name) - { - Sender = sender; - PropertyMetadata = metadata; - } - - public CoreObject Sender { get; } + public CoreObject Sender { get; } = sender; public CoreProperty Property => GetProperty(); - - public CorePropertyMetadata PropertyMetadata { get; } + + public CorePropertyMetadata PropertyMetadata { get; } = metadata; public object? NewValue => GetNewValue(); @@ -28,22 +25,20 @@ protected CorePropertyChangedEventArgs(CoreObject sender, CoreProperty property, protected abstract CoreProperty GetProperty(); } -public sealed class CorePropertyChangedEventArgs : CorePropertyChangedEventArgs +public sealed class CorePropertyChangedEventArgs( + CoreObject sender, + CoreProperty property, + CorePropertyMetadata metadata, + TValue? newValue, + TValue? oldValue) + : CorePropertyChangedEventArgs(sender, property,metadata) { - public CorePropertyChangedEventArgs(CoreObject sender, CoreProperty property, CorePropertyMetadata metadata, TValue? newValue, TValue? oldValue) - : base(sender, property,metadata) - { - Property = property; - NewValue = newValue; - OldValue = oldValue; - } + public new CoreProperty Property { get; } = property; - public new CoreProperty Property { get; } + public new TValue? NewValue { get; } = newValue; - public new TValue? NewValue { get; } + public new TValue? OldValue { get; } = oldValue; - public new TValue? OldValue { get; } - protected override object? GetNewValue() { return NewValue; diff --git a/src/Beutl.Core/Hierarchy/HierarchyAttachmentEventArgs.cs b/src/Beutl.Core/Hierarchy/HierarchyAttachmentEventArgs.cs index be4ce970c..09e7ae473 100644 --- a/src/Beutl.Core/Hierarchy/HierarchyAttachmentEventArgs.cs +++ b/src/Beutl.Core/Hierarchy/HierarchyAttachmentEventArgs.cs @@ -1,14 +1,8 @@ namespace Beutl; -public readonly struct HierarchyAttachmentEventArgs +public readonly struct HierarchyAttachmentEventArgs(IHierarchicalRoot root, IHierarchical? parent) { - public HierarchyAttachmentEventArgs(IHierarchicalRoot root, IHierarchical? parent) - { - Root = root; - Parent = parent; - } + public IHierarchicalRoot Root { get; } = root; - public IHierarchicalRoot Root { get; } - - public IHierarchical? Parent { get; } + public IHierarchical? Parent { get; } = parent; } diff --git a/src/Beutl.Core/IRecordableCommand.cs b/src/Beutl.Core/IRecordableCommand.cs index ca64206c0..f06ff9cfd 100644 --- a/src/Beutl.Core/IRecordableCommand.cs +++ b/src/Beutl.Core/IRecordableCommand.cs @@ -31,68 +31,52 @@ public static IRecordableCommand ToCommand(this IRecordableCommand[] commands) return new MultipleCommand(commands); } - private sealed class ConnectedCommand : IRecordableCommand + private sealed class ConnectedCommand(IRecordableCommand command1, IRecordableCommand command2) : IRecordableCommand { - private readonly IRecordableCommand _command1; - private readonly IRecordableCommand _command2; - - public ConnectedCommand(IRecordableCommand command1, IRecordableCommand command2) - { - _command1 = command1; - _command2 = command2; - } - public void Do() { - _command1.Do(); - _command2.Do(); + command1.Do(); + command2.Do(); } public void Redo() { - _command1.Redo(); - _command2.Redo(); + command1.Redo(); + command2.Redo(); } public void Undo() { - _command1.Undo(); - _command2.Undo(); + command1.Undo(); + command2.Undo(); } } - private sealed class MultipleCommand : IRecordableCommand + private sealed class MultipleCommand(IRecordableCommand[] commands) : IRecordableCommand { - private readonly IRecordableCommand[] _commands; - - public MultipleCommand(IRecordableCommand[] commands) - { - _commands = commands; - } - public void Do() { - for (int i = 0; i < _commands.Length; i++) + for (int i = 0; i < commands.Length; i++) { - IRecordableCommand? item = _commands[i]; + IRecordableCommand? item = commands[i]; item.Do(); } } public void Redo() { - for (int i = 0; i < _commands.Length; i++) + for (int i = 0; i < commands.Length; i++) { - IRecordableCommand? item = _commands[i]; + IRecordableCommand? item = commands[i]; item.Redo(); } } public void Undo() { - for (int i = _commands.Length - 1; i >= 0; i--) + for (int i = commands.Length - 1; i >= 0; i--) { - IRecordableCommand? item = _commands[i]; + IRecordableCommand? item = commands[i]; item.Undo(); } } diff --git a/src/Beutl.Core/JsonHelper.cs b/src/Beutl.Core/JsonHelper.cs index ddf7ef8b4..1ac17df61 100644 --- a/src/Beutl.Core/JsonHelper.cs +++ b/src/Beutl.Core/JsonHelper.cs @@ -12,7 +12,7 @@ namespace Beutl; public static class JsonHelper { - private static readonly Dictionary s_converters = new(); + private static readonly Dictionary s_converters = []; public static JsonWriterOptions WriterOptions { get; } = new() { diff --git a/src/Beutl.Core/NotifiableAttribute.cs b/src/Beutl.Core/NotifiableAttribute.cs index 0ad128c26..b99ad038b 100644 --- a/src/Beutl.Core/NotifiableAttribute.cs +++ b/src/Beutl.Core/NotifiableAttribute.cs @@ -1,12 +1,7 @@ namespace Beutl; [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] -public sealed class NotifiableAttribute : Attribute +public sealed class NotifiableAttribute(bool notifiable) : Attribute { - public NotifiableAttribute(bool notifiable) - { - Notifiable = notifiable; - } - - public bool Notifiable { get; } + public bool Notifiable { get; } = notifiable; } diff --git a/src/Beutl.Core/OnceEnumerable.cs b/src/Beutl.Core/OnceEnumerable.cs index bc1b056f0..84fc60828 100644 --- a/src/Beutl.Core/OnceEnumerable.cs +++ b/src/Beutl.Core/OnceEnumerable.cs @@ -2,35 +2,23 @@ namespace Beutl; -internal sealed class OnceEnumerable : IEnumerable +internal sealed class OnceEnumerable(T value) : IEnumerable { - private readonly T _value; - - public OnceEnumerable(T value) - { - _value = value; - } - public IEnumerator GetEnumerator() { - return new Enumerator(_value); + return new Enumerator(value); } IEnumerator IEnumerable.GetEnumerator() { - return new Enumerator(_value); + return new Enumerator(value); } - private sealed class Enumerator : IEnumerator + private sealed class Enumerator(T value) : IEnumerator { private bool _flag; - public Enumerator(T value) - { - Current = value; - } - - public T Current { get; } + public T Current { get; } = value; object IEnumerator.Current => Current!; diff --git a/src/Beutl.Core/Optional.cs b/src/Beutl.Core/Optional.cs index 29d785930..2485f5250 100644 --- a/src/Beutl.Core/Optional.cs +++ b/src/Beutl.Core/Optional.cs @@ -1,18 +1,10 @@ namespace Beutl; -public readonly struct Optional : IEquatable>, IOptional +public readonly struct Optional(T value) : IEquatable>, IOptional { - private readonly T _value; + public bool HasValue { get; } = true; - public Optional(T value) - { - _value = value; - HasValue = true; - } - - public bool HasValue { get; } - - public T Value => HasValue ? _value : throw new InvalidOperationException("Optional has no value."); + public T Value => HasValue ? value : throw new InvalidOperationException("Optional has no value."); public override bool Equals(object? obj) { @@ -26,40 +18,40 @@ public bool Equals(Optional other) public override int GetHashCode() { - return HasValue ? _value?.GetHashCode() ?? 0 : 0; + return HasValue ? value?.GetHashCode() ?? 0 : 0; } public Optional ToObject() { - return HasValue ? new Optional(_value) : default; + return HasValue ? new Optional(value) : default; } public override string ToString() { - return HasValue ? _value?.ToString() ?? "(null)" : "(empty)"; + return HasValue ? value?.ToString() ?? "(null)" : "(empty)"; } public T? GetValueOrDefault() { - return HasValue ? _value : default; + return HasValue ? value : default; } public T? GetValueOrDefault(T defaultValue) { - return HasValue ? _value : defaultValue; + return HasValue ? value : defaultValue; } public TResult? GetValueOrDefault() { return HasValue ? - _value is TResult result ? result : default + value is TResult result ? result : default : default; } public TResult? GetValueOrDefault(TResult defaultValue) { return HasValue ? - _value is TResult result ? result : default + value is TResult result ? result : default : defaultValue; } diff --git a/src/Beutl.Core/Project.cs b/src/Beutl.Core/Project.cs index 62a80ac7e..db3dd6b29 100644 --- a/src/Beutl.Core/Project.cs +++ b/src/Beutl.Core/Project.cs @@ -21,7 +21,7 @@ public sealed class Project : Hierarchical, IStorable private EventHandler? _saved; private EventHandler? _restored; private readonly HierarchicalList _items; - private readonly Dictionary _variables = new(); + private readonly Dictionary _variables = []; static Project() { diff --git a/src/Beutl.Core/ProjectItemContainer.cs b/src/Beutl.Core/ProjectItemContainer.cs index 5902960b9..095147232 100644 --- a/src/Beutl.Core/ProjectItemContainer.cs +++ b/src/Beutl.Core/ProjectItemContainer.cs @@ -4,7 +4,7 @@ namespace Beutl; public sealed class ProjectItemContainer { - private readonly List> _items = new(); + private readonly List> _items = []; private readonly BeutlApplication _app = BeutlApplication.Current; private IProjectItemGenerator? _generator; diff --git a/src/Beutl.Core/PropertyChangeTracker.cs b/src/Beutl.Core/PropertyChangeTracker.cs index dbf59e714..f0972cca2 100644 --- a/src/Beutl.Core/PropertyChangeTracker.cs +++ b/src/Beutl.Core/PropertyChangeTracker.cs @@ -4,8 +4,8 @@ namespace Beutl; public sealed class PropertyChangeTracker : IDisposable { - private readonly List _changes = new(); - private readonly List _trackingElement = new(); + private readonly List _changes = []; + private readonly List _trackingElement = []; public PropertyChangeTracker(IEnumerable elements, int maxDepth = -1) { @@ -30,7 +30,7 @@ public PropertyChangeTracker(IEnumerable elements, int maxDepth = - public IRecordableCommand ToCommand() { - return new CommandImpl(_changes.ToArray()); + return new CommandImpl([.. _changes]); } private void AddHandlers(ICoreObject obj, int currentDepth) @@ -96,20 +96,13 @@ public void Dispose() } } - private sealed class CommandImpl : IRecordableCommand + private sealed class CommandImpl(CorePropertyChangedEventArgs[] changes) : IRecordableCommand { - private readonly CorePropertyChangedEventArgs[] _changes; - - public CommandImpl(CorePropertyChangedEventArgs[] changes) - { - _changes = changes; - } - public void Do() { - for (int i = 0; i < _changes.Length; i++) + for (int i = 0; i < changes.Length; i++) { - CorePropertyChangedEventArgs item = _changes[i]; + CorePropertyChangedEventArgs item = changes[i]; item.Sender.SetValue(item.Property, item.NewValue); } @@ -126,9 +119,9 @@ public void Redo() public void Undo() { - for (int i = _changes.Length - 1; i >= 0; i--) + for (int i = changes.Length - 1; i >= 0; i--) { - CorePropertyChangedEventArgs item = _changes[i]; + CorePropertyChangedEventArgs item = changes[i]; item.Sender.SetValue(item.Property, item.OldValue); } diff --git a/src/Beutl.Core/PropertyRegistry.cs b/src/Beutl.Core/PropertyRegistry.cs index 07a2dc749..6273ff353 100644 --- a/src/Beutl.Core/PropertyRegistry.cs +++ b/src/Beutl.Core/PropertyRegistry.cs @@ -4,11 +4,11 @@ namespace Beutl; public static class PropertyRegistry { - private static readonly Dictionary s_properties = new(); - private static readonly Dictionary> s_registered = new(); - private static readonly Dictionary> s_attached = new(); - private static readonly Dictionary> s_registeredCache = new(); - private static readonly Dictionary> s_attachedCache = new(); + private static readonly Dictionary s_properties = []; + private static readonly Dictionary> s_registered = []; + private static readonly Dictionary> s_attached = []; + private static readonly Dictionary> s_registeredCache = []; + private static readonly Dictionary> s_attachedCache = []; public static IReadOnlyList GetRegistered(Type type) { @@ -19,7 +19,7 @@ public static IReadOnlyList GetRegistered(Type type) } Type? t = type; - result = new List(); + result = []; while (t != null) { @@ -46,7 +46,7 @@ public static IReadOnlyList GetRegisteredAttached(Type type) } Type? t = type; - result = new List(); + result = []; while (t != null) { diff --git a/src/Beutl.Core/Rational.cs b/src/Beutl.Core/Rational.cs index ce5fd86e0..475bda614 100644 --- a/src/Beutl.Core/Rational.cs +++ b/src/Beutl.Core/Rational.cs @@ -6,7 +6,7 @@ namespace Beutl; -public readonly partial struct Rational +public readonly partial struct Rational(long numerator, long denominator) : IEquatable, IEqualityOperators, IMultiplyOperators, @@ -20,15 +20,9 @@ public Rational(long value) { } - public Rational(long numerator, long denominator) - { - Numerator = numerator; - Denominator = denominator; - } - - public long Numerator { get; } + public long Numerator { get; } = numerator; - public long Denominator { get; } + public long Denominator { get; } = denominator; [Obsolete("Use Rational.IsNaN")] public bool IsIndeterminate => Denominator == 0 && Numerator == 0; diff --git a/src/Beutl.Core/Reactive/LightweightObservableBase.cs b/src/Beutl.Core/Reactive/LightweightObservableBase.cs index 0d00cb479..2975ba608 100644 --- a/src/Beutl.Core/Reactive/LightweightObservableBase.cs +++ b/src/Beutl.Core/Reactive/LightweightObservableBase.cs @@ -5,7 +5,7 @@ namespace Beutl.Reactive; public abstract class LightweightObservableBase : IObservable { private Exception? _error; - private List>? _observers = new(); + private List>? _observers = []; public IDisposable Subscribe(IObserver observer) { @@ -115,7 +115,7 @@ protected void PublishNext(T value) } else { - observers = _observers.ToArray(); + observers = [.. _observers]; } } if (singleObserver != null) @@ -144,7 +144,7 @@ protected void PublishCompleted() { return; } - observers = _observers.ToArray(); + observers = [.. _observers]; Volatile.Write(ref _observers, null); } @@ -172,7 +172,7 @@ protected void PublishError(Exception error) } _error = error; - observers = _observers.ToArray(); + observers = [.. _observers]; Volatile.Write(ref _observers, null); } diff --git a/src/Beutl.Core/RingStack.cs b/src/Beutl.Core/RingStack.cs index 0c4a01bd0..6a4b61da5 100644 --- a/src/Beutl.Core/RingStack.cs +++ b/src/Beutl.Core/RingStack.cs @@ -1,24 +1,15 @@ namespace Beutl; -internal sealed class RingStack +internal sealed class RingStack(int size) { - private readonly int _capacity; - private T[] _buffer; - private int _top; - - public RingStack(int size) - { - _capacity = size; - _buffer = new T[4]; - _top = -1; - Count = 0; - } + private T[] _buffer = new T[4]; + private int _top = -1; public bool IsEmpty => Count == 0; - public bool IsFull => Count == _capacity; + public bool IsFull => Count == size; - public int Count { get; private set; } + public int Count { get; private set; } = 0; private void Resize(int newCapacity) { @@ -31,10 +22,10 @@ private void Resize(int newCapacity) public void Push(T item) { if (Count == _buffer.Length - && _buffer.Length < _capacity) // 配列が満杯の場合 + && _buffer.Length < size) // 配列が満杯の場合 { int newCapacity = _buffer.Length * 2; // 新しい容量は現在の2倍にする - Resize(Math.Min(newCapacity, _capacity)); + Resize(Math.Min(newCapacity, size)); } else // 配列に空きがある場合 { diff --git a/src/Beutl.Core/Serialization/ArrayTypeHelpers.cs b/src/Beutl.Core/Serialization/ArrayTypeHelpers.cs index e96b6b2ea..2b9108fe8 100644 --- a/src/Beutl.Core/Serialization/ArrayTypeHelpers.cs +++ b/src/Beutl.Core/Serialization/ArrayTypeHelpers.cs @@ -4,8 +4,8 @@ namespace Beutl.Serialization; internal static class ArrayTypeHelpers { - private static readonly Dictionary s_elementTypes = new(); - private static readonly Dictionary s_genericArgsTypes = new(); + private static readonly Dictionary s_elementTypes = []; + private static readonly Dictionary s_genericArgsTypes = []; public static object ConvertArrayType(List output, Type type, Type elementType) { diff --git a/src/Beutl.Core/Serialization/DummyTypeAttribute.cs b/src/Beutl.Core/Serialization/DummyTypeAttribute.cs index ae734044e..28c5828ba 100644 --- a/src/Beutl.Core/Serialization/DummyTypeAttribute.cs +++ b/src/Beutl.Core/Serialization/DummyTypeAttribute.cs @@ -3,14 +3,9 @@ namespace Beutl.Serialization; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = true, AllowMultiple = false)] -public sealed class DummyTypeAttribute : Attribute +public sealed class DummyTypeAttribute(Type dummyType) : Attribute { - public DummyTypeAttribute(Type dummyType) - { - DummyType = dummyType; - } - - public Type DummyType { get; } + public Type DummyType { get; } = dummyType; } public interface IDummy : ICoreSerializable diff --git a/src/Beutl.Core/Serialization/JsonSerializationContext.cs b/src/Beutl.Core/Serialization/JsonSerializationContext.cs index 618656432..b1c1aa156 100644 --- a/src/Beutl.Core/Serialization/JsonSerializationContext.cs +++ b/src/Beutl.Core/Serialization/JsonSerializationContext.cs @@ -2,28 +2,21 @@ namespace Beutl.Serialization; -public partial class JsonSerializationContext : IJsonSerializationContext +public partial class JsonSerializationContext( + Type ownerType, ISerializationErrorNotifier errorNotifier, + ICoreSerializationContext? parent = null, JsonObject? json = null) + : IJsonSerializationContext { - public readonly Dictionary _knownTypes = new(); - private readonly JsonObject _json; + public readonly Dictionary _knownTypes = []; + private readonly JsonObject _json = json ?? []; - public JsonSerializationContext( - Type ownerType, ISerializationErrorNotifier errorNotifier, - ICoreSerializationContext? parent = null, JsonObject? json = null) - { - OwnerType = ownerType; - Parent = parent; - ErrorNotifier = errorNotifier; - _json = json ?? new JsonObject(); - } - - public ICoreSerializationContext? Parent { get; } + public ICoreSerializationContext? Parent { get; } = parent; public CoreSerializationMode Mode => CoreSerializationMode.ReadWrite; - public Type OwnerType { get; } + public Type OwnerType { get; } = ownerType; - public ISerializationErrorNotifier ErrorNotifier { get; } + public ISerializationErrorNotifier ErrorNotifier { get; } = errorNotifier; public JsonObject GetJsonObject() { diff --git a/src/Beutl.Core/Serialization/RelaySerializationErrorNotifier.cs b/src/Beutl.Core/Serialization/RelaySerializationErrorNotifier.cs index 104c10bc5..cf63a9e6d 100644 --- a/src/Beutl.Core/Serialization/RelaySerializationErrorNotifier.cs +++ b/src/Beutl.Core/Serialization/RelaySerializationErrorNotifier.cs @@ -1,16 +1,10 @@ namespace Beutl.Serialization; -public sealed class RelaySerializationErrorNotifier : ISerializationErrorNotifier +public sealed class RelaySerializationErrorNotifier(ISerializationErrorNotifier parent, string? prependPath) : ISerializationErrorNotifier { - public RelaySerializationErrorNotifier(ISerializationErrorNotifier parent, string? prependPath) - { - Parent = parent; - Prepend = prependPath; - } - - public ISerializationErrorNotifier Parent { get; } + public ISerializationErrorNotifier Parent { get; } = parent; - public string? Prepend { get; } + public string? Prepend { get; } = prependPath; public void NotifyError(string path, string message, Exception? ex = null) { diff --git a/src/Beutl.Core/Serialization/SerializationErrorCollector.cs b/src/Beutl.Core/Serialization/SerializationErrorCollector.cs index 3327b5859..7f8f17f92 100644 --- a/src/Beutl.Core/Serialization/SerializationErrorCollector.cs +++ b/src/Beutl.Core/Serialization/SerializationErrorCollector.cs @@ -2,7 +2,7 @@ public class SerializationErrorCollector : ISerializationErrorNotifier { - public List Errors { get; } = new(); + public List Errors { get; } = []; public void NotifyError(string path, string message, Exception? ex = null) { diff --git a/src/Beutl.Core/Serialization/StringValuePair.cs b/src/Beutl.Core/Serialization/StringValuePair.cs index f5642e895..9db0980ef 100644 --- a/src/Beutl.Core/Serialization/StringValuePair.cs +++ b/src/Beutl.Core/Serialization/StringValuePair.cs @@ -3,28 +3,9 @@ namespace Beutl.Serialization; [StructLayout(LayoutKind.Sequential)] -internal class StringValuePair +internal class StringValuePair(string key, T value) { - private string _key; // Do not rename (binary serialization) - private T _value; // Do not rename (binary serialization) + public string Key { get; set; } = key; - // Constructs a new DictionaryEnumerator by setting the Key - // and Value fields appropriately. - public StringValuePair(string key, T value) - { - _key = key; - _value = value; - } - - public string Key - { - get => _key; - set => _key = value; - } - - public T Value - { - get => _value; - set => _value = value; - } + public T Value { get; set; } = value; } diff --git a/src/Beutl.Core/Services/LibraryService.cs b/src/Beutl.Core/Services/LibraryService.cs index e2e0d5809..ca12a504c 100644 --- a/src/Beutl.Core/Services/LibraryService.cs +++ b/src/Beutl.Core/Services/LibraryService.cs @@ -25,15 +25,9 @@ protected internal virtual void SetLibraryService(LibraryService libraryService) } } -public sealed class MultipleTypeLibraryItem : LibraryItem +public sealed class MultipleTypeLibraryItem(string displayName, string? description = null) : LibraryItem(displayName, description) { - private readonly Dictionary _types; - - public MultipleTypeLibraryItem(string displayName, string? description = null) - : base(displayName, description) - { - _types = new Dictionary(); - } + private readonly Dictionary _types = []; public IReadOnlyDictionary Types => _types; @@ -45,34 +39,24 @@ public MultipleTypeLibraryItem Bind(string format) } } -public sealed class SingleTypeLibraryItem : LibraryItem +public sealed class SingleTypeLibraryItem( + string format, + Type implementationType, + string displayName, + string? description = null) + : LibraryItem(displayName, description) { - public SingleTypeLibraryItem( - string format, - Type implementationType, - string displayName, - string? description = null) - : base(displayName, description) - { - Format = format; - ImplementationType = implementationType; - } + public string Format { get; } = format; - public string Format { get; } - - public Type ImplementationType { get; } + public Type ImplementationType { get; } = implementationType; } -public sealed class GroupLibraryItem : LibraryItem +public sealed class GroupLibraryItem(string displayName, string? description = null) + : LibraryItem(displayName, description) { - private readonly List _items = new(); + private readonly List _items = []; private readonly object _lock = new(); - public GroupLibraryItem(string displayName, string? description = null) - : base(displayName, description) - { - } - public IReadOnlyList Items => _items; public void Merge(IReadOnlyList items) @@ -201,8 +185,8 @@ public static class KnownLibraryItemFormats public sealed class LibraryService { - private readonly List _items = new(); - private readonly Dictionary> _formatToType = new(); + private readonly List _items = []; + private readonly Dictionary> _formatToType = []; private readonly object _lock = new(); internal int _totalCount; @@ -282,7 +266,7 @@ private HashSet GetHashSet(string format) } else { - hashset = new HashSet(); + hashset = []; _formatToType.Add(format, hashset); return hashset; } diff --git a/src/Beutl.Core/StaticProperty.cs b/src/Beutl.Core/StaticProperty.cs index e330bf1c7..ad507832c 100644 --- a/src/Beutl.Core/StaticProperty.cs +++ b/src/Beutl.Core/StaticProperty.cs @@ -2,30 +2,20 @@ namespace Beutl; -public abstract class StaticProperty : CoreProperty +public abstract class StaticProperty(string name, Type ownerType, CorePropertyMetadata metadata) + : CoreProperty(name, ownerType, metadata) { - public StaticProperty(string name, Type ownerType, CorePropertyMetadata metadata) - : base(name, ownerType, metadata) - { - } - internal abstract void RouteSetTypedValue(ICoreObject o, T? value); internal abstract T? RouteGetTypedValue(ICoreObject o); } -public class StaticProperty : StaticProperty, IStaticProperty +public class StaticProperty(string name, Func getter, Action? setter, CorePropertyMetadata metadata) + : StaticProperty(name, typeof(TOwner), metadata), IStaticProperty { - public StaticProperty(string name, Func getter, Action? setter, CorePropertyMetadata metadata) - : base(name, typeof(TOwner), metadata) - { - Getter = getter; - Setter = setter; - } - - public Func Getter { get; } + public Func Getter { get; } = getter; - public Action? Setter { get; } + public Action? Setter { get; } = setter; public bool CanRead => true; diff --git a/src/Beutl.Core/TypeFormat.cs b/src/Beutl.Core/TypeFormat.cs index 6c77961e9..522e51779 100644 --- a/src/Beutl.Core/TypeFormat.cs +++ b/src/Beutl.Core/TypeFormat.cs @@ -265,7 +265,7 @@ private static void TakeGenericArguments(Span tokens, out Span gen private static Type[] ParseGenericTypes(Span tokens) { if (tokens.Length == 0) - return Array.Empty(); + return []; var list = new List(); @@ -346,19 +346,12 @@ private static string TakeTypeNameTokens(Span tokens, out Span gen } } - internal class TypeNameFormatter + internal class TypeNameFormatter(Type type) { - private readonly Type _type; - - public TypeNameFormatter(Type type) - { - _type = type; - } - private void WriteNamespace(StringBuilder sb) { - string? asmName = _type.Assembly.GetName().Name; - string? ns = _type.Namespace; + string? asmName = type.Assembly.GetName().Name; + string? ns = type.Namespace; if (ns != null) { if (asmName != null) @@ -380,7 +373,7 @@ private void WriteNamespace(StringBuilder sb) public string Format() { var sb = new StringBuilder(); - string? asmName = _type.Assembly.GetName().Name; + string? asmName = type.Assembly.GetName().Name; if (asmName != null) { sb.Append('['); @@ -390,7 +383,7 @@ public string Format() WriteNamespace(sb); - WriteTypeName(sb, _type); + WriteTypeName(sb, type); return sb.ToString(); } @@ -442,21 +435,14 @@ private static string TrimTypeName(string typeName) } } - internal class TypeNameTokenizer + internal class TypeNameTokenizer(string s) { - private readonly string _s; - - public TypeNameTokenizer(string s) - { - _s = s; - } - public List Tokenize() { var list = new List(); - for (int i = 0; i < _s.Length; i++) + for (int i = 0; i < s.Length; i++) { - char c = _s[i]; + char c = s[i]; if (IsKigou(c)) { switch (c) @@ -489,19 +475,19 @@ public List Tokenize() int start = i; while (true) { - c = _s[i]; + c = s[i]; if (IsKigou(c)) { - list.Add(new(TokenType.Part, _s.Substring(start, i - start))); + list.Add(new(TokenType.Part, s.Substring(start, i - start))); i--; break; } i++; - if (i >= _s.Length) + if (i >= s.Length) { - list.Add(new(TokenType.Part, _s.Substring(start, i - start))); + list.Add(new(TokenType.Part, s.Substring(start, i - start))); break; } } diff --git a/src/Beutl.Core/Validation/MultipleValidator.cs b/src/Beutl.Core/Validation/MultipleValidator.cs index 069766df4..959eab9f9 100644 --- a/src/Beutl.Core/Validation/MultipleValidator.cs +++ b/src/Beutl.Core/Validation/MultipleValidator.cs @@ -2,14 +2,9 @@ namespace Beutl.Validation; -public sealed class MultipleValidator : IValidator +public sealed class MultipleValidator(IValidator[] items) : IValidator { - public MultipleValidator(IValidator[] items) - { - Items = items; - } - - public IValidator[] Items { get; } + public IValidator[] Items { get; } = items; public bool TryCoerce(ValidationContext context, ref T? value) { diff --git a/src/Beutl.Core/Validation/ValidationContext.cs b/src/Beutl.Core/Validation/ValidationContext.cs index f682ef6a2..9c0896f69 100644 --- a/src/Beutl.Core/Validation/ValidationContext.cs +++ b/src/Beutl.Core/Validation/ValidationContext.cs @@ -1,14 +1,8 @@ namespace Beutl.Validation; -public readonly struct ValidationContext +public readonly struct ValidationContext(object? target, CoreProperty? property) { - public ValidationContext(object? target, CoreProperty? property) - { - Target = target; - Property = property; - } + public object? Target { get; } = target; - public object? Target { get; } - - public CoreProperty? Property { get; } + public CoreProperty? Property { get; } = property; } diff --git a/src/Beutl.Engine/Animation/Animatable.cs b/src/Beutl.Engine/Animation/Animatable.cs index 8519cc568..d2631047c 100644 --- a/src/Beutl.Engine/Animation/Animatable.cs +++ b/src/Beutl.Engine/Animation/Animatable.cs @@ -19,7 +19,7 @@ static Animatable() protected Animatable() { - Animations = new(); + Animations = []; } [NotAutoSerialized] diff --git a/src/Beutl.Engine/Animation/AnimatorRegistry.cs b/src/Beutl.Engine/Animation/AnimatorRegistry.cs index c604fc4e7..c46c12f35 100644 --- a/src/Beutl.Engine/Animation/AnimatorRegistry.cs +++ b/src/Beutl.Engine/Animation/AnimatorRegistry.cs @@ -8,8 +8,8 @@ namespace Beutl.Animation; public static class AnimatorRegistry { - private static readonly List<(Func Condition, Type Animator)> s_animators = new() - { + private static readonly List<(Func Condition, Type Animator)> s_animators = + [ (type => typeof(bool).IsAssignableFrom(type), typeof(BoolAnimator)), (type => typeof(byte).IsAssignableFrom(type), typeof(ByteAnimator)), (type => typeof(Color).IsAssignableFrom(type), typeof(ColorAnimator)), @@ -38,7 +38,7 @@ public static class AnimatorRegistry (type => typeof(Vector3).IsAssignableFrom(type), typeof(Vector3Animator)), (type => typeof(Vector4).IsAssignableFrom(type), typeof(Vector4Animator)), (type => typeof(Graphics.Vector).IsAssignableFrom(type), typeof(VectorAnimator)), - }; + ]; public static Animator CreateAnimator() { diff --git a/src/Beutl.Engine/Animation/KeyFrameAnimation.cs b/src/Beutl.Engine/Animation/KeyFrameAnimation.cs index 7d80ff76c..b0617d66a 100644 --- a/src/Beutl.Engine/Animation/KeyFrameAnimation.cs +++ b/src/Beutl.Engine/Animation/KeyFrameAnimation.cs @@ -114,7 +114,7 @@ public bool UseGlobalClock set => SetAndRaise(UseGlobalClockProperty, ref _useGlobalClock, value); } - public KeyFrames KeyFrames { get; } = new(); + public KeyFrames KeyFrames { get; } = []; public CoreProperty Property { diff --git a/src/Beutl.Engine/Audio/Effects/Delay.cs b/src/Beutl.Engine/Audio/Effects/Delay.cs index d927f94c9..5e9b9a8cc 100644 --- a/src/Beutl.Engine/Audio/Effects/Delay.cs +++ b/src/Beutl.Engine/Audio/Effects/Delay.cs @@ -149,16 +149,10 @@ public override ISoundProcessor CreateProcessor() return new DelayProcessor(this); } - private sealed class DelayProcessor : ISoundProcessor + private sealed class DelayProcessor(Delay delay) : ISoundProcessor { - private readonly Delay _delay; private SimpleCircularBuffer? _delayBuffer; - public DelayProcessor(Delay delay) - { - _delay = delay; - } - ~DelayProcessor() { _delayBuffer?.Dispose(); @@ -181,10 +175,10 @@ private void Initialize(Pcm pcm) public void Process(in Pcm src, out Pcm dst) { int sampleRate = src.SampleRate; - float delayTime = _delay._delayTime / 1000f; - float feedback = _delay._feedback / 100f; - float dryMix = _delay._dryMix / 100f; - float wetMix = _delay._wetMix / 100f; + float delayTime = delay._delayTime / 1000f; + float feedback = delay._feedback / 100f; + float dryMix = delay._dryMix / 100f; + float wetMix = delay._wetMix / 100f; Initialize(src); Span channel_data = src.DataSpan; diff --git a/src/Beutl.Engine/Audio/Effects/SoundEffectGroup.cs b/src/Beutl.Engine/Audio/Effects/SoundEffectGroup.cs index cc5ccd3a2..e1f60ba58 100644 --- a/src/Beutl.Engine/Audio/Effects/SoundEffectGroup.cs +++ b/src/Beutl.Engine/Audio/Effects/SoundEffectGroup.cs @@ -19,7 +19,7 @@ static SoundEffectGroup() public SoundEffectGroup() { - _children = new SoundEffects(); + _children = []; _children.Invalidated += (_, e) => RaiseInvalidated(e); } diff --git a/src/Beutl.Engine/Audio/Effects/SoundProcessorGroup.cs b/src/Beutl.Engine/Audio/Effects/SoundProcessorGroup.cs index 4043bb84e..83f0f53a5 100644 --- a/src/Beutl.Engine/Audio/Effects/SoundProcessorGroup.cs +++ b/src/Beutl.Engine/Audio/Effects/SoundProcessorGroup.cs @@ -5,7 +5,7 @@ namespace Beutl.Audio.Effects; internal sealed class SoundProcessorGroup : ISoundProcessor { - public ISoundProcessor[] Processors { get; set; } = Array.Empty(); + public ISoundProcessor[] Processors { get; set; } = []; public void Dispose() { @@ -14,7 +14,7 @@ public void Dispose() item.Dispose(); } - Processors = Array.Empty(); + Processors = []; } public void Process(in Pcm src, out Pcm dst) diff --git a/src/Beutl.Engine/Audio/Platforms/XAudio2/XAudioSource.cs b/src/Beutl.Engine/Audio/Platforms/XAudio2/XAudioSource.cs index 42b13af38..93b9266ec 100644 --- a/src/Beutl.Engine/Audio/Platforms/XAudio2/XAudioSource.cs +++ b/src/Beutl.Engine/Audio/Platforms/XAudio2/XAudioSource.cs @@ -2,16 +2,10 @@ namespace Beutl.Audio.Platforms.XAudio2; -public sealed class XAudioSource : IDisposable +public sealed class XAudioSource(XAudioContext context) : IDisposable { - private readonly XAudioContext _context; private IXAudio2SourceVoice? _sourceVoice; - public XAudioSource(XAudioContext context) - { - _context = context; - } - public int BuffersQueued => _sourceVoice?.State.BuffersQueued ?? -1; public void Dispose() @@ -39,7 +33,7 @@ public void QueueBuffer(XAudioBuffer buffer) { if (_sourceVoice == null) { - _sourceVoice = _context.Device.CreateSourceVoice(buffer.Format!); + _sourceVoice = context.Device.CreateSourceVoice(buffer.Format!); } _sourceVoice.SubmitSourceBuffer(buffer.Buffer); diff --git a/src/Beutl.Engine/Audio/SoundNode.cs b/src/Beutl.Engine/Audio/SoundNode.cs index f45d84c48..79e7948f9 100644 --- a/src/Beutl.Engine/Audio/SoundNode.cs +++ b/src/Beutl.Engine/Audio/SoundNode.cs @@ -2,13 +2,8 @@ namespace Beutl.Audio; -public class SoundNode : INode +public class SoundNode(Sound sound) : INode { - public SoundNode(Sound sound) - { - Sound = sound; - } - ~SoundNode() { if (IsDisposed) @@ -18,7 +13,7 @@ public SoundNode(Sound sound) } } - public Sound Sound { get; } + public Sound Sound { get; } = sound; public bool IsDisposed { get; private set; } diff --git a/src/Beutl.Engine/Graphics/BrushConstructor.cs b/src/Beutl.Engine/Graphics/BrushConstructor.cs index eb016bd2b..c36f33d55 100644 --- a/src/Beutl.Engine/Graphics/BrushConstructor.cs +++ b/src/Beutl.Engine/Graphics/BrushConstructor.cs @@ -7,23 +7,15 @@ namespace Beutl.Graphics; -public readonly struct BrushConstructor +public readonly struct BrushConstructor(Size targetSize, IBrush? brush, BlendMode blendMode, IImmediateCanvasFactory factory) { - public BrushConstructor(Size targetSize, IBrush? brush, BlendMode blendMode, IImmediateCanvasFactory factory) - { - TargetSize = targetSize; - Brush = brush; - BlendMode = blendMode; - Factory = factory; - } - - public Size TargetSize { get; } + public Size TargetSize { get; } = targetSize; - public IBrush? Brush { get; } + public IBrush? Brush { get; } = brush; - public BlendMode BlendMode { get; } + public BlendMode BlendMode { get; } = blendMode; - public IImmediateCanvasFactory Factory { get; } + public IImmediateCanvasFactory Factory { get; } = factory; public void ConfigurePaint(SKPaint paint) { diff --git a/src/Beutl.Engine/Graphics/ColorMatrix.cs b/src/Beutl.Engine/Graphics/ColorMatrix.cs index 79de5a1eb..81bf19217 100644 --- a/src/Beutl.Engine/Graphics/ColorMatrix.cs +++ b/src/Beutl.Engine/Graphics/ColorMatrix.cs @@ -7,39 +7,13 @@ namespace Beutl.Graphics; [StructLayout(LayoutKind.Sequential)] -public readonly struct ColorMatrix : IEquatable +public readonly struct ColorMatrix( + float m11, float m12, float m13, float m14, float m15, + float m21, float m22, float m23, float m24, float m25, + float m31, float m32, float m33, float m34, float m35, + float m41, float m42, float m43, float m44, float m45) + : IEquatable { - public ColorMatrix( - float m11, float m12, float m13, float m14, float m15, - float m21, float m22, float m23, float m24, float m25, - float m31, float m32, float m33, float m34, float m35, - float m41, float m42, float m43, float m44, float m45) - { - M11 = m11; - M12 = m12; - M13 = m13; - M14 = m14; - M15 = m15; - - M21 = m21; - M22 = m22; - M23 = m23; - M24 = m24; - M25 = m25; - - M31 = m31; - M32 = m32; - M33 = m33; - M34 = m34; - M35 = m35; - - M41 = m41; - M42 = m42; - M43 = m43; - M44 = m44; - M45 = m45; - } - public static ColorMatrix Identity { get; } = new ColorMatrix( 1F, 0F, 0F, 0F, 0F, @@ -49,45 +23,45 @@ public ColorMatrix( public bool IsIdentity => Equals(Identity); - public float M11 { get; } + public float M11 { get; } = m11; - public float M12 { get; } + public float M12 { get; } = m12; - public float M13 { get; } + public float M13 { get; } = m13; - public float M14 { get; } + public float M14 { get; } = m14; - public float M15 { get; } + public float M15 { get; } = m15; - public float M21 { get; } + public float M21 { get; } = m21; - public float M22 { get; } + public float M22 { get; } = m22; - public float M23 { get; } + public float M23 { get; } = m23; - public float M24 { get; } + public float M24 { get; } = m24; - public float M25 { get; } + public float M25 { get; } = m25; - public float M31 { get; } + public float M31 { get; } = m31; - public float M32 { get; } + public float M32 { get; } = m32; - public float M33 { get; } + public float M33 { get; } = m33; - public float M34 { get; } + public float M34 { get; } = m34; - public float M35 { get; } + public float M35 { get; } = m35; - public float M41 { get; } + public float M41 { get; } = m41; - public float M42 { get; } + public float M42 { get; } = m42; - public float M43 { get; } + public float M43 { get; } = m43; - public float M44 { get; } + public float M44 { get; } = m44; - public float M45 { get; } + public float M45 { get; } = m45; public static ColorMatrix CreateFromSpan(ReadOnlySpan span) { @@ -143,13 +117,13 @@ public static ColorMatrix CreateContrast(float contrast) public float[] ToArray() { - return new float[] - { + return + [ M11, M12, M13, M14, M15, M21, M22, M23, M24, M25, M31, M32, M33, M34, M35, M41, M42, M43, M44, M45, - }; + ]; } internal void ToArrayForSkia(float[] array) @@ -361,22 +335,13 @@ internal static void ToSkiaColorMatrix(Span array) array[19] *= 255; } - internal struct Vector5 + internal struct Vector5(float x, float y, float z, float w, float v) { - public float X; - public float Y; - public float Z; - public float W; - public float V; - - public Vector5(float x, float y, float z, float w, float v) - { - X = x; - Y = y; - Z = z; - W = w; - V = v; - } + public float X = x; + public float Y = y; + public float Z = z; + public float W = w; + public float V = v; public static Vector5 operator *(in Vector5 left, in Vector5 right) { @@ -415,20 +380,12 @@ public Vector5(float x, float y, float z, float w, float v) } } - internal struct Matrix4x5 + internal struct Matrix4x5(Vector5 x, Vector5 y, Vector5 z, Vector5 w) { - public Vector5 X; - public Vector5 Y; - public Vector5 Z; - public Vector5 W; - - public Matrix4x5(Vector5 x, Vector5 y, Vector5 z, Vector5 w) - { - X = x; - Y = y; - Z = z; - W = w; - } + public Vector5 X = x; + public Vector5 Y = y; + public Vector5 Z = z; + public Vector5 W = w; public readonly ColorMatrix AsColorMatrix() => Unsafe.As(ref Unsafe.AsRef(in this)); diff --git a/src/Beutl.Engine/Graphics/CubeFile.cs b/src/Beutl.Engine/Graphics/CubeFile.cs index 6099a4c59..4fe5012dd 100644 --- a/src/Beutl.Engine/Graphics/CubeFile.cs +++ b/src/Beutl.Engine/Graphics/CubeFile.cs @@ -52,12 +52,12 @@ public Vector3 TrilinearInterplate(Vec3b color) int index = pos[0] + pos[1] * lut_size + pos[2] * lut_size_2; - Span next_index = stackalloc int[3] - { + Span next_index = + [ 1, lut_size, lut_size_2 - }; + ]; if (index % lut_size == lut_size - 1) { diff --git a/src/Beutl.Engine/Graphics/DrawableGroup.cs b/src/Beutl.Engine/Graphics/DrawableGroup.cs index 057dba1f7..2bcef7919 100644 --- a/src/Beutl.Engine/Graphics/DrawableGroup.cs +++ b/src/Beutl.Engine/Graphics/DrawableGroup.cs @@ -8,7 +8,7 @@ namespace Beutl.Graphics; public sealed class DrawableGroup : Drawable { public static readonly CoreProperty ChildrenProperty; - private readonly Drawables _children = new(); + private readonly Drawables _children = []; static DrawableGroup() { @@ -19,7 +19,6 @@ static DrawableGroup() public DrawableGroup() { - _children = new Drawables(); _children.Invalidated += (_, e) => RaiseInvalidated(e); _children.Attached += HierarchicalChildren.Add; _children.Detached += item => HierarchicalChildren.Remove(item); diff --git a/src/Beutl.Engine/Graphics/FilterEffects/DynamicEnumTest.cs b/src/Beutl.Engine/Graphics/FilterEffects/DynamicEnumTest.cs index f273d4f60..5acc49d0d 100644 --- a/src/Beutl.Engine/Graphics/FilterEffects/DynamicEnumTest.cs +++ b/src/Beutl.Engine/Graphics/FilterEffects/DynamicEnumTest.cs @@ -30,15 +30,9 @@ public override void ApplyTo(FilterEffectContext context) { } - public sealed class MyDynamicEnumValue : IDynamicEnumValue + public sealed class MyDynamicEnumValue(string display/*, object? metadata*/) : IDynamicEnumValue { - // metadataは例えばEnumに関連づけられている、Idなど - public MyDynamicEnumValue(string display/*, object? metadata*/) - { - DisplayName = display; - } - - public string DisplayName { get; } + public string DisplayName { get; } = display; public bool Equals(IDynamicEnumValue? other) { @@ -48,13 +42,13 @@ public bool Equals(IDynamicEnumValue? other) public sealed class MyDynamicEnum : IDynamicEnum { - private static readonly CoreList s_enumValues = new() - { + private static readonly CoreList s_enumValues = + [ new MyDynamicEnumValue("Enum 1"), new MyDynamicEnumValue("Enum 2"), new MyDynamicEnumValue("Enum 3"), new MyDynamicEnumValue("Enum 4"), - }; + ]; public MyDynamicEnum() { diff --git a/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectContext.cs b/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectContext.cs index 50c06b7ea..2119d36a0 100644 --- a/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectContext.cs +++ b/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectContext.cs @@ -11,18 +11,11 @@ namespace Beutl.Graphics.Effects; -internal sealed class ArrayPooledObjectPolicy : IPooledObjectPolicy +internal sealed class ArrayPooledObjectPolicy(int length) : IPooledObjectPolicy { - private readonly int _length; - - public ArrayPooledObjectPolicy(int length) - { - _length = length; - } - public T[] Create() { - return new T[_length]; + return new T[length]; } public bool Return(T[] obj) @@ -50,7 +43,7 @@ public FilterEffectContext(Rect bounds) { Bounds = OriginalBounds = bounds; _versions = new PooledList<(FilterEffect, int)>(ClearMode.Always); - _items = new PooledList(); + _items = []; } private FilterEffectContext(FilterEffectContext obj) diff --git a/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectGroup.cs b/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectGroup.cs index 06ec3d0ee..b2a1b2a6b 100644 --- a/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectGroup.cs +++ b/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectGroup.cs @@ -19,7 +19,7 @@ static FilterEffectGroup() public FilterEffectGroup() { - _children = new FilterEffects(); + _children = []; _children.Invalidated += (_, e) => RaiseInvalidated(e); } diff --git a/src/Beutl.Engine/Graphics/Matrix.cs b/src/Beutl.Engine/Graphics/Matrix.cs index 8a7be92ee..f2f6120d4 100644 --- a/src/Beutl.Engine/Graphics/Matrix.cs +++ b/src/Beutl.Engine/Graphics/Matrix.cs @@ -20,9 +20,24 @@ namespace Beutl.Graphics; /// /// Note: Skia.SkMatrix uses a transposed layout (where for example skewX/skewY and perspp0/tranX are swapped). /// +/// +/// Initializes a new instance of the struct. +/// +/// The first element of the first row. +/// The second element of the first row. +/// The third element of the first row. +/// The first element of the second row. +/// The second element of the second row. +/// The third element of the second row. +/// The first element of the third row. +/// The second element of the third row. +/// The third element of the third row. [JsonConverter(typeof(MatrixJsonConverter))] [TypeConverter(typeof(MatrixConverter))] -public readonly struct Matrix +public readonly struct Matrix( + float scaleX, float skewY, float persX, + float skewX, float scaleY, float persY, + float offsetX, float offsetY, float persZ) : IEquatable, IParsable, ISpanParsable, @@ -40,49 +55,16 @@ public readonly struct Matrix /// The first element of the third row. /// The second element of the third row. public Matrix( - float scaleX, - float skewY, - float skewX, - float scaleY, - float offsetX, - float offsetY) : this(scaleX, skewY, 0, skewX, scaleY, 0, offsetX, offsetY, 1) + float scaleX, float skewY, + float skewX, float scaleY, + float offsetX, float offsetY) + : this( + scaleX, skewY, 0, + skewX, scaleY, 0, + offsetX, offsetY, 1) { } - /// - /// Initializes a new instance of the struct. - /// - /// The first element of the first row. - /// The second element of the first row. - /// The third element of the first row. - /// The first element of the second row. - /// The second element of the second row. - /// The third element of the second row. - /// The first element of the third row. - /// The second element of the third row. - /// The third element of the third row. - public Matrix( - float scaleX, - float skewY, - float persX, - float skewX, - float scaleY, - float persY, - float offsetX, - float offsetY, - float persZ) - { - M11 = scaleX; - M12 = skewY; - M13 = persX; - M21 = skewX; - M22 = scaleY; - M23 = persY; - M31 = offsetX; - M32 = offsetY; - M33 = persZ; - } - /// /// Returns the multiplicative identity matrix. /// @@ -104,47 +86,47 @@ public Matrix( /// /// The first element of the first row (scaleX). /// - public float M11 { get; } + public float M11 { get; } = scaleX; /// /// The second element of the first row (skewY). /// - public float M12 { get; } + public float M12 { get; } = skewY; /// /// The third element of the first row (persX: input x-axis perspective factor). /// - public float M13 { get; } + public float M13 { get; } = persX; /// /// The first element of the second row (skewX). /// - public float M21 { get; } + public float M21 { get; } = skewX; /// /// The second element of the second row (scaleY). /// - public float M22 { get; } + public float M22 { get; } = scaleY; /// /// The third element of the second row (persY: input y-axis perspective factor). /// - public float M23 { get; } + public float M23 { get; } = persY; /// /// The first element of the third row (offsetX/translateX). /// - public float M31 { get; } + public float M31 { get; } = offsetX; /// /// The second element of the third row (offsetY/translateY). /// - public float M32 { get; } + public float M32 { get; } = offsetY; /// /// The third element of the third row (persZ: perspective scale factor). /// - public float M33 { get; } + public float M33 { get; } = persZ; static int ITupleConvertible.TupleLength => 9; diff --git a/src/Beutl.Engine/Graphics/Operations/AlphaMapOperation.cs b/src/Beutl.Engine/Graphics/Operations/AlphaMapOperation.cs index 7ac311f61..839a27c4a 100644 --- a/src/Beutl.Engine/Graphics/Operations/AlphaMapOperation.cs +++ b/src/Beutl.Engine/Graphics/Operations/AlphaMapOperation.cs @@ -2,19 +2,10 @@ namespace Beutl.Graphics.Operations; -internal readonly unsafe struct AlphaMapOperation +internal readonly unsafe struct AlphaMapOperation(Bgra8888* src, Grayscale8* dst) { - private readonly Bgra8888* _src; - private readonly Grayscale8* _dst; - - public AlphaMapOperation(Bgra8888* src, Grayscale8* dst) - { - _src = src; - _dst = dst; - } - public void Invoke(int pos) { - _dst[pos] = new(_src[pos].A); + dst[pos] = new(src[pos].A); } } diff --git a/src/Beutl.Engine/Graphics/Operations/AlphaSubtractOperation.cs b/src/Beutl.Engine/Graphics/Operations/AlphaSubtractOperation.cs index 028e4d771..f827b71ee 100644 --- a/src/Beutl.Engine/Graphics/Operations/AlphaSubtractOperation.cs +++ b/src/Beutl.Engine/Graphics/Operations/AlphaSubtractOperation.cs @@ -2,19 +2,10 @@ namespace Beutl.Graphics.Operations; -public readonly unsafe struct AlphaSubtractOperation +public readonly unsafe struct AlphaSubtractOperation(Bgra8888* data, Bgra8888* mask) { - private readonly Bgra8888* _data; - private readonly Bgra8888* _mask; - - public AlphaSubtractOperation(Bgra8888* data, Bgra8888* mask) - { - _data = data; - _mask = mask; - } - public readonly void Invoke(int pos) { - _data[pos].A = (byte)(_data[pos].A & _mask[pos].A); + data[pos].A = (byte)(data[pos].A & mask[pos].A); } } diff --git a/src/Beutl.Engine/Graphics/Operations/ConvertOperation.cs b/src/Beutl.Engine/Graphics/Operations/ConvertOperation.cs index a0e5750c5..775ebd097 100644 --- a/src/Beutl.Engine/Graphics/Operations/ConvertOperation.cs +++ b/src/Beutl.Engine/Graphics/Operations/ConvertOperation.cs @@ -2,22 +2,13 @@ namespace Beutl.Graphics.Operations; -public readonly unsafe struct ConvertOperation +public readonly unsafe struct ConvertOperation(T1* src, T2* dst) where T1 : unmanaged, IPixel where T2 : unmanaged, IPixel { - private readonly T1* _src; - private readonly T2* _dst; - - public ConvertOperation(T1* src, T2* dst) - { - _src = src; - _dst = dst; - } - public readonly void Invoke(int p) { - var color = _src[p].ToColor(); - _dst[p] = default(T2).FromColor(color); + var color = src[p].ToColor(); + dst[p] = default(T2).FromColor(color); } } diff --git a/src/Beutl.Engine/Graphics/Operations/CropOperation.cs b/src/Beutl.Engine/Graphics/Operations/CropOperation.cs index 9789259fb..328790761 100644 --- a/src/Beutl.Engine/Graphics/Operations/CropOperation.cs +++ b/src/Beutl.Engine/Graphics/Operations/CropOperation.cs @@ -3,25 +3,14 @@ namespace Beutl.Graphics.Operations; -public readonly unsafe struct CropOperation +public readonly unsafe struct CropOperation(Bitmap src, Bitmap dst, PixelRect roi) where TPixel : unmanaged, IPixel { - private readonly Bitmap _src; - private readonly Bitmap _dst; - private readonly PixelRect _roi; - - public CropOperation(Bitmap src, Bitmap dst, PixelRect roi) - { - _src = src; - _dst = dst; - _roi = roi; - } - public readonly void Invoke(int y) { - var sourceRow = _src[y + _roi.Y].Slice(_roi.X, _roi.Width); - var targetRow = _dst[y]; + var sourceRow = src[y + roi.Y].Slice(roi.X, roi.Width); + var targetRow = dst[y]; - sourceRow.Slice(0, _roi.Width).CopyTo(targetRow); + sourceRow.Slice(0, roi.Width).CopyTo(targetRow); } } diff --git a/src/Beutl.Engine/Graphics/Operations/ReplaceOperation.cs b/src/Beutl.Engine/Graphics/Operations/ReplaceOperation.cs index a990edc60..92a8d5336 100644 --- a/src/Beutl.Engine/Graphics/Operations/ReplaceOperation.cs +++ b/src/Beutl.Engine/Graphics/Operations/ReplaceOperation.cs @@ -3,24 +3,13 @@ namespace Beutl.Graphics.Operations; -public readonly unsafe struct ReplaceOperation +public readonly unsafe struct ReplaceOperation(Bitmap src, Bitmap dst, PixelRect roi) where TPixel : unmanaged, IPixel { - private readonly Bitmap _src; - private readonly Bitmap _dst; - private readonly PixelRect _roi; - - public ReplaceOperation(Bitmap src, Bitmap dst, PixelRect roi) - { - _src = src; - _dst = dst; - _roi = roi; - } - public readonly void Invoke(int y) { - var sourceRow = _src[y]; - var targetRow = _dst[y + _roi.Y].Slice(_roi.X, _roi.Width); + var sourceRow = src[y]; + var targetRow = dst[y + roi.Y].Slice(roi.X, roi.Width); sourceRow.CopyTo(targetRow); } diff --git a/src/Beutl.Engine/Graphics/Point.cs b/src/Beutl.Engine/Graphics/Point.cs index 099631393..418af13bf 100644 --- a/src/Beutl.Engine/Graphics/Point.cs +++ b/src/Beutl.Engine/Graphics/Point.cs @@ -14,9 +14,14 @@ namespace Beutl.Graphics; /// /// Defines a point. /// +/// +/// Initializes a new instance of the structure. +/// +/// The X position. +/// The Y position. [JsonConverter(typeof(PointJsonConverter))] [TypeConverter(typeof(PointConverter))] -public readonly struct Point +public readonly struct Point(float x, float y) : IEquatable, IParsable, IFormattable, @@ -35,26 +40,16 @@ public readonly struct Point IMultiplyOperators, ITupleConvertible { - /// - /// Initializes a new instance of the structure. - /// - /// The X position. - /// The Y position. - public Point(float x, float y) - { - X = x; - Y = y; - } /// /// Gets the X position. /// - public float X { get; } + public float X { get; } = x; /// /// Gets the Y position. /// - public float Y { get; } + public float Y { get; } = y; /// /// Gets a value indicating whether the X and Y coordinates are zero. diff --git a/src/Beutl.Engine/Graphics/Rect.cs b/src/Beutl.Engine/Graphics/Rect.cs index 5cf0babf7..f038e29aa 100644 --- a/src/Beutl.Engine/Graphics/Rect.cs +++ b/src/Beutl.Engine/Graphics/Rect.cs @@ -400,13 +400,13 @@ public bool Intersects(Rect rect) /// The bounding box public Rect TransformToAABB(Matrix matrix) { - ReadOnlySpan points = stackalloc Point[4] - { + ReadOnlySpan points = + [ TopLeft.Transform(matrix), TopRight.Transform(matrix), BottomRight.Transform(matrix), BottomLeft.Transform(matrix) - }; + ]; float left = float.MaxValue; float right = float.MinValue; diff --git a/src/Beutl.Engine/Graphics/RelativePoint.cs b/src/Beutl.Engine/Graphics/RelativePoint.cs index bbd7e9ba6..bf96da416 100644 --- a/src/Beutl.Engine/Graphics/RelativePoint.cs +++ b/src/Beutl.Engine/Graphics/RelativePoint.cs @@ -13,9 +13,14 @@ namespace Beutl.Graphics; /// /// Defines a point that may be defined relative to a containing element. /// +/// +/// Initializes a new instance of the struct. +/// +/// The point. +/// The unit. [JsonConverter(typeof(RelativePointJsonConverter))] [TypeConverter(typeof(RelativePointConverter))] -public readonly struct RelativePoint +public readonly struct RelativePoint(Point point, RelativeUnit unit) : IEquatable, IParsable, ISpanParsable, @@ -50,26 +55,15 @@ public RelativePoint(float x, float y, RelativeUnit unit) { } - /// - /// Initializes a new instance of the struct. - /// - /// The point. - /// The unit. - public RelativePoint(Point point, RelativeUnit unit) - { - Point = point; - Unit = unit; - } - /// /// Gets the point. /// - public Point Point { get; } + public Point Point { get; } = point; /// /// Gets the unit. /// - public RelativeUnit Unit { get; } + public RelativeUnit Unit { get; } = unit; /// /// Checks for equality between two s. diff --git a/src/Beutl.Engine/Graphics/RelativeRect.cs b/src/Beutl.Engine/Graphics/RelativeRect.cs index 7da603a46..efed9d224 100644 --- a/src/Beutl.Engine/Graphics/RelativeRect.cs +++ b/src/Beutl.Engine/Graphics/RelativeRect.cs @@ -19,7 +19,7 @@ public readonly struct RelativeRect IUtf8SpanFormattable, IEqualityOperators { - private static readonly char[] s_percentChar = { '%' }; + private static readonly char[] s_percentChar = ['%']; /// /// A rectangle that represents 100% of an area. diff --git a/src/Beutl.Engine/Graphics/Rendering/BlendModeNode.cs b/src/Beutl.Engine/Graphics/Rendering/BlendModeNode.cs index d6271cfd4..28024afa3 100644 --- a/src/Beutl.Engine/Graphics/Rendering/BlendModeNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/BlendModeNode.cs @@ -5,14 +5,9 @@ namespace Beutl.Graphics.Rendering; -public sealed class BlendModeNode : ContainerNode, ISupportRenderCache +public sealed class BlendModeNode(BlendMode blendMode) : ContainerNode, ISupportRenderCache { - public BlendModeNode(BlendMode blendMode) - { - BlendMode = blendMode; - } - - public BlendMode BlendMode { get; } + public BlendMode BlendMode { get; } = blendMode; public bool Equals(BlendMode blendMode) { diff --git a/src/Beutl.Engine/Graphics/Rendering/ClearNode.cs b/src/Beutl.Engine/Graphics/Rendering/ClearNode.cs index 3c8783b8f..0f258f257 100644 --- a/src/Beutl.Engine/Graphics/Rendering/ClearNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/ClearNode.cs @@ -2,15 +2,9 @@ namespace Beutl.Graphics.Rendering; -public sealed class ClearNode : DrawNode +public sealed class ClearNode(Color color) : DrawNode(Rect.Empty) { - public ClearNode(Color color) - : base(Rect.Empty) - { - Color = color; - } - - public Color Color { get; } + public Color Color { get; } = color; public bool Equals(Color color) { diff --git a/src/Beutl.Engine/Graphics/Rendering/ContainerNode.cs b/src/Beutl.Engine/Graphics/Rendering/ContainerNode.cs index 98307c36f..1d90963d2 100644 --- a/src/Beutl.Engine/Graphics/Rendering/ContainerNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/ContainerNode.cs @@ -4,7 +4,7 @@ namespace Beutl.Graphics.Rendering; public class ContainerNode : IGraphicNode { - private readonly List _children = new List(); + private readonly List _children = []; private bool _isBoundsDirty = true; private Rect _originalBounds; diff --git a/src/Beutl.Engine/Graphics/Rendering/DeferradCanvas.cs b/src/Beutl.Engine/Graphics/Rendering/DeferradCanvas.cs index 6e0028f43..044f87938 100644 --- a/src/Beutl.Engine/Graphics/Rendering/DeferradCanvas.cs +++ b/src/Beutl.Engine/Graphics/Rendering/DeferradCanvas.cs @@ -7,20 +7,12 @@ namespace Beutl.Graphics.Rendering; -public sealed class DeferradCanvas : ICanvas +public sealed class DeferradCanvas(ContainerNode container, PixelSize canvasSize = default) : ICanvas { - private readonly Stack<(ContainerNode, int)> _nodes; - private ContainerNode _container; + private readonly Stack<(ContainerNode, int)> _nodes = []; private int _drawOperationindex; - public DeferradCanvas(ContainerNode container, PixelSize canvasSize = default) - { - _container = container; - _nodes = new Stack<(ContainerNode, int)>(); - Size = canvasSize; - } - - public PixelSize Size { get; } + public PixelSize Size { get; } = canvasSize; public bool IsDisposed { get; } @@ -30,13 +22,13 @@ public DeferradCanvas(ContainerNode container, PixelSize canvasSize = default) private void Add(IGraphicNode node) { - if (_drawOperationindex < _container.Children.Count) + if (_drawOperationindex < container.Children.Count) { - _container.SetChild(_drawOperationindex, node); + container.SetChild(_drawOperationindex, node); } else { - _container.AddChild(node); + container.AddChild(node); } } @@ -53,25 +45,25 @@ private void AddAndPush(ContainerNode node, ContainerNode? old) private void Push(ContainerNode node) { - _nodes.Push((_container, _drawOperationindex + 1)); + _nodes.Push((container, _drawOperationindex + 1)); _drawOperationindex = 0; - _container = node; + container = node; } private T? Next() where T : class, IGraphicNode { - return _drawOperationindex < _container.Children.Count ? _container.Children[_drawOperationindex] as T : null; + return _drawOperationindex < container.Children.Count ? container.Children[_drawOperationindex] as T : null; } private IGraphicNode? Next() { - return _drawOperationindex < _container.Children.Count ? _container.Children[_drawOperationindex] : null; + return _drawOperationindex < container.Children.Count ? container.Children[_drawOperationindex] : null; } public void Dispose() { - _container.RemoveRange(_drawOperationindex, _container.Children.Count - _drawOperationindex); + container.RemoveRange(_drawOperationindex, container.Children.Count - _drawOperationindex); } public void Reset() @@ -231,9 +223,9 @@ public void Pop(int count = -1) while (count < 0 && _nodes.TryPop(out (ContainerNode, int) state)) { - _container.RemoveRange(_drawOperationindex, _container.Children.Count - _drawOperationindex); + container.RemoveRange(_drawOperationindex, container.Children.Count - _drawOperationindex); - _container = state.Item1; + container = state.Item1; _drawOperationindex = state.Item2; count++; @@ -244,9 +236,9 @@ public void Pop(int count = -1) while (_nodes.Count >= count && _nodes.TryPop(out (ContainerNode, int) state)) { - _container.RemoveRange(_drawOperationindex, _container.Children.Count - _drawOperationindex); + container.RemoveRange(_drawOperationindex, container.Children.Count - _drawOperationindex); - _container = state.Item1; + container = state.Item1; _drawOperationindex = state.Item2; } } diff --git a/src/Beutl.Engine/Graphics/Rendering/DrawableNode.cs b/src/Beutl.Engine/Graphics/Rendering/DrawableNode.cs index 4fab7979f..60099e14e 100644 --- a/src/Beutl.Engine/Graphics/Rendering/DrawableNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/DrawableNode.cs @@ -3,14 +3,9 @@ namespace Beutl.Graphics.Rendering; -public class DrawableNode : ContainerNode +public class DrawableNode(Drawable drawable) : ContainerNode { - public DrawableNode(Drawable drawable) - { - Drawable = drawable; - } - - public Drawable Drawable { get; private set; } + public Drawable Drawable { get; private set; } = drawable; public override void Render(ImmediateCanvas canvas) { diff --git a/src/Beutl.Engine/Graphics/Rendering/EllipseNode.cs b/src/Beutl.Engine/Graphics/Rendering/EllipseNode.cs index ce5f69a9f..dab935db3 100644 --- a/src/Beutl.Engine/Graphics/Rendering/EllipseNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/EllipseNode.cs @@ -2,15 +2,10 @@ namespace Beutl.Graphics.Rendering; -public sealed class EllipseNode : BrushDrawNode +public sealed class EllipseNode(Rect rect, IBrush? fill, IPen? pen) + : BrushDrawNode(fill, pen, PenHelper.GetBounds(rect, pen)) { - public EllipseNode(Rect rect, IBrush? fill, IPen? pen) - : base(fill, pen, PenHelper.GetBounds(rect, pen)) - { - Rect = rect; - } - - public Rect Rect { get; } + public Rect Rect { get; } = rect; public bool Equals(Rect rect, IBrush? fill, IPen? pen) { diff --git a/src/Beutl.Engine/Graphics/Rendering/FilterEffectNode.cs b/src/Beutl.Engine/Graphics/Rendering/FilterEffectNode.cs index 59e3c9071..09ef118e5 100644 --- a/src/Beutl.Engine/Graphics/Rendering/FilterEffectNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/FilterEffectNode.cs @@ -6,16 +6,11 @@ namespace Beutl.Graphics.Rendering; -public sealed class FilterEffectNode : ContainerNode, ISupportRenderCache +public sealed class FilterEffectNode(FilterEffect filterEffect) : ContainerNode, ISupportRenderCache { private FilterEffectContext? _prevContext; - public FilterEffectNode(FilterEffect filterEffect) - { - FilterEffect = filterEffect; - } - - public FilterEffect FilterEffect { get; } + public FilterEffect FilterEffect { get; } = filterEffect; protected override void OnDispose(bool disposing) { diff --git a/src/Beutl.Engine/Graphics/Rendering/GeometryClipNode.cs b/src/Beutl.Engine/Graphics/Rendering/GeometryClipNode.cs index fb2860002..384ccfeaf 100644 --- a/src/Beutl.Engine/Graphics/Rendering/GeometryClipNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/GeometryClipNode.cs @@ -2,20 +2,13 @@ namespace Beutl.Graphics.Rendering; -public sealed class GeometryClipNode : ContainerNode +public sealed class GeometryClipNode(Geometry clip, ClipOperation operation) : ContainerNode { - private readonly int _version; + private readonly int _version = clip.Version; - public GeometryClipNode(Geometry clip, ClipOperation operation) - { - Clip = clip; - _version = clip.Version; - Operation = operation; - } - - public Geometry Clip { get; private set; } + public Geometry Clip { get; private set; } = clip; - public ClipOperation Operation { get; } + public ClipOperation Operation { get; } = operation; public bool Equals(Geometry clip, ClipOperation operation) { diff --git a/src/Beutl.Engine/Graphics/Rendering/GeometryNode.cs b/src/Beutl.Engine/Graphics/Rendering/GeometryNode.cs index a78c9f923..2075ff878 100644 --- a/src/Beutl.Engine/Graphics/Rendering/GeometryNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/GeometryNode.cs @@ -2,18 +2,12 @@ namespace Beutl.Graphics.Rendering; -public sealed class GeometryNode : BrushDrawNode +public sealed class GeometryNode(Geometry geometry, IBrush? fill, IPen? pen) + : BrushDrawNode(fill, pen, PenHelper.CalculateBoundsWithStrokeCap(geometry.GetRenderBounds(pen), pen)) { - private readonly int _version; + private readonly int _version = geometry.Version; - public GeometryNode(Geometry geometry, IBrush? fill, IPen? pen) - : base(fill, pen, PenHelper.CalculateBoundsWithStrokeCap(geometry.GetRenderBounds(pen), pen)) - { - Geometry = geometry; - _version = geometry.Version; - } - - public Geometry Geometry { get; private set; } + public Geometry Geometry { get; private set; } = geometry; public bool Equals(Geometry geometry, IBrush? fill, IPen? pen) { diff --git a/src/Beutl.Engine/Graphics/Rendering/ImageSourceNode.cs b/src/Beutl.Engine/Graphics/Rendering/ImageSourceNode.cs index 018b6f6c5..3005e8315 100644 --- a/src/Beutl.Engine/Graphics/Rendering/ImageSourceNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/ImageSourceNode.cs @@ -3,15 +3,10 @@ namespace Beutl.Graphics.Rendering; -public sealed class ImageSourceNode : BrushDrawNode +public sealed class ImageSourceNode(IImageSource source, IBrush? fill, IPen? pen) + : BrushDrawNode(fill, pen, PenHelper.GetBounds(new Rect(default, source.FrameSize.ToSize(1)), pen)) { - public ImageSourceNode(IImageSource source, IBrush? fill, IPen? pen) - : base(fill, pen, PenHelper.GetBounds(new Rect(default, source.FrameSize.ToSize(1)), pen)) - { - Source = source.Clone(); - } - - public IImageSource Source { get; } + public IImageSource Source { get; } = source.Clone(); public bool Equals(IImageSource source, IBrush? fill, IPen? pen) { diff --git a/src/Beutl.Engine/Graphics/Rendering/LayerNode.cs b/src/Beutl.Engine/Graphics/Rendering/LayerNode.cs index 9af713471..2c9cdd07a 100644 --- a/src/Beutl.Engine/Graphics/Rendering/LayerNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/LayerNode.cs @@ -6,14 +6,9 @@ namespace Beutl.Graphics.Rendering; -public class LayerNode : ContainerNode +public class LayerNode(Rect limit) : ContainerNode { - public LayerNode(Rect limit) - { - Limit = limit; - } - - public Rect Limit { get; } + public Rect Limit { get; } = limit; public override void Render(ImmediateCanvas canvas) { diff --git a/src/Beutl.Engine/Graphics/Rendering/OpacityMaskNode.cs b/src/Beutl.Engine/Graphics/Rendering/OpacityMaskNode.cs index 6eafef2c7..f6e9cf970 100644 --- a/src/Beutl.Engine/Graphics/Rendering/OpacityMaskNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/OpacityMaskNode.cs @@ -2,20 +2,13 @@ namespace Beutl.Graphics.Rendering; -public sealed class OpacityMaskNode : ContainerNode +public sealed class OpacityMaskNode(IBrush mask, Rect maskBounds, bool invert) : ContainerNode { - public OpacityMaskNode(IBrush mask, Rect maskBounds, bool invert) - { - Mask = (mask as IMutableBrush)?.ToImmutable() ?? mask; - MaskBounds = maskBounds; - Invert = invert; - } - - public IBrush Mask { get; private set; } + public IBrush Mask { get; private set; } = (mask as IMutableBrush)?.ToImmutable() ?? mask; - public Rect MaskBounds { get; } + public Rect MaskBounds { get; } = maskBounds; - public bool Invert { get; } + public bool Invert { get; } = invert; public bool Equals(IBrush? mask, Rect maskBounds, bool invert) { diff --git a/src/Beutl.Engine/Graphics/Rendering/RectClipNode.cs b/src/Beutl.Engine/Graphics/Rendering/RectClipNode.cs index ac9bca058..9a4c32183 100644 --- a/src/Beutl.Engine/Graphics/Rendering/RectClipNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/RectClipNode.cs @@ -1,16 +1,10 @@ namespace Beutl.Graphics.Rendering; -public sealed class RectClipNode : ContainerNode +public sealed class RectClipNode(Rect clip, ClipOperation operation) : ContainerNode { - public RectClipNode(Rect clip, ClipOperation operation) - { - Clip = clip; - Operation = operation; - } - - public Rect Clip { get; } + public Rect Clip { get; } = clip; - public ClipOperation Operation { get; } + public ClipOperation Operation { get; } = operation; public bool Equals(Rect clip, ClipOperation operation) { diff --git a/src/Beutl.Engine/Graphics/Rendering/RectangleNode.cs b/src/Beutl.Engine/Graphics/Rendering/RectangleNode.cs index 9b447199f..8b74ee863 100644 --- a/src/Beutl.Engine/Graphics/Rendering/RectangleNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/RectangleNode.cs @@ -2,15 +2,10 @@ namespace Beutl.Graphics.Rendering; -public sealed class RectangleNode : BrushDrawNode +public sealed class RectangleNode(Rect rect, IBrush? fill, IPen? pen) + : BrushDrawNode(fill, pen, PenHelper.GetBounds(rect, pen)) { - public RectangleNode(Rect rect, IBrush? fill, IPen? pen) - : base(fill, pen, PenHelper.GetBounds(rect, pen)) - { - Rect = rect; - } - - public Rect Rect { get; } + public Rect Rect { get; } = rect; public bool Equals(Rect rect, IBrush? fill, IPen? pen) { diff --git a/src/Beutl.Engine/Graphics/Rendering/RenderSceneBrush.cs b/src/Beutl.Engine/Graphics/Rendering/RenderSceneBrush.cs index 31cdc105a..f14fdb05f 100644 --- a/src/Beutl.Engine/Graphics/Rendering/RenderSceneBrush.cs +++ b/src/Beutl.Engine/Graphics/Rendering/RenderSceneBrush.cs @@ -4,20 +4,14 @@ namespace Beutl.Graphics.Rendering; -internal sealed class RenderSceneBrush : IDrawableBrush, IEquatable, IDisposable +internal sealed class RenderSceneBrush(IDrawableBrush @base, RenderScene? scene, Rect bounds) + : IDrawableBrush, IEquatable, IDisposable { - public RenderSceneBrush(IDrawableBrush @base, RenderScene? scene, Rect bounds) - { - Base = @base; - Scene = scene; - Bounds = bounds; - } - - public RenderScene? Scene { get; private set; } + public RenderScene? Scene { get; private set; } = scene; - public Rect Bounds { get; } + public Rect Bounds { get; } = bounds; - public IDrawableBrush Base { get; } + public IDrawableBrush Base { get; } = @base; public AlignmentX AlignmentX => Base.AlignmentX; diff --git a/src/Beutl.Engine/Graphics/Rendering/TextNode.cs b/src/Beutl.Engine/Graphics/Rendering/TextNode.cs index 4afa684a5..7508fdda3 100644 --- a/src/Beutl.Engine/Graphics/Rendering/TextNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/TextNode.cs @@ -4,15 +4,10 @@ namespace Beutl.Graphics.Rendering; // Todo: bounds,HitTest -public sealed class TextNode : BrushDrawNode +public sealed class TextNode(FormattedText text, IBrush? fill, IPen? pen) + : BrushDrawNode(fill, pen, new(new Point(0, text.Metrics.Ascent), text.Bounds)) { - public TextNode(FormattedText text, IBrush? fill, IPen? pen) - : base(fill, pen, new(new Point(0, text.Metrics.Ascent), text.Bounds)) - { - Text = text; - } - - public FormattedText Text { get; private set; } + public FormattedText Text { get; private set; } = text; public bool Equals(FormattedText text, IBrush? fill, IPen? pen) { diff --git a/src/Beutl.Engine/Graphics/Rendering/TransformNode.cs b/src/Beutl.Engine/Graphics/Rendering/TransformNode.cs index 64a537b4e..8fdf15270 100644 --- a/src/Beutl.Engine/Graphics/Rendering/TransformNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/TransformNode.cs @@ -1,16 +1,10 @@ namespace Beutl.Graphics.Rendering; -public sealed class TransformNode : ContainerNode +public sealed class TransformNode(Matrix transform, TransformOperator transformOperator) : ContainerNode { - public TransformNode(Matrix transform, TransformOperator transformOperator) - { - Transform = transform; - TransformOperator = transformOperator; - } - - public Matrix Transform { get; } + public Matrix Transform { get; } = transform; - public TransformOperator TransformOperator { get; } + public TransformOperator TransformOperator { get; } = transformOperator; protected override Rect TransformBounds(Rect bounds) { diff --git a/src/Beutl.Engine/Graphics/Rendering/VideoSourceNode.cs b/src/Beutl.Engine/Graphics/Rendering/VideoSourceNode.cs index f92b63c76..28d4efb0b 100644 --- a/src/Beutl.Engine/Graphics/Rendering/VideoSourceNode.cs +++ b/src/Beutl.Engine/Graphics/Rendering/VideoSourceNode.cs @@ -3,18 +3,13 @@ namespace Beutl.Graphics.Rendering; -public sealed class VideoSourceNode : BrushDrawNode +public sealed class VideoSourceNode( + IVideoSource source, int frame, IBrush? fill, IPen? pen) + : BrushDrawNode(fill, pen, PenHelper.GetBounds(new Rect(default, source.FrameSize.ToSize(1)), pen)) { - public VideoSourceNode(IVideoSource source, int frame, IBrush? fill, IPen? pen) - : base(fill, pen, PenHelper.GetBounds(new Rect(default, source.FrameSize.ToSize(1)), pen)) - { - Source = source.Clone(); - Frame = frame; - } - - public IVideoSource Source { get; } + public IVideoSource Source { get; } = source.Clone(); - public int Frame { get; } + public int Frame { get; } = frame; public bool Equals(IVideoSource source, int frame, IBrush? fill, IPen? pen) { diff --git a/src/Beutl.Engine/Graphics/Shapes/TextBlock.cs b/src/Beutl.Engine/Graphics/Shapes/TextBlock.cs index ee3c7e9f5..35b6bfd14 100644 --- a/src/Beutl.Engine/Graphics/Shapes/TextBlock.cs +++ b/src/Beutl.Engine/Graphics/Shapes/TextBlock.cs @@ -300,7 +300,7 @@ private void OnUpdateText() { if (string.IsNullOrEmpty(_text)) { - Elements = new TextElements(Array.Empty()); + Elements = new TextElements([]); } else { diff --git a/src/Beutl.Engine/Graphics/Shapes/TextElementsBuilder.cs b/src/Beutl.Engine/Graphics/Shapes/TextElementsBuilder.cs index 6172551aa..ad9542168 100644 --- a/src/Beutl.Engine/Graphics/Shapes/TextElementsBuilder.cs +++ b/src/Beutl.Engine/Graphics/Shapes/TextElementsBuilder.cs @@ -8,39 +8,26 @@ namespace Beutl.Graphics.Shapes; -public class TextElementsBuilder +public class TextElementsBuilder(FormattedTextInfo initialOptions) { - private readonly List _elements = new(); - private readonly Stack _fontFamily = new(); - private readonly Stack _fontWeight = new(); - private readonly Stack _fontStyle = new(); - private readonly Stack _size = new(); - private readonly Stack _brush = new(); - private readonly Stack _pen = new(); - private readonly Stack _spacing = new(); - private readonly Stack _margin = new(); - private readonly FormattedTextInfo _initialOptions; - private FontFamily _curFontFamily; - private FontWeight _curFontWeight; - private FontStyle _curFontStyle; - private float _curSize; - private IBrush? _curBrush; - private IPen? _curPen; - private float _curSpacing; + private readonly List _elements = []; + private readonly Stack _fontFamily = []; + private readonly Stack _fontWeight = []; + private readonly Stack _fontStyle = []; + private readonly Stack _size = []; + private readonly Stack _brush = []; + private readonly Stack _pen = []; + private readonly Stack _spacing = []; + private readonly Stack _margin = []; + private FontFamily _curFontFamily = initialOptions.Typeface.FontFamily; + private FontWeight _curFontWeight = initialOptions.Typeface.Weight; + private FontStyle _curFontStyle = initialOptions.Typeface.Style; + private float _curSize = initialOptions.Size; + private IBrush? _curBrush = initialOptions.Brush; + private IPen? _curPen = initialOptions.Pen; + private float _curSpacing = initialOptions.Space; private bool _singleLine; - public TextElementsBuilder(FormattedTextInfo initialOptions) - { - _initialOptions = initialOptions; - _curFontFamily = initialOptions.Typeface.FontFamily; - _curFontWeight = initialOptions.Typeface.Weight; - _curFontStyle = initialOptions.Typeface.Style; - _curSize = initialOptions.Size; - _curBrush = initialOptions.Brush; - _curPen = initialOptions.Pen; - _curSpacing = initialOptions.Space; - } - public ReadOnlySpan Items => CollectionsMarshal.AsSpan(_elements); public void PushFontFamily(FontFamily? font) @@ -98,25 +85,25 @@ public void Pop(Options options) switch (options) { case Options.FontFamily: - _curFontFamily = _fontFamily.PopOrDefault(_initialOptions.Typeface.FontFamily); + _curFontFamily = _fontFamily.PopOrDefault(initialOptions.Typeface.FontFamily); break; case Options.FontWeight: - _curFontWeight = _fontWeight.PopOrDefault(_initialOptions.Typeface.Weight); + _curFontWeight = _fontWeight.PopOrDefault(initialOptions.Typeface.Weight); break; case Options.FontStyle: - _curFontStyle = _fontStyle.PopOrDefault(_initialOptions.Typeface.Style); + _curFontStyle = _fontStyle.PopOrDefault(initialOptions.Typeface.Style); break; case Options.Size: - _curSize = _size.PopOrDefault(_initialOptions.Size); + _curSize = _size.PopOrDefault(initialOptions.Size); break; case Options.Brush: - _curBrush = _brush.PopOrDefault(_initialOptions.Brush); + _curBrush = _brush.PopOrDefault(initialOptions.Brush); break; case Options.Pen: - _curPen = _pen.PopOrDefault(_initialOptions.Pen); + _curPen = _pen.PopOrDefault(initialOptions.Pen); break; case Options.Spacing: - _curSpacing = _spacing.PopOrDefault(_initialOptions.Space); + _curSpacing = _spacing.PopOrDefault(initialOptions.Space); break; case Options.SingleLine: _singleLine = false; diff --git a/src/Beutl.Engine/Graphics/Size.cs b/src/Beutl.Engine/Graphics/Size.cs index f5ddb3696..709fb2634 100644 --- a/src/Beutl.Engine/Graphics/Size.cs +++ b/src/Beutl.Engine/Graphics/Size.cs @@ -14,9 +14,14 @@ namespace Beutl.Graphics; /// /// Defines a size. /// +/// +/// Initializes a new instance of the structure. +/// +/// The width. +/// The height. [JsonConverter(typeof(SizeJsonConverter))] [TypeConverter(typeof(SizeConverter))] -public readonly struct Size +public readonly struct Size(float width, float height) : IEquatable, IParsable, ISpanParsable, @@ -45,17 +50,6 @@ public readonly struct Size /// public static readonly Size Empty = new(0, 0); - /// - /// Initializes a new instance of the structure. - /// - /// The width. - /// The height. - public Size(float width, float height) - { - Width = width; - Height = height; - } - /// /// Gets the aspect ratio of the size. /// @@ -64,12 +58,12 @@ public Size(float width, float height) /// /// Gets the width. /// - public float Width { get; } + public float Width { get; } = width; /// /// Gets the height. /// - public float Height { get; } + public float Height { get; } = height; /// /// Gets a value indicating whether the Width and Height values are zero. diff --git a/src/Beutl.Engine/Graphics/Transformation/TransformGroup.cs b/src/Beutl.Engine/Graphics/Transformation/TransformGroup.cs index ac046b33e..fbf901b6e 100644 --- a/src/Beutl.Engine/Graphics/Transformation/TransformGroup.cs +++ b/src/Beutl.Engine/Graphics/Transformation/TransformGroup.cs @@ -19,7 +19,7 @@ static TransformGroup() public TransformGroup() { - _children = new Transforms(); + _children = []; _children.Invalidated += (_, e) => RaiseInvalidated(e); } diff --git a/src/Beutl.Engine/Graphics/Transformation/TransformParser.cs b/src/Beutl.Engine/Graphics/Transformation/TransformParser.cs index 90f38e440..bbcb98d6d 100644 --- a/src/Beutl.Engine/Graphics/Transformation/TransformParser.cs +++ b/src/Beutl.Engine/Graphics/Transformation/TransformParser.cs @@ -9,7 +9,7 @@ namespace Beutl.Graphics.Transformation; internal static class TransformParser { private static readonly (string, TransformFunction)[] s_functionMapping = - { + [ ("translate", TransformFunction.Translate), ("translateX", TransformFunction.TranslateX), ("translateY", TransformFunction.TranslateY), @@ -21,17 +21,17 @@ private static readonly (string, TransformFunction)[] s_functionMapping = ("skewY", TransformFunction.SkewY), ("rotate", TransformFunction.Rotate), ("matrix", TransformFunction.Matrix) - }; + ]; private static readonly (string, Unit)[] s_unitMapping = - { + [ ("deg", Unit.Degree), ("grad", Unit.Gradian), ("rad", Unit.Radian), ("turn", Unit.Turn), ("px", Unit.Pixel), ("%", Unit.Relative) - }; + ]; public static ITransform Parse(ReadOnlySpan s) { @@ -487,16 +487,10 @@ private enum Unit Relative } - private readonly struct UnitValue + private readonly struct UnitValue(Unit unit, float value) { - public readonly Unit Unit; - public readonly float Value; - - public UnitValue(Unit unit, float value) - { - Unit = unit; - Value = value; - } + public readonly Unit Unit = unit; + public readonly float Value = value; public static UnitValue Zero => new(Unit.None, 0); @@ -519,14 +513,9 @@ private enum TransformFunction Matrix } - public readonly struct Builder + public readonly struct Builder(int capacity) { - private readonly List _data; - - public Builder(int capacity) - { - _data = new List(capacity); - } + private readonly List _data = new(capacity); public void AppendTranslate(float x, float y) { diff --git a/src/Beutl.Engine/Graphics/Vector.cs b/src/Beutl.Engine/Graphics/Vector.cs index 6bc9000ad..7fa9dca67 100644 --- a/src/Beutl.Engine/Graphics/Vector.cs +++ b/src/Beutl.Engine/Graphics/Vector.cs @@ -14,9 +14,14 @@ namespace Beutl.Graphics; /// /// Defines a vector. /// +/// +/// Initializes a new instance of the structure. +/// +/// The X component. +/// The Y component. [JsonConverter(typeof(VectorJsonConverter))] [TypeConverter(typeof(VectorConverter))] -public readonly struct Vector +public readonly struct Vector(float x, float y) : IEquatable, IParsable, ISpanParsable, @@ -25,26 +30,16 @@ public readonly struct Vector IUtf8SpanParsable, ITupleConvertible { - /// - /// Initializes a new instance of the structure. - /// - /// The X component. - /// The Y component. - public Vector(float x, float y) - { - X = x; - Y = y; - } /// /// Gets the X component. /// - public float X { get; } + public float X { get; } = x; /// /// Gets the Y component. /// - public float Y { get; } + public float Y { get; } = y; /// /// Returns the vector (0.0, 0.0). diff --git a/src/Beutl.Engine/Media/Bitmap.cs b/src/Beutl.Engine/Media/Bitmap.cs index b14886564..b82a6a35b 100644 --- a/src/Beutl.Engine/Media/Bitmap.cs +++ b/src/Beutl.Engine/Media/Bitmap.cs @@ -9,23 +9,15 @@ namespace Beutl.Media; -public readonly struct BitmapInfo +public readonly struct BitmapInfo(int width, int height, int byteCount, int pixelSize) { - public BitmapInfo(int width, int height, int byteCount, int pixelSize) - { - Width = width; - Height = height; - ByteCount = byteCount; - PixelSize = pixelSize; - } + public int Width { get; } = width; - public int Width { get; } - - public int Height { get; } + public int Height { get; } = height; - public int ByteCount { get; } + public int ByteCount { get; } = byteCount; - public int PixelSize { get; } + public int PixelSize { get; } = pixelSize; } public unsafe class Bitmap : IBitmap diff --git a/src/Beutl.Engine/Media/Brushes/GradientBrush.cs b/src/Beutl.Engine/Media/Brushes/GradientBrush.cs index 2bd56d25a..e65a12ce2 100644 --- a/src/Beutl.Engine/Media/Brushes/GradientBrush.cs +++ b/src/Beutl.Engine/Media/Brushes/GradientBrush.cs @@ -33,7 +33,7 @@ static GradientBrush() /// public GradientBrush() { - _gradientStops = new GradientStops(); + _gradientStops = []; _gradientStops.Invalidated += (_, e) => RaiseInvalidated(e); } diff --git a/src/Beutl.Engine/Media/Color.cs b/src/Beutl.Engine/Media/Color.cs index 0b439af2c..014da460f 100644 --- a/src/Beutl.Engine/Media/Color.cs +++ b/src/Beutl.Engine/Media/Color.cs @@ -13,38 +13,31 @@ namespace Beutl.Media; /// [JsonConverter(typeof(ColorJsonConverter))] [TypeConverter(typeof(ColorConverter))] -public readonly struct Color +public readonly struct Color(byte a, byte r, byte g, byte b) : IEquatable, IParsable, ISpanParsable { - public Color(byte a, byte r, byte g, byte b) - { - A = a; - R = r; - G = g; - B = b; - } /// /// Gets the Alpha component of the color. /// - public byte A { get; } + public byte A { get; } = a; /// /// Gets the Red component of the color. /// - public byte R { get; } + public byte R { get; } = r; /// /// Gets the Green component of the color. /// - public byte G { get; } + public byte G { get; } = g; /// /// Gets the Blue component of the color. /// - public byte B { get; } + public byte B { get; } = b; /// /// Creates a from alpha, red, green and blue components. diff --git a/src/Beutl.Engine/Media/Decoding/DecoderRegistry.cs b/src/Beutl.Engine/Media/Decoding/DecoderRegistry.cs index 0893f7cab..6e329df31 100644 --- a/src/Beutl.Engine/Media/Decoding/DecoderRegistry.cs +++ b/src/Beutl.Engine/Media/Decoding/DecoderRegistry.cs @@ -4,8 +4,8 @@ namespace Beutl.Media.Decoding; public static class DecoderRegistry { - private static readonly List s_registered = new(); - private static readonly List s_ordered = new(); + private static readonly List s_registered = []; + private static readonly List s_ordered = []; private static readonly object s_lock = new(); static DecoderRegistry() diff --git a/src/Beutl.Engine/Media/Encoding/EncoderRegistry.cs b/src/Beutl.Engine/Media/Encoding/EncoderRegistry.cs index de26da36d..72d9db2e3 100644 --- a/src/Beutl.Engine/Media/Encoding/EncoderRegistry.cs +++ b/src/Beutl.Engine/Media/Encoding/EncoderRegistry.cs @@ -2,7 +2,7 @@ public static class EncoderRegistry { - private static readonly List s_registerd = new(); + private static readonly List s_registerd = []; public static IEnumerable EnumerateEncoders() { diff --git a/src/Beutl.Engine/Media/Font/FontFamily.cs b/src/Beutl.Engine/Media/Font/FontFamily.cs index ed93a87e5..e183dcf23 100644 --- a/src/Beutl.Engine/Media/Font/FontFamily.cs +++ b/src/Beutl.Engine/Media/Font/FontFamily.cs @@ -10,16 +10,11 @@ namespace Beutl.Media; [JsonConverter(typeof(FontFamilyJsonConverter))] [TypeConverter(typeof(FontFamilyConverter))] -public class FontFamily : IEquatable +public class FontFamily(string familyname) : IEquatable { public static readonly FontFamily Default = new(GetDefaultFontFamily()); - public FontFamily(string familyname) - { - Name = familyname; - } - - public string Name { get; } + public string Name { get; } = familyname; public IEnumerable Typefaces => FontManager.Instance.GetTypefaces(this); diff --git a/src/Beutl.Engine/Media/Font/FontManager.cs b/src/Beutl.Engine/Media/Font/FontManager.cs index 903967c3b..b4f807dd2 100644 --- a/src/Beutl.Engine/Media/Font/FontManager.cs +++ b/src/Beutl.Engine/Media/Font/FontManager.cs @@ -12,7 +12,7 @@ namespace Beutl.Media; public sealed class FontManager { public static readonly FontManager Instance = new(); - internal readonly Dictionary> _fonts = new(); + internal readonly Dictionary> _fonts = []; private readonly string[] _fontDirs; private FontManager() @@ -45,7 +45,7 @@ Typeface GetDefaultTypeface() } } - _fontDirs = GlobalConfiguration.Instance.FontConfig.FontDirectories.ToArray(); + _fontDirs = [.. GlobalConfiguration.Instance.FontConfig.FontDirectories]; var list = new List(); foreach (string file in _fontDirs @@ -71,7 +71,7 @@ Typeface GetDefaultTypeface() foreach (IGrouping item in list.GroupBy(i => i.FamilyName)) { var family = new FontFamily(item.Key); - _fonts.Add(family, TypefaceCollection.Create(item.ToArray())); + _fonts.Add(family, TypefaceCollection.Create([.. item])); } DefaultTypeface = GetDefaultTypeface(); diff --git a/src/Beutl.Engine/Media/Font/Typeface.cs b/src/Beutl.Engine/Media/Font/Typeface.cs index b45fe4410..7a35fd62e 100644 --- a/src/Beutl.Engine/Media/Font/Typeface.cs +++ b/src/Beutl.Engine/Media/Font/Typeface.cs @@ -5,31 +5,26 @@ namespace Beutl.Media; [JsonConverter(typeof(TypefaceJsonConverter))] -public readonly struct Typeface : IEquatable +public readonly struct Typeface( + FontFamily fontFamily, + FontStyle style = FontStyle.Normal, + FontWeight weight = FontWeight.Regular) : IEquatable { - public Typeface(FontFamily fontFamily, - FontStyle style = FontStyle.Normal, - FontWeight weight = FontWeight.Regular) - { - FontFamily = fontFamily; - Style = style; - Weight = weight; - } /// /// Gets the font family. /// - public FontFamily FontFamily { get; } + public FontFamily FontFamily { get; } = fontFamily; /// /// Gets the font style. /// - public FontStyle Style { get; } + public FontStyle Style { get; } = style; /// /// Gets the font weight. /// - public FontWeight Weight { get; } + public FontWeight Weight { get; } = weight; public override bool Equals(object? obj) { diff --git a/src/Beutl.Engine/Media/Geometry/PathGeometry.cs b/src/Beutl.Engine/Media/Geometry/PathGeometry.cs index a3730205b..64a446e9f 100644 --- a/src/Beutl.Engine/Media/Geometry/PathGeometry.cs +++ b/src/Beutl.Engine/Media/Geometry/PathGeometry.cs @@ -7,7 +7,7 @@ namespace Beutl.Media; public sealed class PathGeometry : Geometry { public static readonly CoreProperty OperationsProperty; - private readonly PathOperations _operations = new(); + private readonly PathOperations _operations = []; static PathGeometry() { diff --git a/src/Beutl.Engine/Media/Immutable/ImmutableGradientStop.cs b/src/Beutl.Engine/Media/Immutable/ImmutableGradientStop.cs index 563433894..8f6fb8616 100644 --- a/src/Beutl.Engine/Media/Immutable/ImmutableGradientStop.cs +++ b/src/Beutl.Engine/Media/Immutable/ImmutableGradientStop.cs @@ -1,16 +1,10 @@ namespace Beutl.Media.Immutable; -public class ImmutableGradientStop : IGradientStop, IEquatable +public class ImmutableGradientStop(float offset, Color color) : IGradientStop, IEquatable { - public ImmutableGradientStop(float offset, Color color) - { - Offset = offset; - Color = color; - } - - public float Offset { get; } + public float Offset { get; } = offset; - public Color Color { get; } + public Color Color { get; } = color; public override bool Equals(object? obj) { diff --git a/src/Beutl.Engine/Media/Immutable/ImmutablePen.cs b/src/Beutl.Engine/Media/Immutable/ImmutablePen.cs index 6b23db8b9..2dcf63895 100644 --- a/src/Beutl.Engine/Media/Immutable/ImmutablePen.cs +++ b/src/Beutl.Engine/Media/Immutable/ImmutablePen.cs @@ -1,42 +1,31 @@ namespace Beutl.Media.Immutable; -public sealed class ImmutablePen : IPen +public sealed class ImmutablePen( + IBrush? brush, + IReadOnlyList? dashArray, + float dashOffset, + float thickness, + float miterLimit = 10, + StrokeCap strokeCap = StrokeCap.Flat, + StrokeJoin strokeJoin = StrokeJoin.Miter, + StrokeAlignment strokeAlignment = StrokeAlignment.Center) + : IPen { - public ImmutablePen( - IBrush? brush, - IReadOnlyList? dashArray, - float dashOffset, - float thickness, - float miterLimit = 10, - StrokeCap strokeCap = StrokeCap.Flat, - StrokeJoin strokeJoin = StrokeJoin.Miter, - StrokeAlignment strokeAlignment = StrokeAlignment.Center) - { - Brush = brush; - DashArray = dashArray; - DashOffset = dashOffset; - Thickness = thickness; - MiterLimit = miterLimit; - StrokeCap = strokeCap; - StrokeJoin = strokeJoin; - StrokeAlignment = strokeAlignment; - } - - public IBrush? Brush { get; } + public IBrush? Brush { get; } = brush; - public IReadOnlyList? DashArray { get; } + public IReadOnlyList? DashArray { get; } = dashArray; - public float DashOffset { get; } + public float DashOffset { get; } = dashOffset; - public float Thickness { get; } + public float Thickness { get; } = thickness; - public float MiterLimit { get; } + public float MiterLimit { get; } = miterLimit; - public StrokeCap StrokeCap { get; } + public StrokeCap StrokeCap { get; } = strokeCap; - public StrokeJoin StrokeJoin { get; } + public StrokeJoin StrokeJoin { get; } = strokeJoin; - public StrokeAlignment StrokeAlignment { get; } + public StrokeAlignment StrokeAlignment { get; } = strokeAlignment; public override bool Equals(object? obj) { diff --git a/src/Beutl.Engine/Media/Immutable/ImmutablePerlinNoiseBrush.cs b/src/Beutl.Engine/Media/Immutable/ImmutablePerlinNoiseBrush.cs index a74414433..d2e6eb3ef 100644 --- a/src/Beutl.Engine/Media/Immutable/ImmutablePerlinNoiseBrush.cs +++ b/src/Beutl.Engine/Media/Immutable/ImmutablePerlinNoiseBrush.cs @@ -3,28 +3,17 @@ namespace Beutl.Media.Immutable; -public sealed class ImmutablePerlinNoiseBrush : IPerlinNoiseBrush, IEquatable +public sealed class ImmutablePerlinNoiseBrush( + float baseFrequencyX, + float baseFrequencyY, + int octaves, + float seed, + PerlinNoiseType perlinNoiseType, + float opacity, + ITransform? transform, + RelativePoint transformOrigin) + : IPerlinNoiseBrush, IEquatable { - public ImmutablePerlinNoiseBrush( - float baseFrequencyX, - float baseFrequencyY, - int octaves, - float seed, - PerlinNoiseType perlinNoiseType, - float opacity, - ITransform? transform, - RelativePoint transformOrigin) - { - BaseFrequencyX = baseFrequencyX; - BaseFrequencyY = baseFrequencyY; - Octaves = octaves; - Seed = seed; - PerlinNoiseType = perlinNoiseType; - Opacity = opacity; - Transform = transform; - TransformOrigin = transformOrigin; - } - public ImmutablePerlinNoiseBrush(IPerlinNoiseBrush source) : this(source.BaseFrequencyX, source.BaseFrequencyY, @@ -37,21 +26,21 @@ public ImmutablePerlinNoiseBrush(IPerlinNoiseBrush source) { } - public float BaseFrequencyX { get; } + public float BaseFrequencyX { get; } = baseFrequencyX; - public float BaseFrequencyY { get; } + public float BaseFrequencyY { get; } = baseFrequencyY; - public int Octaves { get; } + public int Octaves { get; } = octaves; - public float Seed { get; } + public float Seed { get; } = seed; - public PerlinNoiseType PerlinNoiseType { get; } + public PerlinNoiseType PerlinNoiseType { get; } = perlinNoiseType; - public float Opacity { get; } + public float Opacity { get; } = opacity; - public ITransform? Transform { get; } + public ITransform? Transform { get; } = transform; - public RelativePoint TransformOrigin { get; } + public RelativePoint TransformOrigin { get; } = transformOrigin; public override bool Equals(object? obj) { diff --git a/src/Beutl.Engine/Media/Immutable/ImmutableSolidColorBrush.cs b/src/Beutl.Engine/Media/Immutable/ImmutableSolidColorBrush.cs index 0aaf96465..de9b9a925 100644 --- a/src/Beutl.Engine/Media/Immutable/ImmutableSolidColorBrush.cs +++ b/src/Beutl.Engine/Media/Immutable/ImmutableSolidColorBrush.cs @@ -3,16 +3,10 @@ namespace Beutl.Media.Immutable; -public class ImmutableSolidColorBrush : ISolidColorBrush, IEquatable +public class ImmutableSolidColorBrush( + Color color, float opacity = 100, ImmutableTransform? transform = null, RelativePoint origin = default) + : ISolidColorBrush, IEquatable { - public ImmutableSolidColorBrush(Color color, float opacity = 100, ImmutableTransform? transform = null, RelativePoint origin = default) - { - Color = color; - Opacity = opacity; - Transform = transform; - TransformOrigin = origin; - } - public ImmutableSolidColorBrush(uint color) : this(Color.FromUInt32(color)) { @@ -23,13 +17,13 @@ public ImmutableSolidColorBrush(ISolidColorBrush source) { } - public Color Color { get; } + public Color Color { get; } = color; - public float Opacity { get; } + public float Opacity { get; } = opacity; - public ITransform? Transform { get; } + public ITransform? Transform { get; } = transform; - public RelativePoint TransformOrigin { get; } + public RelativePoint TransformOrigin { get; } = origin; public override string ToString() { diff --git a/src/Beutl.Engine/Media/Immutable/ImmutableTransform.cs b/src/Beutl.Engine/Media/Immutable/ImmutableTransform.cs index 8895b3bb3..75c1dd589 100644 --- a/src/Beutl.Engine/Media/Immutable/ImmutableTransform.cs +++ b/src/Beutl.Engine/Media/Immutable/ImmutableTransform.cs @@ -3,17 +3,11 @@ namespace Beutl.Media.Immutable; -public sealed class ImmutableTransform : ITransform, IEquatable +public sealed class ImmutableTransform(Matrix matrix, bool isEnabled = true) : ITransform, IEquatable { - public Matrix Value { get; } + public Matrix Value { get; } = matrix; - public bool IsEnabled { get; } - - public ImmutableTransform(Matrix matrix, bool isEnabled = true) - { - Value = matrix; - IsEnabled = isEnabled; - } + public bool IsEnabled { get; } = isEnabled; public override bool Equals(object? obj) { diff --git a/src/Beutl.Engine/Media/KnownColors.cs b/src/Beutl.Engine/Media/KnownColors.cs index d62e46fd2..a1dd173d3 100644 --- a/src/Beutl.Engine/Media/KnownColors.cs +++ b/src/Beutl.Engine/Media/KnownColors.cs @@ -35,7 +35,7 @@ static KnownColors() s_knownColorNames = knownColorNames.ToFrozenDictionary(); s_knownColors = knownColors.ToFrozenDictionary(); - s_knownBrushes = new Dictionary(); + s_knownBrushes = []; } public static ISolidColorBrush? GetKnownBrush(string s) diff --git a/src/Beutl.Engine/Media/Music/Sample.cs b/src/Beutl.Engine/Media/Music/Sample.cs index a9f257ea4..8bc556995 100644 --- a/src/Beutl.Engine/Media/Music/Sample.cs +++ b/src/Beutl.Engine/Media/Music/Sample.cs @@ -1,18 +1,12 @@ namespace Beutl.Media.Music; -public readonly struct Sample : IEquatable +public readonly struct Sample(float left, float right) : IEquatable { public static readonly Sample One = new(1, 1); - public Sample(float left, float right) - { - Left = left; - Right = right; - } + public float Left { get; } = left; - public float Left { get; } - - public float Right { get; } + public float Right { get; } = right; public override bool Equals(object? obj) => obj is Sample sample && Equals(sample); diff --git a/src/Beutl.Engine/Media/Music/Samples/Monaural16BitInteger.cs b/src/Beutl.Engine/Media/Music/Samples/Monaural16BitInteger.cs index 5f5f5a6ec..7d2a707a2 100644 --- a/src/Beutl.Engine/Media/Music/Samples/Monaural16BitInteger.cs +++ b/src/Beutl.Engine/Media/Music/Samples/Monaural16BitInteger.cs @@ -4,14 +4,9 @@ namespace Beutl.Media.Music.Samples; [StructLayout(LayoutKind.Sequential)] -public struct Monaural16BitInteger : ISample +public struct Monaural16BitInteger(short value) : ISample { - public short Value; - - public Monaural16BitInteger(short value) - { - Value = value; - } + public short Value = value; public static Monaural16BitInteger ConvertFrom(Sample src) { diff --git a/src/Beutl.Engine/Media/Music/Samples/Monaural32BitFloat.cs b/src/Beutl.Engine/Media/Music/Samples/Monaural32BitFloat.cs index 6e41492c7..c5d7001a1 100644 --- a/src/Beutl.Engine/Media/Music/Samples/Monaural32BitFloat.cs +++ b/src/Beutl.Engine/Media/Music/Samples/Monaural32BitFloat.cs @@ -3,14 +3,9 @@ namespace Beutl.Media.Music.Samples; [StructLayout(LayoutKind.Sequential)] -public struct Monaural32BitFloat : ISample +public struct Monaural32BitFloat(float value) : ISample { - public float Value; - - public Monaural32BitFloat(float value) - { - Value = value; - } + public float Value = value; public static Monaural32BitFloat Amplifier(Monaural32BitFloat s, Sample level) { diff --git a/src/Beutl.Engine/Media/Music/Samples/Monaural32BitInteger.cs b/src/Beutl.Engine/Media/Music/Samples/Monaural32BitInteger.cs index f651f711f..e0360d374 100644 --- a/src/Beutl.Engine/Media/Music/Samples/Monaural32BitInteger.cs +++ b/src/Beutl.Engine/Media/Music/Samples/Monaural32BitInteger.cs @@ -3,14 +3,9 @@ namespace Beutl.Media.Music.Samples; [StructLayout(LayoutKind.Sequential)] -public struct Monaural32BitInteger : ISample +public struct Monaural32BitInteger(int value) : ISample { - public int Value; - - public Monaural32BitInteger(int value) - { - Value = value; - } + public int Value = value; public static Monaural32BitInteger ConvertFrom(Sample src) { diff --git a/src/Beutl.Engine/Media/Music/Samples/Stereo16BitInteger.cs b/src/Beutl.Engine/Media/Music/Samples/Stereo16BitInteger.cs index 73fab8b1c..c28af14f7 100644 --- a/src/Beutl.Engine/Media/Music/Samples/Stereo16BitInteger.cs +++ b/src/Beutl.Engine/Media/Music/Samples/Stereo16BitInteger.cs @@ -3,17 +3,11 @@ namespace Beutl.Media.Music.Samples; [StructLayout(LayoutKind.Sequential)] -public struct Stereo16BitInteger : ISample +public struct Stereo16BitInteger(short left, short right) : ISample { - public short Left; + public short Left = left; - public short Right; - - public Stereo16BitInteger(short left, short right) - { - Left = left; - Right = right; - } + public short Right = right; public static Stereo16BitInteger ConvertFrom(Sample src) { diff --git a/src/Beutl.Engine/Media/Music/Samples/Stereo32BitFloat.cs b/src/Beutl.Engine/Media/Music/Samples/Stereo32BitFloat.cs index a198fb16d..0c11ed32e 100644 --- a/src/Beutl.Engine/Media/Music/Samples/Stereo32BitFloat.cs +++ b/src/Beutl.Engine/Media/Music/Samples/Stereo32BitFloat.cs @@ -4,17 +4,11 @@ namespace Beutl.Media.Music.Samples; [StructLayout(LayoutKind.Sequential)] -public struct Stereo32BitFloat : ISample +public struct Stereo32BitFloat(float left, float right) : ISample { - public float Left; + public float Left = left; - public float Right; - - public Stereo32BitFloat(float left, float right) - { - Left = left; - Right = right; - } + public float Right = right; public static Stereo32BitFloat ConvertFrom(Sample src) { diff --git a/src/Beutl.Engine/Media/Music/Samples/Stereo32BitInteger.cs b/src/Beutl.Engine/Media/Music/Samples/Stereo32BitInteger.cs index 7064a778d..7de281a2a 100644 --- a/src/Beutl.Engine/Media/Music/Samples/Stereo32BitInteger.cs +++ b/src/Beutl.Engine/Media/Music/Samples/Stereo32BitInteger.cs @@ -3,17 +3,11 @@ namespace Beutl.Media.Music.Samples; [StructLayout(LayoutKind.Sequential)] -public struct Stereo32BitInteger : ISample +public struct Stereo32BitInteger(int left, int right) : ISample { - public int Left; + public int Left = left; - public int Right; - - public Stereo32BitInteger(int left, int right) - { - Left = left; - Right = right; - } + public int Right = right; public static Stereo32BitInteger ConvertFrom(Sample src) { diff --git a/src/Beutl.Engine/Media/Pixel/Bgr565.cs b/src/Beutl.Engine/Media/Pixel/Bgr565.cs index d3dd51d31..063692f7c 100644 --- a/src/Beutl.Engine/Media/Pixel/Bgr565.cs +++ b/src/Beutl.Engine/Media/Pixel/Bgr565.cs @@ -3,14 +3,9 @@ namespace Beutl.Media.Pixel; [StructLayout(LayoutKind.Sequential)] -public struct Bgr565 : IPixel +public struct Bgr565(ushort value) : IPixel { - public ushort Value; - - public Bgr565(ushort value) - { - Value = value; - } + public ushort Value = value; public Bgr565 FromColor(Color color) { diff --git a/src/Beutl.Engine/Media/Pixel/Bgr888.cs b/src/Beutl.Engine/Media/Pixel/Bgr888.cs index 290adbee7..e2107a942 100644 --- a/src/Beutl.Engine/Media/Pixel/Bgr888.cs +++ b/src/Beutl.Engine/Media/Pixel/Bgr888.cs @@ -3,20 +3,13 @@ namespace Beutl.Media.Pixel; [StructLayout(LayoutKind.Sequential)] -public struct Bgr888 : IPixel +public struct Bgr888(byte r, byte g, byte b) : IPixel { - public byte B; + public byte B = b; - public byte G; + public byte G = g; - public byte R; - - public Bgr888(byte r, byte g, byte b) - { - R = r; - G = g; - B = b; - } + public byte R = r; public Bgr888 FromColor(Color color) { diff --git a/src/Beutl.Engine/Media/Pixel/Bgra4444.cs b/src/Beutl.Engine/Media/Pixel/Bgra4444.cs index d1b97aae6..bbf2936d9 100644 --- a/src/Beutl.Engine/Media/Pixel/Bgra4444.cs +++ b/src/Beutl.Engine/Media/Pixel/Bgra4444.cs @@ -5,14 +5,9 @@ namespace Beutl.Media.Pixel; [StructLayout(LayoutKind.Sequential)] -public struct Bgra4444 : IPixel +public struct Bgra4444(ushort value) : IPixel { - public ushort Value; - - public Bgra4444(ushort value) - { - Value = value; - } + public ushort Value = value; public Bgra4444 FromColor(Color color) { diff --git a/src/Beutl.Engine/Media/Pixel/Bgra8888.cs b/src/Beutl.Engine/Media/Pixel/Bgra8888.cs index 202a90db5..019d0b777 100644 --- a/src/Beutl.Engine/Media/Pixel/Bgra8888.cs +++ b/src/Beutl.Engine/Media/Pixel/Bgra8888.cs @@ -3,23 +3,15 @@ namespace Beutl.Media.Pixel; [StructLayout(LayoutKind.Sequential)] -public struct Bgra8888 : IPixel +public struct Bgra8888(byte r, byte g, byte b, byte a) : IPixel { - public byte B; + public byte B = b; - public byte G; + public byte G = g; - public byte R; + public byte R = r; - public byte A; - - public Bgra8888(byte r, byte g, byte b, byte a) - { - R = r; - G = g; - B = b; - A = a; - } + public byte A = a; public Bgra8888 FromColor(Color color) { diff --git a/src/Beutl.Engine/Media/Pixel/Grayscale8.cs b/src/Beutl.Engine/Media/Pixel/Grayscale8.cs index 7e220475d..096bc569d 100644 --- a/src/Beutl.Engine/Media/Pixel/Grayscale8.cs +++ b/src/Beutl.Engine/Media/Pixel/Grayscale8.cs @@ -3,14 +3,9 @@ namespace Beutl.Media.Pixel; [StructLayout(LayoutKind.Sequential)] -public struct Grayscale8 : IPixel +public struct Grayscale8(byte value) : IPixel { - public byte Value; - - public Grayscale8(byte value) - { - Value = value; - } + public byte Value = value; public Grayscale8 FromColor(Color color) { diff --git a/src/Beutl.Engine/Media/PixelPoint.cs b/src/Beutl.Engine/Media/PixelPoint.cs index b6631fea5..c83452dd8 100644 --- a/src/Beutl.Engine/Media/PixelPoint.cs +++ b/src/Beutl.Engine/Media/PixelPoint.cs @@ -16,9 +16,14 @@ namespace Beutl.Media; /// /// Represents a point in device pixels. /// +/// +/// Initializes a new instance of the structure. +/// +/// The X co-ordinate. +/// The Y co-ordinate. [JsonConverter(typeof(PixelPointJsonConverter))] [TypeConverter(typeof(PixelPointConverter))] -public readonly struct PixelPoint +public readonly struct PixelPoint(int x, int y) : IEquatable, IParsable, ISpanParsable, @@ -32,26 +37,15 @@ public readonly struct PixelPoint /// public static readonly PixelPoint Origin = new(0, 0); - /// - /// Initializes a new instance of the structure. - /// - /// The X co-ordinate. - /// The Y co-ordinate. - public PixelPoint(int x, int y) - { - X = x; - Y = y; - } - /// /// Gets the X co-ordinate. /// - public int X { get; } + public int X { get; } = x; /// /// Gets the Y co-ordinate. /// - public int Y { get; } + public int Y { get; } = y; static int ITupleConvertible.TupleLength => 2; diff --git a/src/Beutl.Engine/Media/PixelSize.cs b/src/Beutl.Engine/Media/PixelSize.cs index 0ff7eb25f..1b60ed867 100644 --- a/src/Beutl.Engine/Media/PixelSize.cs +++ b/src/Beutl.Engine/Media/PixelSize.cs @@ -16,9 +16,14 @@ namespace Beutl.Media; /// /// Represents a size in device pixels. /// +/// +/// Initializes a new instance of the structure. +/// +/// The width. +/// The height. [JsonConverter(typeof(PixelSizeJsonConverter))] [TypeConverter(typeof(PixelSizeConverter))] -public readonly struct PixelSize +public readonly struct PixelSize(int width, int height) : IEquatable, IParsable, ISpanParsable, @@ -30,17 +35,6 @@ public readonly struct PixelSize /// public static readonly PixelSize Empty = new(0, 0); - /// - /// Initializes a new instance of the structure. - /// - /// The width. - /// The height. - public PixelSize(int width, int height) - { - Width = width; - Height = height; - } - /// /// Gets the aspect ratio of the size. /// @@ -49,12 +43,12 @@ public PixelSize(int width, int height) /// /// Gets the width. /// - public int Width { get; } + public int Width { get; } = width; /// /// Gets the height. /// - public int Height { get; } + public int Height { get; } = height; static int ITupleConvertible.TupleLength => 2; diff --git a/src/Beutl.Engine/Media/Source/SoundSource.cs b/src/Beutl.Engine/Media/Source/SoundSource.cs index 88294777a..699d96b5d 100644 --- a/src/Beutl.Engine/Media/Source/SoundSource.cs +++ b/src/Beutl.Engine/Media/Source/SoundSource.cs @@ -5,33 +5,22 @@ namespace Beutl.Media.Source; -public class SoundSource : ISoundSource +public class SoundSource(Ref mediaReader, string fileName) : ISoundSource { - private readonly Ref _mediaReader; - - public SoundSource(Ref mediaReader, string fileName) - { - _mediaReader = mediaReader; - Name = fileName; - Duration = TimeSpan.FromSeconds(mediaReader.Value.AudioInfo.Duration.ToDouble()); - SampleRate = mediaReader.Value.AudioInfo.SampleRate; - NumChannels = mediaReader.Value.AudioInfo.NumChannels; - } - ~SoundSource() { Dispose(); } - public TimeSpan Duration { get; } + public TimeSpan Duration { get; } = TimeSpan.FromSeconds(mediaReader.Value.AudioInfo.Duration.ToDouble()); - public int SampleRate { get; } + public int SampleRate { get; } = mediaReader.Value.AudioInfo.SampleRate; - public int NumChannels { get; } + public int NumChannels { get; } = mediaReader.Value.AudioInfo.NumChannels; public bool IsDisposed { get; private set; } - public string Name { get; } + public string Name { get; } = fileName; public static SoundSource Open(string fileName) { @@ -57,7 +46,7 @@ public void Dispose() { if (!IsDisposed) { - _mediaReader.Dispose(); + mediaReader.Dispose(); GC.SuppressFinalize(this); IsDisposed = true; } @@ -68,7 +57,7 @@ public SoundSource Clone() if (IsDisposed) throw new ObjectDisposedException(nameof(VideoSource)); - return new SoundSource(_mediaReader.Clone(), Name); + return new SoundSource(mediaReader.Clone(), Name); } public bool Read(int start, int length, [NotNullWhen(true)] out IPcm? sound) @@ -79,7 +68,7 @@ public bool Read(int start, int length, [NotNullWhen(true)] out IPcm? sound) return false; } - return _mediaReader.Value.ReadAudio(start, length, out sound); + return mediaReader.Value.ReadAudio(start, length, out sound); } public bool Read(TimeSpan start, TimeSpan length, [NotNullWhen(true)] out IPcm? sound) @@ -90,7 +79,7 @@ public bool Read(TimeSpan start, TimeSpan length, [NotNullWhen(true)] out IPcm? return false; } - return _mediaReader.Value.ReadAudio(ToSamples(start), ToSamples(length), out sound); + return mediaReader.Value.ReadAudio(ToSamples(start), ToSamples(length), out sound); } public bool Read(TimeSpan start, int length, [NotNullWhen(true)] out IPcm? sound) @@ -101,7 +90,7 @@ public bool Read(TimeSpan start, int length, [NotNullWhen(true)] out IPcm? sound return false; } - return _mediaReader.Value.ReadAudio(ToSamples(start), length, out sound); + return mediaReader.Value.ReadAudio(ToSamples(start), length, out sound); } public bool Read(int start, TimeSpan length, [NotNullWhen(true)] out IPcm? sound) @@ -112,7 +101,7 @@ public bool Read(int start, TimeSpan length, [NotNullWhen(true)] out IPcm? sound return false; } - return _mediaReader.Value.ReadAudio(start, ToSamples(length), out sound); + return mediaReader.Value.ReadAudio(start, ToSamples(length), out sound); } ISoundSource ISoundSource.Clone() => Clone(); diff --git a/src/Beutl.Engine/Media/TextFormatting/FormattedTextTokenizer.cs b/src/Beutl.Engine/Media/TextFormatting/FormattedTextTokenizer.cs index 7d00bd0dd..edc4d383b 100644 --- a/src/Beutl.Engine/Media/TextFormatting/FormattedTextTokenizer.cs +++ b/src/Beutl.Engine/Media/TextFormatting/FormattedTextTokenizer.cs @@ -3,20 +3,13 @@ namespace Beutl.Media.TextFormatting; -public struct FormattedTextTokenizer +public struct FormattedTextTokenizer(string str) { - private readonly string _str; - - public FormattedTextTokenizer(string str) - { - _str = str; - } - public bool CompatMode { get; set; } = false; public int LineCount { get; private set; } = 0; - public List Result { get; } = new(); + public List Result { get; } = []; public void Tokenize() { @@ -24,17 +17,17 @@ public void Tokenize() if (!CompatMode) { - Tokenize(new StringSpan(_str, 0, _str.Length)); + Tokenize(new StringSpan(str, 0, str.Length)); } else { - ReadOnlySpan span = _str.AsSpan(); + ReadOnlySpan span = str.AsSpan(); foreach (ReadOnlySpan linesp in span.EnumerateLines()) { int start = span.IndexOf(linesp, StringComparison.Ordinal); int len = linesp.Length; - Tokenize(new StringSpan(_str, start, len)); + Tokenize(new StringSpan(str, start, len)); Result.Add(new Token(StringSpan.Empty, TokenType.NewLine)); lineCount++; diff --git a/src/Beutl.Engine/Rendering/Cache/RenderCache.cs b/src/Beutl.Engine/Rendering/Cache/RenderCache.cs index 9c5481f9a..66cd04813 100644 --- a/src/Beutl.Engine/Rendering/Cache/RenderCache.cs +++ b/src/Beutl.Engine/Rendering/Cache/RenderCache.cs @@ -10,9 +10,9 @@ namespace Beutl.Rendering.Cache; -public sealed class RenderCache : IDisposable +public sealed class RenderCache(IGraphicNode node) : IDisposable { - private readonly WeakReference _node; + private readonly WeakReference _node = new WeakReference(node); private Ref? _cache; private Rect _cacheBounds; @@ -24,11 +24,6 @@ public sealed class RenderCache : IDisposable private FixedArrayAccessor? _accessor; private int _denum; - public RenderCache(IGraphicNode node) - { - _node = new WeakReference(node); - } - ~RenderCache() { if (!IsDisposed) diff --git a/src/Beutl.Engine/Rendering/Cache/RenderCacheContext.cs b/src/Beutl.Engine/Rendering/Cache/RenderCacheContext.cs index 6566b425a..c33bda482 100644 --- a/src/Beutl.Engine/Rendering/Cache/RenderCacheContext.cs +++ b/src/Beutl.Engine/Rendering/Cache/RenderCacheContext.cs @@ -13,7 +13,7 @@ namespace Beutl.Rendering.Cache; public sealed class RenderCacheContext : IDisposable { - private readonly ConditionalWeakTable _table = new(); + private readonly ConditionalWeakTable _table = []; private RenderCacheOptions _cacheOptions = new(); public RenderCacheOptions CacheOptions diff --git a/src/Beutl.Engine/Rendering/FpsText.cs b/src/Beutl.Engine/Rendering/FpsText.cs index 409449cc7..fa69730be 100644 --- a/src/Beutl.Engine/Rendering/FpsText.cs +++ b/src/Beutl.Engine/Rendering/FpsText.cs @@ -32,48 +32,39 @@ public FpsDrawer StartRender(ImmediateCanvas canvas) return new FpsDrawer(canvas, this); } - public readonly struct FpsDrawer : IDisposable + public readonly struct FpsDrawer(ImmediateCanvas canvas, FpsText fpsText) : IDisposable { - private readonly ImmediateCanvas _canvas; - private readonly FpsText _fpsText; - private readonly DateTime _startTime; - - public FpsDrawer(ImmediateCanvas canvas, FpsText fpsText) - { - _canvas = canvas; - _fpsText = fpsText; - _startTime = DateTime.Now; - } + private readonly DateTime _startTime = DateTime.Now; public void Dispose() { - if (_fpsText.DrawFps) + if (fpsText.DrawFps) { DateTime endTime = DateTime.Now; double sec = (double)(endTime - _startTime).TotalSeconds; double fps = 1 / sec; - _fpsText._maxFps = Math.Max(_fpsText._maxFps, fps); - _fpsText._minFps = Math.Min(_fpsText._minFps, fps); + fpsText._maxFps = Math.Max(fpsText._maxFps, fps); + fpsText._minFps = Math.Min(fpsText._minFps, fps); - _fpsText._prevFps = fps; - _fpsText._avgFps = (_fpsText._prevFps + fps) / 2; + fpsText._prevFps = fps; + fpsText._avgFps = (fpsText._prevFps + fps) / 2; - _fpsText._textBlock.Text = $""" + fpsText._textBlock.Text = $""" {fps:N2} FPS - Min: {_fpsText._minFps:N2} FPS - Max: {_fpsText._maxFps:N2} FPS - Avg: {_fpsText._avgFps:N2} FPS + Min: {fpsText._minFps:N2} FPS + Max: {fpsText._maxFps:N2} FPS + Avg: {fpsText._avgFps:N2} FPS """; - _fpsText._textBlock.Measure(_canvas.Size.ToSize(1)); - float width = _fpsText._textBlock.Bounds.Size.Width; - float height = _fpsText._textBlock.Bounds.Size.Height; + fpsText._textBlock.Measure(canvas.Size.ToSize(1)); + float width = fpsText._textBlock.Bounds.Size.Width; + float height = fpsText._textBlock.Bounds.Size.Height; - using (_canvas.PushTransform(Matrix.CreateTranslation(width / 2, height / 2))) + using (canvas.PushTransform(Matrix.CreateTranslation(width / 2, height / 2))) { - _canvas.DrawRectangle(_fpsText._textBlock.Bounds, s_background, null); - _fpsText._textBlock.Render(_canvas); + canvas.DrawRectangle(fpsText._textBlock.Bounds, s_background, null); + fpsText._textBlock.Render(canvas); } } } diff --git a/src/Beutl.Engine/Rendering/GlContexts/Cgl/CglContext.cs b/src/Beutl.Engine/Rendering/GlContexts/Cgl/CglContext.cs index 3e413da8d..fe37415f9 100644 --- a/src/Beutl.Engine/Rendering/GlContexts/Cgl/CglContext.cs +++ b/src/Beutl.Engine/Rendering/GlContexts/Cgl/CglContext.cs @@ -10,12 +10,12 @@ internal class CglContext : GlContext public CglContext() { - CGLPixelFormatAttribute[] attributes = new[] - { + CGLPixelFormatAttribute[] attributes = + [ CGLPixelFormatAttribute.kCGLPFAOpenGLProfile, (CGLPixelFormatAttribute)CGLOpenGLProfile.kCGLOGLPVersion_3_2_Core, CGLPixelFormatAttribute.kCGLPFADoubleBuffer, CGLPixelFormatAttribute.kCGLPFANone - }; + ]; Cgl.CGLChoosePixelFormat(attributes, out nint pixFormat, out _); @@ -73,6 +73,6 @@ public override GRGlTextureInfo CreateTexture(SKSizeI textureSize) public override void DestroyTexture(uint texture) { - Cgl.glDeleteTextures(1, new[] { texture }); + Cgl.glDeleteTextures(1, [texture]); } } diff --git a/src/Beutl.Engine/Rendering/GlContexts/Glx/Glx.cs b/src/Beutl.Engine/Rendering/GlContexts/Glx/Glx.cs index 247081402..fcf1fcac8 100644 --- a/src/Beutl.Engine/Rendering/GlContexts/Glx/Glx.cs +++ b/src/Beutl.Engine/Rendering/GlContexts/Glx/Glx.cs @@ -57,7 +57,7 @@ internal class Glx static Glx() { - var ptr = glXGetProcAddressARB("glXCreateContextAttribsARB"); + nint ptr = glXGetProcAddressARB("glXCreateContextAttribsARB"); if (ptr != IntPtr.Zero) { glXCreateContextAttribsARB = (glXCreateContextAttribsARBDelegate)Marshal.GetDelegateForFunctionPointer(ptr, typeof(glXCreateContextAttribsARBDelegate)); @@ -136,7 +136,7 @@ public static string[] QueryExtensions(IntPtr dpy, int screen) string? str = QueryExtensionsString(dpy, screen); if (string.IsNullOrEmpty(str)) { - return Array.Empty(); + return []; } return str.Split(' '); diff --git a/src/Beutl.Engine/Rendering/GlContexts/Glx/GlxContext.cs b/src/Beutl.Engine/Rendering/GlContexts/Glx/GlxContext.cs index 2bb214477..ff22e402c 100644 --- a/src/Beutl.Engine/Rendering/GlContexts/Glx/GlxContext.cs +++ b/src/Beutl.Engine/Rendering/GlContexts/Glx/GlxContext.cs @@ -24,8 +24,8 @@ public GlxContext() throw new Exception("Failed to open X display."); } - int[] visualAttribs = new[] - { + int[] visualAttribs = + [ Glx.GLX_X_RENDERABLE, Xlib.True, Glx.GLX_DRAWABLE_TYPE, Glx.GLX_PIXMAP_BIT, Glx.GLX_RENDER_TYPE, Glx.GLX_RGBA_BIT, @@ -39,7 +39,7 @@ public GlxContext() // Glx.GLX_SAMPLE_BUFFERS, 1, // Glx.GLX_SAMPLES, 4, Xlib.None - }; + ]; if (!Glx.glXQueryVersion(fDisplay, out int glxMajor, out int glxMinor) || (glxMajor < 1) || @@ -105,7 +105,7 @@ public GlxContext() } flags.Add(Xlib.None); - fContext = Glx.glXCreateContextAttribsARB(fDisplay, bestFBC, IntPtr.Zero, Xlib.True, flags.ToArray()); + fContext = Glx.glXCreateContextAttribsARB(fDisplay, bestFBC, IntPtr.Zero, Xlib.True, [.. flags]); } if (fContext == IntPtr.Zero) @@ -182,6 +182,6 @@ public override GRGlTextureInfo CreateTexture(SKSizeI textureSize) public override void DestroyTexture(uint texture) { - Glx.glDeleteTextures(1, new[] { texture }); + Glx.glDeleteTextures(1, [texture]); } } diff --git a/src/Beutl.Engine/Rendering/GlContexts/Wgl/Wgl.cs b/src/Beutl.Engine/Rendering/GlContexts/Wgl/Wgl.cs index 8426159f4..92c56a290 100644 --- a/src/Beutl.Engine/Rendering/GlContexts/Wgl/Wgl.cs +++ b/src/Beutl.Engine/Rendering/GlContexts/Wgl/Wgl.cs @@ -194,7 +194,7 @@ public static string[] GetExtensionsARB(nint dc) string? str = GetExtensionsStringARB(dc); if (string.IsNullOrEmpty(str)) { - return Array.Empty(); + return []; } return str.Split(' '); } diff --git a/src/Beutl.Engine/Rendering/GlContexts/Wgl/WglContext.cs b/src/Beutl.Engine/Rendering/GlContexts/Wgl/WglContext.cs index 285fd924c..7451c2066 100644 --- a/src/Beutl.Engine/Rendering/GlContexts/Wgl/WglContext.cs +++ b/src/Beutl.Engine/Rendering/GlContexts/Wgl/WglContext.cs @@ -31,8 +31,8 @@ public WglContext() throw new Exception("DC does not have extensions."); } - int[] iAttrs = new int[] - { + int[] iAttrs = + [ Wgl.WGL_ACCELERATION_ARB, Wgl.WGL_FULL_ACCELERATION_ARB, Wgl.WGL_DRAW_TO_WINDOW_ARB, Wgl.TRUE, //Wgl.WGL_DOUBLE_BUFFER_ARB, (doubleBuffered ? TRUE : FALSE), @@ -43,7 +43,7 @@ public WglContext() Wgl.WGL_ALPHA_BITS_ARB, 8, Wgl.WGL_STENCIL_BITS_ARB, 8, Wgl.NONE, Wgl.NONE - }; + ]; int[] piFormats = new int[1]; uint nFormats; lock (s_lock) @@ -149,6 +149,6 @@ public override GRGlTextureInfo CreateTexture(SKSizeI textureSize) public override void DestroyTexture(uint texture) { - Wgl.glDeleteTextures(1, new[] { texture }); + Wgl.glDeleteTextures(1, [texture]); } } diff --git a/src/Beutl.Engine/Rendering/RenderLayer.cs b/src/Beutl.Engine/Rendering/RenderLayer.cs index a823ffa28..9b9aeaa15 100644 --- a/src/Beutl.Engine/Rendering/RenderLayer.cs +++ b/src/Beutl.Engine/Rendering/RenderLayer.cs @@ -8,24 +8,18 @@ namespace Beutl.Rendering; -public sealed class RenderLayer : IDisposable +public sealed class RenderLayer(RenderScene renderScene) : IDisposable { - private class Entry : IDisposable + private class Entry(DrawableNode node) : IDisposable { - public Entry(DrawableNode node) - { - Node = node; - IsDirty = true; - } - ~Entry() { Dispose(); } - public DrawableNode Node { get; } + public DrawableNode Node { get; } = node; - public bool IsDirty { get; set; } + public bool IsDirty { get; set; } = true; public bool IsDisposed { get; private set; } @@ -41,15 +35,9 @@ public void Dispose() } // このテーブルは本描画するときに、自分のレイヤー以外のものを削除する。 - private readonly ConditionalWeakTable _cache = new(); - private readonly RenderScene _renderScene; + private readonly ConditionalWeakTable _cache = []; private List? _currentFrame; - public RenderLayer(RenderScene renderScene) - { - _renderScene = renderScene; - } - private List CurrentFrame => _currentFrame ??= new(1); public void Clear() @@ -83,7 +71,7 @@ public void Add(Drawable drawable) if (entry.IsDirty) { // DeferredCanvasを作成し、記録 - using var canvas = new DeferradCanvas(entry.Node, _renderScene.Size); + using var canvas = new DeferradCanvas(entry.Node, renderScene.Size); drawable.Render(canvas); entry.IsDirty = false; } @@ -127,7 +115,7 @@ public void Render(ImmediateCanvas canvas) Drawable drawable = node.Drawable; if (entry.IsDirty) { - var dcanvas = new DeferradCanvas(node, _renderScene.Size); + var dcanvas = new DeferradCanvas(node, renderScene.Size); drawable.Render(dcanvas); entry.IsDirty = false; } @@ -169,7 +157,7 @@ public void Dispose() public Rect[] GetBoundaries() { if (_currentFrame == null || _currentFrame.Count == 0) - return Array.Empty(); + return []; var list = new Rect[_currentFrame.Count]; int index = 0; diff --git a/src/Beutl.Engine/Rendering/RenderScene.cs b/src/Beutl.Engine/Rendering/RenderScene.cs index 6ab0fdc90..4e4cf826f 100644 --- a/src/Beutl.Engine/Rendering/RenderScene.cs +++ b/src/Beutl.Engine/Rendering/RenderScene.cs @@ -3,14 +3,9 @@ namespace Beutl.Rendering; -public sealed class RenderScene : IDisposable +public sealed class RenderScene(PixelSize size) : IDisposable { - private readonly SortedDictionary _layer = new(); - - public RenderScene(PixelSize size) - { - Size = size; - } + private readonly SortedDictionary _layer = []; public RenderLayer this[int index] { @@ -26,7 +21,7 @@ public RenderLayer this[int index] } } - public PixelSize Size { get; } + public PixelSize Size { get; } = size; public void Clear() { diff --git a/src/Beutl.Engine/Styling/SetterInstance.cs b/src/Beutl.Engine/Styling/SetterInstance.cs index 24837e262..c9680b82f 100644 --- a/src/Beutl.Engine/Styling/SetterInstance.cs +++ b/src/Beutl.Engine/Styling/SetterInstance.cs @@ -4,16 +4,10 @@ namespace Beutl.Styling; #pragma warning disable CA1816 -public class SetterInstance : ISetterInstance +public class SetterInstance(Setter setter, ICoreObject target) : ISetterInstance { - private ICoreObject? _target; - private Setter? _setter; - - public SetterInstance(Setter setter, ICoreObject target) - { - _setter = setter; - _target = target; - } + private ICoreObject? _target = target; + private Setter? _setter = setter; public CoreProperty Property => Setter.Property; diff --git a/src/Beutl.Engine/Styling/Style.cs b/src/Beutl.Engine/Styling/Style.cs index 9b21c4adb..1e14d5d78 100644 --- a/src/Beutl.Engine/Styling/Style.cs +++ b/src/Beutl.Engine/Styling/Style.cs @@ -9,7 +9,7 @@ public class Style : IStyle public Style() { - _setters = new Setters(); + _setters = []; _setters.Invalidated += (_, _) => Invalidated?.Invoke(this, EventArgs.Empty); } diff --git a/src/Beutl.Engine/Styling/StyleInstance.cs b/src/Beutl.Engine/Styling/StyleInstance.cs index 6f161e749..15fdf8b32 100644 --- a/src/Beutl.Engine/Styling/StyleInstance.cs +++ b/src/Beutl.Engine/Styling/StyleInstance.cs @@ -6,28 +6,19 @@ namespace Beutl.Styling; #pragma warning disable CA1816 -public class StyleInstance : IStyleInstance +public class StyleInstance(ICoreObject target, IStyle source, ISetterInstance[] setters, IStyleInstance? baseStyle) : IStyleInstance { - private ICoreObject? _target; - private IStyle? _source; - private ISetterInstance[] _setters; + private ICoreObject? _target = target; + private IStyle? _source = source; private ISetterInstance[][]? _cache; - public StyleInstance(ICoreObject target, IStyle source, ISetterInstance[] setters, IStyleInstance? baseStyle) - { - _target = target; - _source = source; - _setters = setters; - BaseStyle = baseStyle; - } - - public IStyleInstance? BaseStyle { get; private set; } + public IStyleInstance? BaseStyle { get; private set; } = baseStyle; public ICoreObject Target => _target ?? throw new InvalidOperationException(); public IStyle Source => _source ?? throw new InvalidOperationException(); - public ReadOnlySpan Setters => _setters; + public ReadOnlySpan Setters => setters; public void Apply(IClock clock) { @@ -90,7 +81,7 @@ public void Dispose() _target = null; _source = null; - _setters = Array.Empty(); + setters = []; _cache = null; BaseStyle = null; } diff --git a/src/Beutl.Engine/Styling/StyleSerializer.cs b/src/Beutl.Engine/Styling/StyleSerializer.cs index ec025065a..fb77a36c5 100644 --- a/src/Beutl.Engine/Styling/StyleSerializer.cs +++ b/src/Beutl.Engine/Styling/StyleSerializer.cs @@ -114,8 +114,11 @@ public static (string, JsonNode?) ToJson(this ISetter setter, Type targetType, I } else { - var json = new JsonObject(); - json["Value"] = value; + var json = new JsonObject + { + ["Value"] = value + }; + if (owner != null) json["Owner"] = owner; if (animationNode != null) diff --git a/src/Beutl.Engine/Styling/Styleable.cs b/src/Beutl.Engine/Styling/Styleable.cs index e31c0c14c..705100f95 100644 --- a/src/Beutl.Engine/Styling/Styleable.cs +++ b/src/Beutl.Engine/Styling/Styleable.cs @@ -27,7 +27,7 @@ static Styleable() protected Styleable() { - _styles = new(); + _styles = []; _styles.Attached += item => { item.Invalidated += Style_Invalidated; diff --git a/src/Beutl.Extensibility/IAbstractProperty.cs b/src/Beutl.Extensibility/IAbstractProperty.cs index abbae66d7..4df4cd15c 100644 --- a/src/Beutl.Extensibility/IAbstractProperty.cs +++ b/src/Beutl.Extensibility/IAbstractProperty.cs @@ -86,20 +86,11 @@ IAbstractProperty IAbstractAnimatableProperty.CreateKeyFrameProperty(IKeyFrameAn } } -internal sealed class KeyFramePropertyWrapper : IAbstractProperty +internal sealed class KeyFramePropertyWrapper(KeyFrame keyFrame, KeyFrameAnimation animation) : IAbstractProperty { - private readonly KeyFrame _keyFrame; - private readonly KeyFrameAnimation _animation; + public Type ImplementedType => animation.Property.OwnerType; - public KeyFramePropertyWrapper(KeyFrame keyFrame, KeyFrameAnimation animation) - { - _keyFrame = keyFrame; - _animation = animation; - } - - public Type ImplementedType => _animation.Property.OwnerType; - - public Type PropertyType => _animation.Property.PropertyType; + public Type PropertyType => animation.Property.PropertyType; public string DisplayName => "KeyFrame Value"; @@ -107,20 +98,20 @@ public KeyFramePropertyWrapper(KeyFrame keyFrame, KeyFrameAnimation animat public IObservable GetObservable() { - return _keyFrame.GetObservable(GetProperty()); + return keyFrame.GetObservable(GetProperty()); } public T? GetValue() { - return _keyFrame.Value; + return keyFrame.Value; } public void SetValue(T? value) { - _keyFrame.SetValue(GetProperty(), value); + keyFrame.SetValue(GetProperty(), value); } - CoreProperty? IAbstractProperty.GetCoreProperty() => _animation.Property; + CoreProperty? IAbstractProperty.GetCoreProperty() => animation.Property; private static CoreProperty GetProperty() { @@ -129,6 +120,6 @@ public void SetValue(T? value) public object? GetDefaultValue() { - return _animation.Property.GetMetadata(ImplementedType).GetDefaultValue(); + return animation.Property.GetMetadata(ImplementedType).GetDefaultValue(); } } diff --git a/src/Beutl.Extensions.FFmpeg/Decoding/FFmpegDecoderInfo.cs b/src/Beutl.Extensions.FFmpeg/Decoding/FFmpegDecoderInfo.cs index 5c1283e0d..2be0dee7e 100644 --- a/src/Beutl.Extensions.FFmpeg/Decoding/FFmpegDecoderInfo.cs +++ b/src/Beutl.Extensions.FFmpeg/Decoding/FFmpegDecoderInfo.cs @@ -6,15 +6,8 @@ namespace Beutl.Embedding.FFmpeg.Decoding; namespace Beutl.Extensions.FFmpeg.Decoding; #endif -public sealed class FFmpegDecoderInfo : IDecoderInfo +public sealed class FFmpegDecoderInfo(FFmpegDecodingSettings settings) : IDecoderInfo { - private readonly FFmpegDecodingSettings _settings; - - public FFmpegDecoderInfo(FFmpegDecodingSettings settings) - { - _settings = settings; - } - public string Name => "FFmpeg Decoder"; public IEnumerable AudioExtensions() @@ -33,7 +26,7 @@ public IEnumerable AudioExtensions() { try { - return new FFmpegReader(file, options, _settings); + return new FFmpegReader(file, options, settings); } catch { diff --git a/src/Beutl.Extensions.FFmpeg/Decoding/FFmpegReader.cs b/src/Beutl.Extensions.FFmpeg/Decoding/FFmpegReader.cs index c8f2b4648..ce67a5e3f 100644 --- a/src/Beutl.Extensions.FFmpeg/Decoding/FFmpegReader.cs +++ b/src/Beutl.Extensions.FFmpeg/Decoding/FFmpegReader.cs @@ -343,8 +343,8 @@ public override bool ReadVideo(int frame, [NotNullWhen(true)] out IBitmap? image var bmp = new Bitmap(width, height); Bgra8888* buf = (Bgra8888*)bmp.Data; - byte*[] dst_data = { (byte*)buf, null, null, null }; - int[] dst_linesize = { output_linesize, 0, 0, 0 }; + byte*[] dst_data = [(byte*)buf, null, null, null]; + int[] dst_linesize = [output_linesize, 0, 0, 0]; byte*[] src_data = _videoFrame->data; int[] src_linesize = _videoFrame->linesize; diff --git a/src/Beutl.Extensions.FFmpeg/Encoding/FFmpegWriter.cs b/src/Beutl.Extensions.FFmpeg/Encoding/FFmpegWriter.cs index 738991329..4e95bf34f 100644 --- a/src/Beutl.Extensions.FFmpeg/Encoding/FFmpegWriter.cs +++ b/src/Beutl.Extensions.FFmpeg/Encoding/FFmpegWriter.cs @@ -143,8 +143,8 @@ public override bool AddVideo(IBitmap image) UpdateSwsContext(new PixelSize(image.Width, image.Height)); int output_linesize = image.Width * 4; - byte*[] src_data = { (byte*)image.Data, null, null, null }; - int[] src_linesize = { output_linesize, 0, 0, 0 }; + byte*[] src_data = [(byte*)image.Data, null, null, null]; + int[] src_linesize = [output_linesize, 0, 0, 0]; ffmpeg.sws_scale( _swsContext, src_data, diff --git a/src/Beutl.Language/LocalizeService.cs b/src/Beutl.Language/LocalizeService.cs index b64984116..fe46c7221 100644 --- a/src/Beutl.Language/LocalizeService.cs +++ b/src/Beutl.Language/LocalizeService.cs @@ -6,10 +6,10 @@ public sealed class LocalizeService { public static readonly LocalizeService Instance = new(); private readonly string[] _supported = - { + [ "en-US", "ja-JP", - }; + ]; public bool IsSupportedCulture(CultureInfo ci) { diff --git a/src/Beutl.Operators/Configure/AnimatableCorePropertyImpl.cs b/src/Beutl.Operators/Configure/AnimatableCorePropertyImpl.cs index 242af1f56..9a9d9a7d4 100644 --- a/src/Beutl.Operators/Configure/AnimatableCorePropertyImpl.cs +++ b/src/Beutl.Operators/Configure/AnimatableCorePropertyImpl.cs @@ -5,26 +5,19 @@ namespace Beutl.Operators.Configure; -public sealed class AnimatableCorePropertyImpl : CorePropertyImpl, IAbstractAnimatableProperty +public sealed class AnimatableCorePropertyImpl(CoreProperty property, Animatable obj) + : CorePropertyImpl(property, obj), IAbstractAnimatableProperty { - private sealed class AnimationObservable : LightweightObservableBase?> + private sealed class AnimationObservable(CoreProperty property, Animatable obj) : LightweightObservableBase?> { - private readonly CoreProperty _property; - private readonly Animatable _obj; private IDisposable? _disposable0; - public AnimationObservable(CoreProperty property, Animatable obj) - { - _property = property; - _obj = obj; - } - protected override void Subscribed(IObserver?> observer, bool first) { base.Subscribed(observer, first); - foreach (IAnimation item in _obj.Animations.GetMarshal().Value) + foreach (IAnimation item in obj.Animations.GetMarshal().Value) { - if (item.Property.Id == _property.Id + if (item.Property.Id == property.Id && item is IAnimation animation) { observer.OnNext(animation); @@ -44,10 +37,10 @@ protected override void Deinitialize() protected override void Initialize() { _disposable0?.Dispose(); - _disposable0 = _obj.Animations.ForEachItem( + _disposable0 = obj.Animations.ForEachItem( item => { - if (item.Property.Id == _property.Id + if (item.Property.Id == property.Id && item is IAnimation animation) { PublishNext(animation); @@ -55,7 +48,7 @@ protected override void Initialize() }, item => { - if (item.Property.Id == _property.Id) + if (item.Property.Id == property.Id) { PublishNext(null); } @@ -66,19 +59,13 @@ protected override void Initialize() } } - public AnimatableCorePropertyImpl(CoreProperty property, Animatable obj) - : base(property, obj) - { - ObserveAnimation = new AnimationObservable(property, obj); - } - public IAnimation? Animation { get => GetAnimation(); set => SetAnimation(value); } - public IObservable?> ObserveAnimation { get; } + public IObservable?> ObserveAnimation { get; } = new AnimationObservable(property, obj); private IAnimation? GetAnimation() { diff --git a/src/Beutl.Operators/Configure/CorePropertyImpl.cs b/src/Beutl.Operators/Configure/CorePropertyImpl.cs index 543742570..947570769 100644 --- a/src/Beutl.Operators/Configure/CorePropertyImpl.cs +++ b/src/Beutl.Operators/Configure/CorePropertyImpl.cs @@ -2,20 +2,14 @@ namespace Beutl.Operators.Configure; -public class CorePropertyImpl : IAbstractProperty +public class CorePropertyImpl(CoreProperty property, ICoreObject obj) : IAbstractProperty { private Type? _implementedType; private IObservable? _observable; - public CorePropertyImpl(CoreProperty property, ICoreObject obj) - { - Property = property; - Object = obj; - } - - public ICoreObject Object { get; } + public ICoreObject Object { get; } = obj; - public CoreProperty Property { get; } + public CoreProperty Property { get; } = property; public Type ImplementedType => _implementedType ??= Object.GetType(); diff --git a/src/Beutl.Operators/Configure/Effects/FilterEffectOperator.cs b/src/Beutl.Operators/Configure/Effects/FilterEffectOperator.cs index a3b685f46..61d4aa337 100644 --- a/src/Beutl.Operators/Configure/Effects/FilterEffectOperator.cs +++ b/src/Beutl.Operators/Configure/Effects/FilterEffectOperator.cs @@ -9,7 +9,7 @@ namespace Beutl.Operators.Configure.Effects; public abstract class FilterEffectOperator : ConfigureOperator where T : FilterEffect, new() { - private readonly ConditionalWeakTable _table = new(); + private readonly ConditionalWeakTable _table = []; protected override void PreProcess(Drawable target, T value) { diff --git a/src/Beutl.Operators/Configure/Transform/TransformOperator.cs b/src/Beutl.Operators/Configure/Transform/TransformOperator.cs index 4a3652fa2..4cca6abae 100644 --- a/src/Beutl.Operators/Configure/Transform/TransformOperator.cs +++ b/src/Beutl.Operators/Configure/Transform/TransformOperator.cs @@ -11,7 +11,7 @@ namespace Beutl.Operators.Configure.Transform; public abstract class TransformOperator : ConfigureOperator where T : Transform, new() { - private readonly ConditionalWeakTable _table = new(); + private readonly ConditionalWeakTable _table = []; protected override void PreProcess(Drawable target, T value) { diff --git a/src/Beutl.PackageTools/KurukuruProgress.cs b/src/Beutl.PackageTools/KurukuruProgress.cs index 871f1f718..7804cfe8a 100644 --- a/src/Beutl.PackageTools/KurukuruProgress.cs +++ b/src/Beutl.PackageTools/KurukuruProgress.cs @@ -1,18 +1,9 @@ namespace Beutl.PackageTools; -public class KurukuruProgress : IProgress +public class KurukuruProgress(Spinner spinner, string message) : IProgress { - private readonly Spinner _spinner; - private readonly string _message; - - public KurukuruProgress(Spinner spinner, string message) - { - _spinner = spinner; - _message = message; - } - public void Report(double value) { - _spinner.Text = $"{_message} {value:P}"; + spinner.Text = $"{message} {value:P}"; } } diff --git a/src/Beutl.PackageTools/PackageIdArgumentParser.cs b/src/Beutl.PackageTools/PackageIdArgumentParser.cs index 8846aeb2f..d322c0122 100644 --- a/src/Beutl.PackageTools/PackageIdArgumentParser.cs +++ b/src/Beutl.PackageTools/PackageIdArgumentParser.cs @@ -2,16 +2,10 @@ namespace Beutl.PackageTools; -public class PackageIdArgumentParser +public class PackageIdArgumentParser(BeutlApiApplication apiApp) { - private readonly DiscoverService _discover; - private readonly InstalledPackageRepository _installedPackageRepository; - - public PackageIdArgumentParser(BeutlApiApplication apiApp) - { - _discover = apiApp.GetResource(); - _installedPackageRepository = apiApp.GetResource(); - } + private readonly DiscoverService _discover = apiApp.GetResource(); + private readonly InstalledPackageRepository _installedPackageRepository = apiApp.GetResource(); public async ValueTask LoadArgs( HashSet<(PackageIdentity, Release?)> packages, diff --git a/src/Beutl.PackageTools/UninstallCommand.cs b/src/Beutl.PackageTools/UninstallCommand.cs index c14627515..b3b9626d2 100644 --- a/src/Beutl.PackageTools/UninstallCommand.cs +++ b/src/Beutl.PackageTools/UninstallCommand.cs @@ -89,11 +89,11 @@ public void UninstallPackages(HashSet<(PackageIdentity, Release?)> items, bool v string installed = Helper.PackagePathResolver.GetInstalledPath(package); if (installed != null) { - installeds = new string[] { installed }; + installeds = [installed]; } else { - installeds = Array.Empty(); + installeds = []; } } diff --git a/src/Beutl.ProjectSystem/ChangeSetterValueCommand.cs b/src/Beutl.ProjectSystem/ChangeSetterValueCommand.cs index 23ae3d0f8..82886a4a8 100644 --- a/src/Beutl.ProjectSystem/ChangeSetterValueCommand.cs +++ b/src/Beutl.ProjectSystem/ChangeSetterValueCommand.cs @@ -2,28 +2,17 @@ namespace Beutl; -public sealed class ChangeSetterValueCommand : IRecordableCommand +public sealed class ChangeSetterValueCommand(Setter setter, T oldValue, T newValue) : IRecordableCommand { - private readonly Setter _setter; - private readonly T _oldValue; - private readonly T _newValue; - - public ChangeSetterValueCommand(Setter setter, T oldValue, T newValue) - { - _setter = setter; - _oldValue = oldValue; - _newValue = newValue; - } - public void Do() { - _setter.Value = _newValue; + setter.Value = newValue; } public void Redo() => Do(); public void Undo() { - _setter.Value = _oldValue; + setter.Value = oldValue; } } diff --git a/src/Beutl.ProjectSystem/NodeTree/Connection.cs b/src/Beutl.ProjectSystem/NodeTree/Connection.cs index 200b97a05..22058cfd8 100644 --- a/src/Beutl.ProjectSystem/NodeTree/Connection.cs +++ b/src/Beutl.ProjectSystem/NodeTree/Connection.cs @@ -11,7 +11,7 @@ public enum ConnectionStatus Error = Connected | 0b10000, } -public sealed class Connection : CoreObject +public sealed class Connection(IInputSocket input, IOutputSocket output) : CoreObject { public static readonly CoreProperty StatusProperty; private ConnectionStatus _status; @@ -23,19 +23,13 @@ static Connection() .Register(); } - public Connection(IInputSocket input, IOutputSocket output) - { - Input = input; - Output = output; - } - public ConnectionStatus Status { get => _status; private set => SetAndRaise(StatusProperty, ref _status, value); } - public IInputSocket Input { get; } + public IInputSocket Input { get; } = input; - public IOutputSocket Output { get; } + public IOutputSocket Output { get; } = output; } diff --git a/src/Beutl.ProjectSystem/NodeTree/ElementNodeTreeModel.cs b/src/Beutl.ProjectSystem/NodeTree/ElementNodeTreeModel.cs index da3f93197..7332c1c89 100644 --- a/src/Beutl.ProjectSystem/NodeTree/ElementNodeTreeModel.cs +++ b/src/Beutl.ProjectSystem/NodeTree/ElementNodeTreeModel.cs @@ -11,7 +11,7 @@ namespace Beutl.NodeTree; public class ElementNodeTreeModel : NodeTreeModel { // 評価する順番 - private readonly List _evalContexts = new(); + private readonly List _evalContexts = []; private bool _isDirty = true; public ElementNodeTreeModel() @@ -106,7 +106,7 @@ private void Build(IRenderer renderer, IClock clock) foreach (Node? lastNode in Nodes.Where(x => !x.Items.Any(x => x is IOutputSocket))) { BuildNode(lastNode, stack); - NodeEvaluationContext[] array = stack.ToArray(); + NodeEvaluationContext[] array = [.. stack]; Array.Reverse(array); _evalContexts.Add(array); diff --git a/src/Beutl.ProjectSystem/NodeTree/NodeGroup.cs b/src/Beutl.ProjectSystem/NodeTree/NodeGroup.cs index 44d1ff40c..14aa23470 100644 --- a/src/Beutl.ProjectSystem/NodeTree/NodeGroup.cs +++ b/src/Beutl.ProjectSystem/NodeTree/NodeGroup.cs @@ -110,7 +110,7 @@ public object InitializeForState(IRenderer renderer, IClock clock) { var stack = new Stack(); BuildNode(lastNode, stack); - NodeEvaluationContext[] array = stack.ToArray(); + NodeEvaluationContext[] array = [.. stack]; evalContexts.Add(array); foreach (NodeEvaluationContext item in array) diff --git a/src/Beutl.ProjectSystem/NodeTree/NodeRegistry.cs b/src/Beutl.ProjectSystem/NodeTree/NodeRegistry.cs index 11e15da5b..f51b2cac2 100644 --- a/src/Beutl.ProjectSystem/NodeTree/NodeRegistry.cs +++ b/src/Beutl.ProjectSystem/NodeTree/NodeRegistry.cs @@ -7,7 +7,7 @@ namespace Beutl.NodeTree; public class NodeRegistry { - private static readonly List s_nodes = new(); + private static readonly List s_nodes = []; internal static int s_totalCount; public static void RegisterNode< @@ -124,7 +124,7 @@ public record RegistryItem( public record GroupableRegistryItem(string DisplayName, Color AccentColor) : BaseRegistryItem(DisplayName, AccentColor) { - public List Items { get; } = new(); + public List Items { get; } = []; internal void Merge(List items) { diff --git a/src/Beutl.ProjectSystem/NodeTree/Nodes/Brushes/GradientBrushNode.cs b/src/Beutl.ProjectSystem/NodeTree/Nodes/Brushes/GradientBrushNode.cs index fe1da8c64..b7f077999 100644 --- a/src/Beutl.ProjectSystem/NodeTree/Nodes/Brushes/GradientBrushNode.cs +++ b/src/Beutl.ProjectSystem/NodeTree/Nodes/Brushes/GradientBrushNode.cs @@ -8,7 +8,7 @@ public class GradientBrushNode : BrushNode public GradientBrushNode() { SpreadMethod = AsInput(GradientBrush.SpreadMethodProperty); - GradientStops = AsInput(GradientBrush.GradientStopsProperty, new GradientStops()); + GradientStops = AsInput(GradientBrush.GradientStopsProperty, []); } protected InputSocket SpreadMethod { get; } diff --git a/src/Beutl.ProjectSystem/NodeTree/Nodes/ConfigureNode.cs b/src/Beutl.ProjectSystem/NodeTree/Nodes/ConfigureNode.cs index 342f59b32..13e478f1c 100644 --- a/src/Beutl.ProjectSystem/NodeTree/Nodes/ConfigureNode.cs +++ b/src/Beutl.ProjectSystem/NodeTree/Nodes/ConfigureNode.cs @@ -2,17 +2,11 @@ namespace Beutl.NodeTree.Nodes; -public class ConfigureNodeEvaluationState +public class ConfigureNodeEvaluationState(Drawable? previous, object? addtionalState) { - public ConfigureNodeEvaluationState(Drawable? previous, object? addtionalState) - { - Previous = previous; - AddtionalState = addtionalState; - } - - public Drawable? Previous { get; set; } + public Drawable? Previous { get; set; } = previous; - public object? AddtionalState { get; set; } + public object? AddtionalState { get; set; } = addtionalState; } public abstract class ConfigureNode : Node diff --git a/src/Beutl.ProjectSystem/NodeTree/Nodes/Filters/FilterEffectNode.cs b/src/Beutl.ProjectSystem/NodeTree/Nodes/Filters/FilterEffectNode.cs index 7e1522d06..7421bebd4 100644 --- a/src/Beutl.ProjectSystem/NodeTree/Nodes/Filters/FilterEffectNode.cs +++ b/src/Beutl.ProjectSystem/NodeTree/Nodes/Filters/FilterEffectNode.cs @@ -2,14 +2,9 @@ namespace Beutl.NodeTree.Nodes.Effects; -public sealed class FilterEffectNodeEvaluationState +public sealed class FilterEffectNodeEvaluationState(FilterEffect? created) { - public FilterEffectNodeEvaluationState(FilterEffect? created) - { - Created = created; - } - - public FilterEffect? Created { get; set; } + public FilterEffect? Created { get; set; } = created; public CombinedFilterEffect? AddtionalState { get; set; } } diff --git a/src/Beutl.ProjectSystem/NodeTree/Nodes/Group/GroupNode.cs b/src/Beutl.ProjectSystem/NodeTree/Nodes/Group/GroupNode.cs index dc37ca3fa..26e292773 100644 --- a/src/Beutl.ProjectSystem/NodeTree/Nodes/Group/GroupNode.cs +++ b/src/Beutl.ProjectSystem/NodeTree/Nodes/Group/GroupNode.cs @@ -12,9 +12,9 @@ namespace Beutl.NodeTree.Nodes.Group; // Todo: ファイルからノードグループを読み込めるようにする。 public class GroupNode : Node { - private readonly CompositeDisposable _disposables = new(); - private readonly List _outputSocketDisposable = new(); - private readonly List _inputSocketDisposable = new(); + private readonly CompositeDisposable _disposables = []; + private readonly List _outputSocketDisposable = []; + private readonly List _inputSocketDisposable = []; private int _outputSocketCount = 0; private int _inputSocketCount = 0; diff --git a/src/Beutl.ProjectSystem/NodeTree/Nodes/Transform/TransformNode.cs b/src/Beutl.ProjectSystem/NodeTree/Nodes/Transform/TransformNode.cs index 39613cda9..979d5d4d7 100644 --- a/src/Beutl.ProjectSystem/NodeTree/Nodes/Transform/TransformNode.cs +++ b/src/Beutl.ProjectSystem/NodeTree/Nodes/Transform/TransformNode.cs @@ -2,14 +2,9 @@ namespace Beutl.NodeTree.Nodes.Transform; -public sealed class TransformNodeEvaluationState +public sealed class TransformNodeEvaluationState(ITransform? created) { - public TransformNodeEvaluationState(ITransform? created) - { - Created = created; - } - - public ITransform? Created { get; set; } + public ITransform? Created { get; set; } = created; public MultiTransform? AddtionalState { get; set; } } diff --git a/src/Beutl.ProjectSystem/NodeTree/OutputSocket.cs b/src/Beutl.ProjectSystem/NodeTree/OutputSocket.cs index ad2e52cad..1561bd9dc 100644 --- a/src/Beutl.ProjectSystem/NodeTree/OutputSocket.cs +++ b/src/Beutl.ProjectSystem/NodeTree/OutputSocket.cs @@ -44,7 +44,7 @@ public void Dispose() public class OutputSocket : Socket, IOutputSocket { - private readonly CoreList _connections = new(); + private readonly CoreList _connections = []; private List? _inputIds = null; // 型が一致していない、ソケットの数 private int _unmatchSockets; diff --git a/src/Beutl.ProjectSystem/NodeTree/SetterPropertyImpl.cs b/src/Beutl.ProjectSystem/NodeTree/SetterPropertyImpl.cs index 163136318..e2d49598f 100644 --- a/src/Beutl.ProjectSystem/NodeTree/SetterPropertyImpl.cs +++ b/src/Beutl.ProjectSystem/NodeTree/SetterPropertyImpl.cs @@ -8,7 +8,7 @@ namespace Beutl.NodeTree; -public sealed class SetterPropertyImpl : IAbstractAnimatableProperty +public sealed class SetterPropertyImpl(Setter setter, Type implementedType) : IAbstractAnimatableProperty { private sealed class AnimationObservable : LightweightObservableBase?> { @@ -46,17 +46,9 @@ private void Setter_Invalidated(object? sender, EventArgs e) } } - public SetterPropertyImpl(Setter setter, Type implementedType) - { - Property = setter.Property; - Setter = setter; - ImplementedType = implementedType; - ObserveAnimation = new AnimationObservable(setter); - } - - public CoreProperty Property { get; } + public CoreProperty Property { get; } = setter.Property; - public Setter Setter { get; } + public Setter Setter { get; } = setter; public IAnimation? Animation { @@ -64,9 +56,9 @@ public IAnimation? Animation set => Setter.Animation = value; } - public IObservable?> ObserveAnimation { get; } + public IObservable?> ObserveAnimation { get; } = new AnimationObservable(setter); - public Type ImplementedType { get; } + public Type ImplementedType { get; } = implementedType; public Type PropertyType => Property.PropertyType; diff --git a/src/Beutl.ProjectSystem/NodeTree/SocketConnectionChangedEventArgs.cs b/src/Beutl.ProjectSystem/NodeTree/SocketConnectionChangedEventArgs.cs index 26dcea37d..e913f2519 100644 --- a/src/Beutl.ProjectSystem/NodeTree/SocketConnectionChangedEventArgs.cs +++ b/src/Beutl.ProjectSystem/NodeTree/SocketConnectionChangedEventArgs.cs @@ -1,14 +1,8 @@ namespace Beutl.NodeTree; -public sealed class SocketConnectionChangedEventArgs +public sealed class SocketConnectionChangedEventArgs(Connection connection, bool isConnected) { - public SocketConnectionChangedEventArgs(Connection connection, bool isConnected) - { - Connection = connection; - IsConnected = isConnected; - } + public Connection Connection { get; } = connection; - public Connection Connection { get; } - - public bool IsConnected { get; } + public bool IsConnected { get; } = isConnected; } diff --git a/src/Beutl.ProjectSystem/Operation/CorePropertyImpl.cs b/src/Beutl.ProjectSystem/Operation/CorePropertyImpl.cs index 98725d7d1..e55a8385c 100644 --- a/src/Beutl.ProjectSystem/Operation/CorePropertyImpl.cs +++ b/src/Beutl.ProjectSystem/Operation/CorePropertyImpl.cs @@ -2,20 +2,14 @@ namespace Beutl.Operation; -internal class CorePropertyImpl : IAbstractProperty +internal class CorePropertyImpl(CoreProperty property, ICoreObject obj) : IAbstractProperty { private Type? _implementedType; private IObservable? _observable; - public CorePropertyImpl(CoreProperty property, ICoreObject obj) - { - Property = property; - Object = obj; - } - - public ICoreObject Object { get; } + public ICoreObject Object { get; } = obj; - public CoreProperty Property { get; } + public CoreProperty Property { get; } = property; public Type ImplementedType => _implementedType ??= Object.GetType(); diff --git a/src/Beutl.ProjectSystem/Operation/SourceStyler.cs b/src/Beutl.ProjectSystem/Operation/SourceStyler.cs index ecf04417c..8c27283ca 100644 --- a/src/Beutl.ProjectSystem/Operation/SourceStyler.cs +++ b/src/Beutl.ProjectSystem/Operation/SourceStyler.cs @@ -9,9 +9,7 @@ namespace Beutl.Operation; public abstract class SourceStyler : StylingOperator, ISourceTransformer { - private readonly ConditionalWeakTable _table = new(); - - internal ConditionalWeakTable Table => _table; + internal ConditionalWeakTable Table { get; } = []; public virtual void Transform(IList value, IClock clock) { @@ -44,7 +42,7 @@ protected virtual void OnPostSelect(Renderable? value) protected virtual IStyleInstance? GetInstance(Renderable value) { Type type = value.GetType(); - if (_table.TryGetValue(value, out IStyleInstance? styleInstance)) + if (Table.TryGetValue(value, out IStyleInstance? styleInstance)) { return styleInstance; } @@ -53,7 +51,7 @@ protected virtual void OnPostSelect(Renderable? value) if (type.IsAssignableTo(Style.TargetType) && value is ICoreObject coreObj) { IStyleInstance instance = Style.Instance(coreObj); - _table.AddOrUpdate(value, instance); + Table.AddOrUpdate(value, instance); return instance; } else @@ -78,8 +76,8 @@ protected override void OnAttachedToHierarchy(in HierarchyAttachmentEventArgs ar protected override void OnDetachedFromHierarchy(in HierarchyAttachmentEventArgs args) { base.OnDetachedFromHierarchy(args); - using var instances = _table.Select(x => x.Value).ToPooledArray(); - _table.Clear(); + using var instances = Table.Select(x => x.Value).ToPooledArray(); + Table.Clear(); foreach (IStyleInstance item in instances) { diff --git a/src/Beutl.ProjectSystem/Operation/StylingOperator.cs b/src/Beutl.ProjectSystem/Operation/StylingOperator.cs index a1fc3b1db..daa6619d5 100644 --- a/src/Beutl.ProjectSystem/Operation/StylingOperator.cs +++ b/src/Beutl.ProjectSystem/Operation/StylingOperator.cs @@ -27,7 +27,7 @@ public interface IStylingSetterPropertyImpl : IAbstractProperty IStyle Style { get; } } -public sealed class StylingSetterPropertyImpl : IAbstractAnimatableProperty, IStylingSetterPropertyImpl +public sealed class StylingSetterPropertyImpl(Setter setter, Style style) : IAbstractAnimatableProperty, IStylingSetterPropertyImpl { private sealed class AnimationObservable : LightweightObservableBase?> { @@ -65,19 +65,11 @@ private void Setter_Invalidated(object? sender, EventArgs e) } } - public StylingSetterPropertyImpl(Setter setter, Style style) - { - Property = setter.Property; - Setter = setter; - Style = style; - ObserveAnimation = new AnimationObservable(setter); - } - - public CoreProperty Property { get; } + public CoreProperty Property { get; } = setter.Property; - public Setter Setter { get; } + public Setter Setter { get; } = setter; - public Style Style { get; } + public Style Style { get; } = style; public IAnimation? Animation { @@ -85,7 +77,7 @@ public IAnimation? Animation set => Setter.Animation = value; } - public IObservable?> ObserveAnimation { get; } + public IObservable?> ObserveAnimation { get; } = new AnimationObservable(setter); public Type PropertyType => Property.PropertyType; @@ -133,7 +125,7 @@ internal static class StylingOperatorPropertyDefinition { internal record struct Definition(PropertyInfo Property, Func Getter, Action Setter); - private static readonly Dictionary s_defines = new(); + private static readonly Dictionary s_defines = []; public static ISetter[] GetSetters(object obj) { diff --git a/src/Beutl.ProjectSystem/ProjectSystem/Elements.cs b/src/Beutl.ProjectSystem/ProjectSystem/Elements.cs index d71da5751..f64ea8f31 100644 --- a/src/Beutl.ProjectSystem/ProjectSystem/Elements.cs +++ b/src/Beutl.ProjectSystem/ProjectSystem/Elements.cs @@ -1,12 +1,5 @@ - -using Beutl.Collections; +using Beutl.Collections; namespace Beutl.ProjectSystem; -public sealed class Elements : HierarchicalList -{ - public Elements(IModifiableHierarchical parent) - : base(parent) - { - } -} +public sealed class Elements(IModifiableHierarchical parent) : HierarchicalList(parent); diff --git a/src/Beutl.ProjectSystem/ProjectSystem/Scene.cs b/src/Beutl.ProjectSystem/ProjectSystem/Scene.cs index 38ed0eead..93447a60f 100644 --- a/src/Beutl.ProjectSystem/ProjectSystem/Scene.cs +++ b/src/Beutl.ProjectSystem/ProjectSystem/Scene.cs @@ -51,11 +51,8 @@ public class Scene : ProjectItem public static readonly CoreProperty RendererProperty; public static readonly CoreProperty ComposerProperty; public static readonly CoreProperty CacheOptionsProperty; - private readonly List _includeElements = new() - { - "**/*.belm" - }; - private readonly List _excludeElements = new(); + private readonly List _includeElements = ["**/*.belm"]; + private readonly List _excludeElements = []; private readonly Elements _children; private TimeSpan _duration = TimeSpan.FromMinutes(5); private TimeSpan _currentFrame; @@ -747,36 +744,24 @@ bool IsOverlapping(TimeRange timeRange, int zindex) return (element.Range, NearestLayerNumber(element)); } - private sealed class AddCommand : IRecordableCommand + private sealed class AddCommand(Scene scene, Element element, ElementOverlapHandling overlapHandling) : IRecordableCommand { - private readonly Scene _scene; - private readonly Element _element; - private readonly ElementOverlapHandling _overlapHandling; - private readonly TimeSpan _oldSceneDuration; - private readonly bool _adjustSceneDuration; + private readonly TimeSpan _oldSceneDuration = scene.Duration; + private readonly bool _adjustSceneDuration = GlobalConfiguration.Instance.EditorConfig.AutoAdjustSceneDuration; private int _zIndex; private TimeRange _range; - public AddCommand(Scene scene, Element element, ElementOverlapHandling overlapHandling) - { - _scene = scene; - _element = element; - _overlapHandling = overlapHandling; - _oldSceneDuration = scene.Duration; - _adjustSceneDuration = GlobalConfiguration.Instance.EditorConfig.AutoAdjustSceneDuration; - } - public void Do() { - (_range, _zIndex) = _scene.GetCorrectPosition(_element, _overlapHandling); - _element.Start = _range.Start; - _element.Length = _range.Duration; - _element.ZIndex = _zIndex; - _scene.Children.Add(_element); + (_range, _zIndex) = scene.GetCorrectPosition(element, overlapHandling); + element.Start = _range.Start; + element.Length = _range.Duration; + element.ZIndex = _zIndex; + scene.Children.Add(element); - if (_adjustSceneDuration && _scene.Duration < _range.End) + if (_adjustSceneDuration && scene.Duration < _range.End) { - _scene.Duration = _range.End; + scene.Duration = _range.End; } } @@ -787,32 +772,24 @@ public void Redo() public void Undo() { - _scene.Children.Remove(_element); - _element.ZIndex = -1; + scene.Children.Remove(element); + element.ZIndex = -1; if (_adjustSceneDuration) { - _scene.Duration = _oldSceneDuration; + scene.Duration = _oldSceneDuration; } } } - private sealed class RemoveCommand : IRecordableCommand + private sealed class RemoveCommand(Scene scene, Element element) : IRecordableCommand { - private readonly Scene _scene; - private readonly Element _element; private int _zIndex; - public RemoveCommand(Scene scene, Element element) - { - _scene = scene; - _element = element; - } - public void Do() { - _zIndex = _element.ZIndex; - _scene.Children.Remove(_element); - _element.ZIndex = -1; + _zIndex = element.ZIndex; + scene.Children.Remove(element); + element.ZIndex = -1; } public void Redo() @@ -822,55 +799,34 @@ public void Redo() public void Undo() { - _element.ZIndex = _zIndex; - _scene.Children.Add(_element); + element.ZIndex = _zIndex; + scene.Children.Add(element); } } - private sealed class MoveCommand : IRecordableCommand + private sealed class MoveCommand( + int zIndex, + Element element, + TimeSpan newStart, TimeSpan oldStart, + TimeSpan newLength, TimeSpan oldLength, + Scene scene) : IRecordableCommand { - private readonly Scene _scene; - private readonly Element _element; - private readonly int _zIndex; - private readonly int _oldZIndex; - private readonly TimeSpan _newStart; - private readonly TimeSpan _oldStart; - private readonly TimeSpan _newLength; - private readonly TimeSpan _oldLength; - private readonly TimeSpan _oldSceneDuration; - private readonly bool _adjustSceneDuration; - - public MoveCommand( - int zIndex, - Element element, - TimeSpan newStart, TimeSpan oldStart, - TimeSpan newLength, TimeSpan oldLength, - Scene scene) - { - _element = element; - _zIndex = zIndex; - _oldZIndex = element.ZIndex; - _newStart = newStart; - _oldStart = oldStart; - _newLength = newLength; - _oldLength = oldLength; - _scene = scene; - _oldSceneDuration = scene.Duration; - _adjustSceneDuration = GlobalConfiguration.Instance.EditorConfig.AutoAdjustSceneDuration; - } + private readonly int _oldZIndex = element.ZIndex; + private readonly TimeSpan _oldSceneDuration = scene.Duration; + private readonly bool _adjustSceneDuration = GlobalConfiguration.Instance.EditorConfig.AutoAdjustSceneDuration; public void Do() { - TimeSpan newEnd = _newStart + _newLength; - (Element? before, Element? after, Element? cover) = _element.GetBeforeAndAfterAndCover(_zIndex, _newStart, newEnd); + TimeSpan newEnd = newStart + newLength; + (Element? before, Element? after, Element? cover) = element.GetBeforeAndAfterAndCover(zIndex, newStart, newEnd); - if (before != null && before.Range.End >= _newStart) + if (before != null && before.Range.End >= newStart) { - if ((after != null && (after.Start - before.Range.End) >= _newLength) || after == null) + if ((after != null && (after.Start - before.Range.End) >= newLength) || after == null) { - _element.Start = before.Range.End; - _element.Length = _newLength; - _element.ZIndex = _zIndex; + element.Start = before.Range.End; + element.Length = newLength; + element.ZIndex = zIndex; } else { @@ -879,12 +835,12 @@ public void Do() } else if (after != null && after.Start < newEnd) { - TimeSpan ns = after.Start - _newLength; - if (((before != null && (after.Start - before.Range.End) >= _newLength) || before == null) && ns >= TimeSpan.Zero) + TimeSpan ns = after.Start - newLength; + if (((before != null && (after.Start - before.Range.End) >= newLength) || before == null) && ns >= TimeSpan.Zero) { - _element.Start = ns; - _element.Length = _newLength; - _element.ZIndex = _zIndex; + element.Start = ns; + element.Length = newLength; + element.ZIndex = zIndex; } else { @@ -897,15 +853,15 @@ public void Do() } else { - _element.Start = _newStart; - _element.Length = _newLength; - _element.ZIndex = _zIndex; + element.Start = newStart; + element.Length = newLength; + element.ZIndex = zIndex; } - TimeRange range = _element.Range; - if (_adjustSceneDuration && _scene.Duration < range.End) + TimeRange range = element.Range; + if (_adjustSceneDuration && scene.Duration < range.End) { - _scene.Duration = range.End; + scene.Duration = range.End; } } @@ -916,12 +872,12 @@ public void Redo() public void Undo() { - _element.ZIndex = _oldZIndex; - _element.Start = _oldStart; - _element.Length = _oldLength; + element.ZIndex = _oldZIndex; + element.Start = oldStart; + element.Length = oldLength; if (_adjustSceneDuration) { - _scene.Duration = _oldSceneDuration; + scene.Duration = _oldSceneDuration; } } } diff --git a/src/Beutl.ProjectSystem/SceneComposer.cs b/src/Beutl.ProjectSystem/SceneComposer.cs index 33aa9f5ad..0b3926574 100644 --- a/src/Beutl.ProjectSystem/SceneComposer.cs +++ b/src/Beutl.ProjectSystem/SceneComposer.cs @@ -10,19 +10,13 @@ namespace Beutl; -public sealed class SceneComposer : Composer +public sealed class SceneComposer(Scene scene) : Composer { - private readonly Scene _scene; - private readonly List _entered = new(); - private readonly List _exited = new(); - private readonly List _current = new(); + private readonly List _entered = []; + private readonly List _exited = []; + private readonly List _current = []; private TimeRange _lastTime = new(TimeSpan.MinValue, default); - public SceneComposer(Scene scene) - { - _scene = scene; - } - protected override void ComposeCore(Audio.Audio audio) { base.ComposeCore(audio); @@ -47,7 +41,7 @@ protected override void ComposeCore(Audio.Audio audio) foreach (Element element in elements) { - using (PooledList list = element.Evaluate(EvaluationTarget.Audio, clock, _scene.Renderer)) + using (PooledList list = element.Evaluate(EvaluationTarget.Audio, clock, scene.Renderer)) { foreach (Renderable item in list.Span) { @@ -87,7 +81,7 @@ private void SortLayers(TimeRange timeSpan, out TimeRange enterAffectsRange) TimeSpan enterStart = TimeSpan.MaxValue; TimeSpan enterEnd = TimeSpan.Zero; - foreach (Element? item in _scene.Children) + foreach (Element? item in scene.Children) { bool recent = InRange(item, _lastTime); bool current = InRange(item, timeSpan); diff --git a/src/Beutl.ProjectSystem/SceneGraphicsEvaluator.cs b/src/Beutl.ProjectSystem/SceneGraphicsEvaluator.cs index 775faded1..5f64e0b9c 100644 --- a/src/Beutl.ProjectSystem/SceneGraphicsEvaluator.cs +++ b/src/Beutl.ProjectSystem/SceneGraphicsEvaluator.cs @@ -10,26 +10,18 @@ namespace Beutl; -internal sealed class SceneGraphicsEvaluator : IDisposable +internal sealed class SceneGraphicsEvaluator(Scene scene, IRenderer renderer) : IDisposable { - private readonly Scene _scene; - private readonly IRenderer _renderer; - private readonly List _entered = new(); - private readonly List _exited = new(); - private readonly List _current = new(); + private readonly List _entered = []; + private readonly List _exited = []; + private readonly List _current = []; private TimeSpan _lastTime = TimeSpan.MinValue; - public SceneGraphicsEvaluator(Scene scene, IRenderer renderer) - { - _scene = scene; - _renderer = renderer; - } - public List CurrentElements => _current; public void Evaluate() { - IClock clock = _renderer.Clock; + IClock clock = renderer.Clock; TimeSpan timeSpan = clock.CurrentTime; SortLayers(timeSpan, out _); Span entered = CollectionsMarshal.AsSpan(_entered); @@ -38,8 +30,8 @@ public void Evaluate() foreach (Element item in exited) { ExitSourceOperators(item); - RenderLayer layer = _renderer.RenderScene[item.ZIndex]; - layer.ClearAllNodeCache(_renderer.GetCacheContext()); + RenderLayer layer = renderer.RenderScene[item.ZIndex]; + layer.ClearAllNodeCache(renderer.GetCacheContext()); } foreach (Element item in entered) @@ -50,14 +42,14 @@ public void Evaluate() for (int i = 0; i < _current.Count; i++) { Element element = _current[i]; - using (PooledList list = element.Evaluate(EvaluationTarget.Graphics, clock, _renderer)) + using (PooledList list = element.Evaluate(EvaluationTarget.Graphics, clock, renderer)) { foreach (Renderable item in list.Span) { if (item is Drawable drawable) { int actualIndex = (drawable as DrawableDecorator)?.OriginalZIndex ?? item.ZIndex; - _renderer.RenderScene[actualIndex].Add(drawable); + renderer.RenderScene[actualIndex].Add(drawable); } } } @@ -91,7 +83,7 @@ private void SortLayers(TimeSpan timeSpan, out TimeRange enterAffectsRange) TimeSpan enterStart = TimeSpan.MaxValue; TimeSpan enterEnd = TimeSpan.Zero; - foreach (Element? item in _scene.Children) + foreach (Element? item in scene.Children) { bool recent = InRange(item, _lastTime); bool current = InRange(item, timeSpan); diff --git a/src/Beutl.Threading/OperationQueue.cs b/src/Beutl.Threading/OperationQueue.cs index f41b72b2e..db49ba983 100644 --- a/src/Beutl.Threading/OperationQueue.cs +++ b/src/Beutl.Threading/OperationQueue.cs @@ -5,12 +5,12 @@ namespace Beutl.Threading; internal sealed class OperationQueue { private readonly object _lock = new(); - private readonly Queue[] _queuedOperations = new Queue[] - { + private readonly Queue[] _queuedOperations = + [ new Queue(), new Queue(), new Queue() - }; + ]; public void Enqueue(DispatcherOperation operation) { diff --git a/src/Beutl.Threading/TimerQueue.cs b/src/Beutl.Threading/TimerQueue.cs index 6ec67e6eb..148c53967 100644 --- a/src/Beutl.Threading/TimerQueue.cs +++ b/src/Beutl.Threading/TimerQueue.cs @@ -5,7 +5,7 @@ namespace Beutl.Threading; internal sealed class TimerQueue { private readonly object _lock = new(); - private readonly SortedDictionary> _operations = new(); + private readonly SortedDictionary> _operations = []; public DateTime? Next { @@ -30,7 +30,7 @@ public void Enqueue(DateTime timestamp, DispatchPriority priority, Action operat } else { - _operations.Add(timestamp, new List { new(operation, priority) }); + _operations.Add(timestamp, [new(operation, priority)]); } } } diff --git a/src/Beutl.Threading/YieldTask.cs b/src/Beutl.Threading/YieldTask.cs index 76b625fcc..c0c0300dc 100644 --- a/src/Beutl.Threading/YieldTask.cs +++ b/src/Beutl.Threading/YieldTask.cs @@ -2,30 +2,16 @@ namespace Beutl.Threading; -public readonly struct YieldTask +public readonly struct YieldTask(DispatchPriority priority) { - private readonly DispatchPriority _priority; - - public YieldTask(DispatchPriority priority) - { - _priority = priority; - } - public YieldTaskAwaiter GetAwaiter() { - return new YieldTaskAwaiter(_priority); + return new YieldTaskAwaiter(priority); } } -public readonly struct YieldTaskAwaiter : INotifyCompletion +public readonly struct YieldTaskAwaiter(DispatchPriority priority) : INotifyCompletion { - private readonly DispatchPriority _priority; - - public YieldTaskAwaiter(DispatchPriority priority) - { - _priority = priority; - } - public bool IsCompleted { get @@ -35,7 +21,7 @@ public bool IsCompleted throw new DispatcherException("Awaiting Dispatcher.Yield outside of QueueSynchronizationContext"); } - return !context.HasQueuedTasks(_priority); + return !context.HasQueuedTasks(priority); } } @@ -46,7 +32,7 @@ public void OnCompleted(Action continuation) throw new DispatcherException("Awaiting Dispatcher.Yield outside of QueueSynchronizationContext"); } - context.Post(_priority, continuation); + context.Post(priority, continuation); } public void GetResult() diff --git a/src/Beutl.Utilities/PooledArrayBufferWriter.cs b/src/Beutl.Utilities/PooledArrayBufferWriter.cs index 53b4ba635..808e74fb8 100644 --- a/src/Beutl.Utilities/PooledArrayBufferWriter.cs +++ b/src/Beutl.Utilities/PooledArrayBufferWriter.cs @@ -64,7 +64,9 @@ public ReadOnlySpan WrittenSpan private void Verify() { if (IsDisposed) + { throw new ObjectDisposedException(nameof(PooledArrayBufferWriter)); + } } public void Clear() @@ -174,7 +176,7 @@ public void Dispose() if (!IsDisposed) { _pool.Return(_buffer, RuntimeHelpers.IsReferenceOrContainsReferences()); - _buffer = Array.Empty(); + _buffer = []; IsDisposed = true; GC.SuppressFinalize(this); diff --git a/src/Beutl.Utilities/StringFormats.cs b/src/Beutl.Utilities/StringFormats.cs index 19d04e23e..3ce048f09 100644 --- a/src/Beutl.Utilities/StringFormats.cs +++ b/src/Beutl.Utilities/StringFormats.cs @@ -11,7 +11,7 @@ public static class StringFormats // https://teratail.com/questions/136799#reply-207332 public static string ToHumanReadableSize(double size, int scale = 0, int standard = 1024) { - string[] unit = new[] { "B", "KB", "MB", "GB" }; + string[] unit = ["B", "KB", "MB", "GB"]; if (scale == unit.Length - 1 || size <= standard) { return $"{size:F} {unit[scale]}"; } return ToHumanReadableSize(size / standard, scale + 1, standard); } diff --git a/src/Beutl.Utilities/WeakEvent.cs b/src/Beutl.Utilities/WeakEvent.cs index a5d27f0bd..a69dadd2d 100644 --- a/src/Beutl.Utilities/WeakEvent.cs +++ b/src/Beutl.Utilities/WeakEvent.cs @@ -7,7 +7,7 @@ public class WeakEvent : WeakEvent where TEventArgs : Event { private readonly Func, Action> _subscribe; - readonly ConditionalWeakTable _subscriptions = new(); + readonly ConditionalWeakTable _subscriptions = []; internal WeakEvent( Action> subscribe, diff --git a/src/Beutl/AppHelpers.cs b/src/Beutl/AppHelpers.cs index 902d994e5..14aeebcc0 100644 --- a/src/Beutl/AppHelpers.cs +++ b/src/Beutl/AppHelpers.cs @@ -6,8 +6,8 @@ internal static class AppHelpers { internal static Color[] GetPaletteColors() { - return new[] - { + return + [ Colors.AliceBlue, Colors.AntiqueWhite, Colors.Aqua, @@ -149,6 +149,6 @@ internal static Color[] GetPaletteColors() Colors.WhiteSmoke, Colors.Yellow, Colors.YellowGreen, - }; + ]; } } diff --git a/src/Beutl/Beutl.csproj b/src/Beutl/Beutl.csproj index ba13fdb63..442f918ee 100644 --- a/src/Beutl/Beutl.csproj +++ b/src/Beutl/Beutl.csproj @@ -89,6 +89,11 @@ True VectorEditorViewModels.tt + + True + True + GraphEditorViewViewModelFactory.Impl.tt + diff --git a/src/Beutl/Helpers/BindingHelper.cs b/src/Beutl/Helpers/BindingHelper.cs index 3a7014108..20110f4eb 100644 --- a/src/Beutl/Helpers/BindingHelper.cs +++ b/src/Beutl/Helpers/BindingHelper.cs @@ -14,18 +14,10 @@ public static IBinding ToPropertyBinding(this IReactiveProperty property, return new BindingAdaptor(property, bindingMode); } - private class BindingAdaptor : IBinding + private class BindingAdaptor(IReactiveProperty property, BindingMode bindingMode) : IBinding { - private readonly IReactiveProperty _property; - private readonly RxPropertySubject _source; - private readonly BindingMode _bindingMode; - - public BindingAdaptor(IReactiveProperty property, BindingMode bindingMode) - { - _property = property; - _source = new RxPropertySubject(property); - _bindingMode = bindingMode; - } + private readonly RxPropertySubject _source = new(property); + private readonly BindingMode _bindingMode = bindingMode; public InstancedBinding? Initiate( AvaloniaObject target, @@ -40,22 +32,15 @@ public BindingAdaptor(IReactiveProperty property, BindingMode bindingMode) return bindingMode switch { BindingMode.TwoWay => InstancedBinding.TwoWay(_source, _source), - BindingMode.OneTime => InstancedBinding.OneTime(_property.Value!), + BindingMode.OneTime => InstancedBinding.OneTime(property.Value!), BindingMode.OneWayToSource => InstancedBinding.OneWayToSource(_source), _ => InstancedBinding.OneWay(_source), }; } } - private sealed class RxPropertySubject : ISubject + private sealed class RxPropertySubject(IReactiveProperty source) : ISubject { - private readonly IReactiveProperty _source; - - public RxPropertySubject(IReactiveProperty source) - { - _source = source; - } - public void OnCompleted() { } @@ -68,17 +53,17 @@ public void OnNext(object? value) { if (value is T t) { - _source.Value = t; + source.Value = t; } else { - _source.Value = default!; + source.Value = default!; } } public IDisposable Subscribe(IObserver observer) { - return _source.Subscribe( + return source.Subscribe( v => observer.OnNext(v), observer.OnError, observer.OnCompleted); diff --git a/src/Beutl/Helpers/ColorGenerator.cs b/src/Beutl/Helpers/ColorGenerator.cs index 3485775c8..92492cad9 100644 --- a/src/Beutl/Helpers/ColorGenerator.cs +++ b/src/Beutl/Helpers/ColorGenerator.cs @@ -10,7 +10,7 @@ namespace Beutl.Helpers; public static class ColorGenerator { - private static readonly Dictionary s_cache = new(); + private static readonly Dictionary s_cache = []; // https://qiita.com/pira/items/dd4057ef499154968f69 public static Media.Color GenerateColor(string str) diff --git a/src/Beutl/Pages/EditPage.axaml.cs b/src/Beutl/Pages/EditPage.axaml.cs index 731bd4e37..dcc4a9608 100644 --- a/src/Beutl/Pages/EditPage.axaml.cs +++ b/src/Beutl/Pages/EditPage.axaml.cs @@ -35,7 +35,7 @@ public sealed partial class EditPage : UserControl private static readonly Binding s_isSelectedBinding = new("IsSelected.Value", BindingMode.TwoWay); private static readonly Binding s_contentBinding = new("Value", BindingMode.OneWay); private static readonly ILogger s_logger = Log.ForContext(); - private readonly AvaloniaList _tabItems = new(); + private readonly AvaloniaList _tabItems = []; private IDisposable? _disposable0; public EditPage() diff --git a/src/Beutl/Pages/ExtensionsPage.axaml.cs b/src/Beutl/Pages/ExtensionsPage.axaml.cs index bc8546e74..2a590d50e 100644 --- a/src/Beutl/Pages/ExtensionsPage.axaml.cs +++ b/src/Beutl/Pages/ExtensionsPage.axaml.cs @@ -66,8 +66,8 @@ private void OpenSettings_Click(object? sender, RoutedEventArgs e) private static List GetItems() { - return new List() - { + return + [ new NavigationViewItem() { Content = "Home", @@ -95,7 +95,7 @@ private static List GetItems() Symbol = Symbol.Code } } - }; + ]; } private void Nav_BackRequested(object? sender, NavigationViewBackRequestedEventArgs e) diff --git a/src/Beutl/Pages/OutputPage.axaml.cs b/src/Beutl/Pages/OutputPage.axaml.cs index dcedefe86..133dd7f84 100644 --- a/src/Beutl/Pages/OutputPage.axaml.cs +++ b/src/Beutl/Pages/OutputPage.axaml.cs @@ -65,7 +65,7 @@ private void OnRemoveClick(object? sender, RoutedEventArgs e) private sealed class _DataTemplate : IDataTemplate { - private readonly Dictionary _contextToViewType = new(); + private readonly Dictionary _contextToViewType = []; public Control? Build(object? param) { diff --git a/src/Beutl/Pages/SettingsPage.axaml.cs b/src/Beutl/Pages/SettingsPage.axaml.cs index 205126873..f7a9d3bf0 100644 --- a/src/Beutl/Pages/SettingsPage.axaml.cs +++ b/src/Beutl/Pages/SettingsPage.axaml.cs @@ -67,8 +67,8 @@ private void OnNavigateRequested(object obj) private static List GetItems() { - return new List() - { + return + [ new NavigationViewItem() { Content = Strings.Account, @@ -132,7 +132,7 @@ private static List GetItems() Symbol = FluentIcons.Common.Symbol.Info } } - }; + ]; } private void Nav_BackRequested(object? sender, NavigationViewBackRequestedEventArgs e) diff --git a/src/Beutl/Services/ObjectSearcher.cs b/src/Beutl/Services/ObjectSearcher.cs index 3a181bac9..8ef84df5a 100644 --- a/src/Beutl/Services/ObjectSearcher.cs +++ b/src/Beutl/Services/ObjectSearcher.cs @@ -4,7 +4,7 @@ namespace Beutl.Services; public class ObjectSearcher { - private readonly HashSet _hashSet = new(); + private readonly HashSet _hashSet = []; private readonly Stack? _stack; private readonly Func, object, bool> _predicate; private readonly object _obj; diff --git a/src/Beutl/Services/OutputService.cs b/src/Beutl/Services/OutputService.cs index e2224e8ea..625e6dde0 100644 --- a/src/Beutl/Services/OutputService.cs +++ b/src/Beutl/Services/OutputService.cs @@ -94,18 +94,11 @@ public static JsonNode ToJson(OutputQueueItem item) public sealed class OutputService { - private readonly CoreList _items; + private readonly CoreList _items = []; private readonly ReactivePropertySlim _selectedItem = new(); - private readonly string _filePath; + private readonly string _filePath = Path.Combine(BeutlEnvironment.GetHomeDirectoryPath(), "outputlist.json"); private bool _isRestored; - public OutputService() - { - _items = new CoreList(); - - _filePath = Path.Combine(BeutlEnvironment.GetHomeDirectoryPath(), "outputlist.json"); - } - public static OutputService Current { get; } = new(); public ICoreList Items => _items; diff --git a/src/Beutl/Services/PropertyEditorService.cs b/src/Beutl/Services/PropertyEditorService.cs index 82980a773..193b4b808 100644 --- a/src/Beutl/Services/PropertyEditorService.cs +++ b/src/Beutl/Services/PropertyEditorService.cs @@ -146,10 +146,10 @@ private record struct ListItemEditor(Func C { typeof(ITransform), new(_ => new TransformListItemEditor(), s => new TransformEditorViewModel(s.ToTyped())) } }; - private static readonly Dictionary s_editorsOverride = new() - { + private static readonly Dictionary s_editorsOverride = + [ // プロパティのIdから、プロパティエディタを作成 - }; + ]; // IList private static readonly FrozenDictionary s_editors = new KeyValuePair[] diff --git a/src/Beutl/Services/StartupTasks/AfterLoadingExtensionsTask.cs b/src/Beutl/Services/StartupTasks/AfterLoadingExtensionsTask.cs index 4e68017fd..e774f6ac7 100644 --- a/src/Beutl/Services/StartupTasks/AfterLoadingExtensionsTask.cs +++ b/src/Beutl/Services/StartupTasks/AfterLoadingExtensionsTask.cs @@ -19,7 +19,7 @@ public AfterLoadingExtensionsTask(Startup startup) LoadSideloadExtensionTask t3 = _startup.GetTask(); await Task.WhenAll(t1.Task, t2.Task, t3.Task); - (LocalPackage, Exception)[] failures = t1.Failures.Concat(t2.Failures).Concat(t3.Failures).ToArray(); + (LocalPackage, Exception)[] failures = [.. t1.Failures, .. t2.Failures, .. t3.Failures]; if (failures.Length > 0) { NotificationService.ShowError( diff --git a/src/Beutl/Services/StartupTasks/LoadInstalledExtensionTask.cs b/src/Beutl/Services/StartupTasks/LoadInstalledExtensionTask.cs index 61105fdaa..4b1bd683b 100644 --- a/src/Beutl/Services/StartupTasks/LoadInstalledExtensionTask.cs +++ b/src/Beutl/Services/StartupTasks/LoadInstalledExtensionTask.cs @@ -55,7 +55,7 @@ public LoadInstalledExtensionTask(PackageManager manager) public override Task Task { get; } - public ConcurrentBag<(LocalPackage, Exception)> Failures { get; } = new(); + public ConcurrentBag<(LocalPackage, Exception)> Failures { get; } = []; // 最後に実行したとき、例外が発生して終了した場合、 // 制限モード (拡張機能を読み込まない) で起動するかを尋ねる。 diff --git a/src/Beutl/Services/StartupTasks/LoadPrimitiveExtensionTask.cs b/src/Beutl/Services/StartupTasks/LoadPrimitiveExtensionTask.cs index 7fd8ce665..62121ef82 100644 --- a/src/Beutl/Services/StartupTasks/LoadPrimitiveExtensionTask.cs +++ b/src/Beutl/Services/StartupTasks/LoadPrimitiveExtensionTask.cs @@ -7,7 +7,7 @@ public sealed class LoadPrimitiveExtensionTask : StartupTask { private readonly PackageManager _manager; public static readonly Extension[] PrimitiveExtensions = - { + [ EditPageExtension.Instance, ExtensionsPageExtension.Instance, OutputPageExtension.Instance, @@ -24,7 +24,7 @@ public sealed class LoadPrimitiveExtensionTask : StartupTask GraphEditorTabExtension.Instance, SceneSettingsTabExtension.Instance, WaveReaderExtension.Instance, - }; + ]; public LoadPrimitiveExtensionTask(PackageManager manager) { @@ -68,11 +68,7 @@ public LoadPrimitiveExtensionTask(PackageManager manager) decoding.Load(); encoding.Load(); - provider.AddExtensions(pkg.LocalId, new Extension[] - { - decoding, - encoding - }); + provider.AddExtensions(pkg.LocalId, [decoding, encoding]); } catch (Exception ex) { @@ -88,5 +84,5 @@ public LoadPrimitiveExtensionTask(PackageManager manager) public override Task Task { get; } - public List<(LocalPackage, Exception)> Failures { get; } = new(); + public List<(LocalPackage, Exception)> Failures { get; } = []; } diff --git a/src/Beutl/Services/StartupTasks/LoadSideloadExtensionTask.cs b/src/Beutl/Services/StartupTasks/LoadSideloadExtensionTask.cs index d9b86a8cb..b3b3b341d 100644 --- a/src/Beutl/Services/StartupTasks/LoadSideloadExtensionTask.cs +++ b/src/Beutl/Services/StartupTasks/LoadSideloadExtensionTask.cs @@ -58,7 +58,7 @@ public LoadSideloadExtensionTask(PackageManager manager) public override Task Task { get; } - public ConcurrentBag<(LocalPackage, Exception)> Failures { get; } = new(); + public ConcurrentBag<(LocalPackage, Exception)> Failures { get; } = []; private static async ValueTask ShowDialog(IReadOnlyList sideloads) { diff --git a/src/Beutl/Services/StartupTasks/Startup.cs b/src/Beutl/Services/StartupTasks/Startup.cs index 0b1092204..8620d2479 100644 --- a/src/Beutl/Services/StartupTasks/Startup.cs +++ b/src/Beutl/Services/StartupTasks/Startup.cs @@ -6,7 +6,7 @@ namespace Beutl.Services.StartupTasks; public sealed class Startup { - private readonly Dictionary> _tasks = new(); + private readonly Dictionary> _tasks = []; private readonly BeutlApiApplication _apiApp; public Startup(BeutlApiApplication apiApp) diff --git a/src/Beutl/Services/Telemetry.cs b/src/Beutl/Services/Telemetry.cs index d67aeba64..c6bc70f2c 100644 --- a/src/Beutl/Services/Telemetry.cs +++ b/src/Beutl/Services/Telemetry.cs @@ -57,7 +57,7 @@ static Telemetry() { return Sdk.CreateTracerProviderBuilder() .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("Beutl")) - .AddSource(list.ToArray()) + .AddSource([.. list]) //.AddZipkinExporter() .AddAzureMonitorTraceExporter(b => b.ConnectionString = $"InstrumentationKey={Instrumentation}") .Build(); diff --git a/src/Beutl/ViewModels/Dialogs/SelectAssetViewModel.cs b/src/Beutl/ViewModels/Dialogs/SelectAssetViewModel.cs index 24e1fd684..53f342405 100644 --- a/src/Beutl/ViewModels/Dialogs/SelectAssetViewModel.cs +++ b/src/Beutl/ViewModels/Dialogs/SelectAssetViewModel.cs @@ -71,7 +71,7 @@ public SelectAssetViewModel(AuthorizedUser user, Func contentTypeF Refresh.Execute(); } - public AvaloniaList Items { get; } = new(); + public AvaloniaList Items { get; } = []; public ReactivePropertySlim SelectedItem { get; } = new(); diff --git a/src/Beutl/ViewModels/Dialogs/SelectImageAssetViewModel.cs b/src/Beutl/ViewModels/Dialogs/SelectImageAssetViewModel.cs index 4370993c8..42bcfd975 100644 --- a/src/Beutl/ViewModels/Dialogs/SelectImageAssetViewModel.cs +++ b/src/Beutl/ViewModels/Dialogs/SelectImageAssetViewModel.cs @@ -66,7 +66,7 @@ public SelectImageAssetViewModel(AuthorizedUser user) Refresh.Execute(); } - public AvaloniaList Items { get; } = new(); + public AvaloniaList Items { get; } = []; public ReactivePropertySlim SelectedItem { get; } = new(); diff --git a/src/Beutl/ViewModels/Dialogs/SelectLibraryItemDialogViewModel.cs b/src/Beutl/ViewModels/Dialogs/SelectLibraryItemDialogViewModel.cs index af7d47a1e..210d5a1d6 100644 --- a/src/Beutl/ViewModels/Dialogs/SelectLibraryItemDialogViewModel.cs +++ b/src/Beutl/ViewModels/Dialogs/SelectLibraryItemDialogViewModel.cs @@ -39,9 +39,9 @@ public SelectLibraryItemDialogViewModel(string format, Type baseType, string tit public string Title { get; } - public ReactiveCollection Items { get; } = new(); + public ReactiveCollection Items { get; } = []; - public ReactiveCollection AllItems { get; } = new(); + public ReactiveCollection AllItems { get; } = []; public ReactiveProperty IsBusy { get; } = new(); @@ -64,7 +64,7 @@ public void LoadAllItems() .Where(x => !x.IsAbstract && x.IsPublic && x.IsAssignableTo(itemType) - && (itemType.GetConstructor(Array.Empty()) != null + && (itemType.GetConstructor([]) != null || itemType.GetConstructors().Length == 0)) .ToArray(); diff --git a/src/Beutl/ViewModels/EditViewModel.cs b/src/Beutl/ViewModels/EditViewModel.cs index c33d0fb6d..a02c17c5c 100644 --- a/src/Beutl/ViewModels/EditViewModel.cs +++ b/src/Beutl/ViewModels/EditViewModel.cs @@ -27,14 +27,9 @@ namespace Beutl.ViewModels; -public sealed class ToolTabViewModel : IDisposable +public sealed class ToolTabViewModel(IToolContext context) : IDisposable { - public ToolTabViewModel(IToolContext context) - { - Context = context; - } - - public IToolContext Context { get; private set; } + public IToolContext Context { get; private set; } = context; public int Order { get; set; } = -1; @@ -48,7 +43,7 @@ public void Dispose() public sealed class EditViewModel : IEditorContext, ITimelineOptionsProvider, ISupportCloseAnimation { private static readonly ILogger s_logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; // Telemetryで使う private readonly string _sceneId; @@ -625,8 +620,8 @@ private static bool MatchFileVideoOnly(string filePath) private static bool MatchFileImage(string filePath) { - string[] extensions = new string[] - { + string[] extensions = + [ "*.bmp", "*.gif", "*.ico", @@ -641,7 +636,7 @@ private static bool MatchFileImage(string filePath) "*.dng", "*.heif", "*.avif", - }; + ]; return MatchFileExtensions(filePath, extensions); } @@ -685,8 +680,8 @@ static KeyBinding KeyBinding(Key key, KeyModifiers modifiers, ICommand command) }; } - return new List - { + return + [ // PlayPause: Space KeyBinding(Key.Space, KeyModifiers.None, Player.PlayPause), // Next: Right @@ -697,28 +692,19 @@ static KeyBinding KeyBinding(Key key, KeyModifiers modifiers, ICommand command) KeyBinding(Key.Home, KeyModifiers.None, Player.Start), // End: End KeyBinding(Key.End, KeyModifiers.None, Player.End), - }; + ]; } - private sealed class KnownCommandsImpl : IKnownEditorCommands + private sealed class KnownCommandsImpl(Scene scene, EditViewModel viewModel) : IKnownEditorCommands { - private readonly Scene _scene; - private readonly EditViewModel _viewModel; - - public KnownCommandsImpl(Scene scene, EditViewModel viewModel) - { - _scene = scene; - _viewModel = viewModel; - } - public ValueTask OnSave() { - _scene.Save(_scene.FileName); - foreach (Element element in _scene.Children) + scene.Save(scene.FileName); + foreach (Element element in scene.Children) { element.Save(element.FileName); } - _viewModel.SaveState(); + viewModel.SaveState(); return ValueTask.FromResult(true); } diff --git a/src/Beutl/ViewModels/Editors/AlignmentXEditorViewModel.cs b/src/Beutl/ViewModels/Editors/AlignmentXEditorViewModel.cs index 6fb79757e..3371db96f 100644 --- a/src/Beutl/ViewModels/Editors/AlignmentXEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/AlignmentXEditorViewModel.cs @@ -5,13 +5,8 @@ namespace Beutl.ViewModels.Editors; -public sealed class AlignmentXEditorViewModel : ValueEditorViewModel +public sealed class AlignmentXEditorViewModel(IAbstractProperty property) : ValueEditorViewModel(property) { - public AlignmentXEditorViewModel(IAbstractProperty property) - : base(property) - { - } - public override void Accept(IPropertyEditorContextVisitor visitor) { base.Accept(visitor); diff --git a/src/Beutl/ViewModels/Editors/AlignmentYEditorViewModel.cs b/src/Beutl/ViewModels/Editors/AlignmentYEditorViewModel.cs index 9fda7a8b8..32dff1e32 100644 --- a/src/Beutl/ViewModels/Editors/AlignmentYEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/AlignmentYEditorViewModel.cs @@ -5,13 +5,8 @@ namespace Beutl.ViewModels.Editors; -public sealed class AlignmentYEditorViewModel : ValueEditorViewModel +public sealed class AlignmentYEditorViewModel(IAbstractProperty property) : ValueEditorViewModel(property) { - public AlignmentYEditorViewModel(IAbstractProperty property) - : base(property) - { - } - public override void Accept(IPropertyEditorContextVisitor visitor) { base.Accept(visitor); diff --git a/src/Beutl/ViewModels/Editors/BaseEditorViewModel.cs b/src/Beutl/ViewModels/Editors/BaseEditorViewModel.cs index 6b76421b4..567ebb144 100644 --- a/src/Beutl/ViewModels/Editors/BaseEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/BaseEditorViewModel.cs @@ -19,7 +19,7 @@ namespace Beutl.ViewModels.Editors; public abstract class BaseEditorViewModel : IPropertyEditorContext, IServiceProvider { - protected CompositeDisposable Disposables = new(); + protected CompositeDisposable Disposables = []; private bool _disposedValue; private IDisposable? _currentFrameRevoker; private bool _skipKeyFrameIndexSubscription; @@ -403,22 +403,11 @@ public override void RemoveAnimation() } } - private sealed class SetCommand : IRecordableCommand + private sealed class SetCommand(IAbstractProperty setter, T? oldValue, T? newValue) : IRecordableCommand { - private readonly IAbstractProperty _setter; - private readonly T? _oldValue; - private readonly T? _newValue; - - public SetCommand(IAbstractProperty setter, T? oldValue, T? newValue) - { - _setter = setter; - _oldValue = oldValue; - _newValue = newValue; - } - public void Do() { - _setter.SetValue(_newValue); + setter.SetValue(newValue); } public void Redo() @@ -428,26 +417,15 @@ public void Redo() public void Undo() { - _setter.SetValue(_oldValue); + setter.SetValue(oldValue); } } - private sealed class SetKeyFrameValueCommand : IRecordableCommand + private sealed class SetKeyFrameValueCommand(KeyFrame setter, T? oldValue, T? newValue) : IRecordableCommand { - private readonly KeyFrame _keyframe; - private readonly T? _oldValue; - private readonly T? _newValue; - - public SetKeyFrameValueCommand(KeyFrame setter, T? oldValue, T? newValue) - { - _keyframe = setter; - _oldValue = oldValue; - _newValue = newValue; - } - public void Do() { - _keyframe.SetValue(KeyFrame.ValueProperty, _newValue); + setter.SetValue(KeyFrame.ValueProperty, newValue); } public void Redo() @@ -457,24 +435,15 @@ public void Redo() public void Undo() { - _keyframe.SetValue(KeyFrame.ValueProperty, _oldValue); + setter.SetValue(KeyFrame.ValueProperty, oldValue); } } - private sealed class AddKeyFrameCommand : IRecordableCommand + private sealed class AddKeyFrameCommand(KeyFrames keyFrames, IKeyFrame keyFrame) : IRecordableCommand { - private readonly KeyFrames _keyFrames; - private readonly IKeyFrame _keyFrame; - - public AddKeyFrameCommand(KeyFrames keyFrames, IKeyFrame keyFrame) - { - _keyFrames = keyFrames; - _keyFrame = keyFrame; - } - public void Do() { - _keyFrames.Add(_keyFrame, out _); + keyFrames.Add(keyFrame, out _); } public void Redo() @@ -484,7 +453,7 @@ public void Redo() public void Undo() { - _keyFrames.Remove(_keyFrame); + keyFrames.Remove(keyFrame); } } diff --git a/src/Beutl/ViewModels/Editors/BooleanEditorViewModel.cs b/src/Beutl/ViewModels/Editors/BooleanEditorViewModel.cs index 528b1982c..f0b5314a2 100644 --- a/src/Beutl/ViewModels/Editors/BooleanEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/BooleanEditorViewModel.cs @@ -4,13 +4,8 @@ namespace Beutl.ViewModels.Editors; -public sealed class BooleanEditorViewModel : ValueEditorViewModel +public sealed class BooleanEditorViewModel(IAbstractProperty property) : ValueEditorViewModel(property) { - public BooleanEditorViewModel(IAbstractProperty property) - : base(property) - { - } - public override void Accept(IPropertyEditorContextVisitor visitor) { base.Accept(visitor); diff --git a/src/Beutl/ViewModels/Editors/BrushEditorViewModel.cs b/src/Beutl/ViewModels/Editors/BrushEditorViewModel.cs index fbe24ceaa..b637401bd 100644 --- a/src/Beutl/ViewModels/Editors/BrushEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/BrushEditorViewModel.cs @@ -11,22 +11,11 @@ namespace Beutl.ViewModels.Editors; -public sealed class SetCommand : IRecordableCommand +public sealed class SetCommand(IAbstractProperty setter, object? oldValue, object? newValue) : IRecordableCommand { - private readonly IAbstractProperty _setter; - private readonly object? _oldValue; - private readonly object? _newValue; - - public SetCommand(IAbstractProperty setter, object? oldValue, object? newValue) - { - _setter = setter; - _oldValue = oldValue; - _newValue = newValue; - } - public void Do() { - _setter.SetValue(_newValue); + setter.SetValue(newValue); } public void Redo() @@ -36,7 +25,7 @@ public void Redo() public void Undo() { - _setter.SetValue(_oldValue); + setter.SetValue(oldValue); } } diff --git a/src/Beutl/ViewModels/Editors/DynamicEnumEditorViewModel.cs b/src/Beutl/ViewModels/Editors/DynamicEnumEditorViewModel.cs index 7b31ffad2..be3283f67 100644 --- a/src/Beutl/ViewModels/Editors/DynamicEnumEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/DynamicEnumEditorViewModel.cs @@ -24,7 +24,7 @@ public DynamicEnumEditorViewModel(IAbstractProperty property) _valuesSubscription?.Dispose(); _valuesSubscription = null; - Items.Replace(value?.Values?.Select(v => v.DisplayName)?.ToArray() ?? Array.Empty()); + Items.Replace([.. value?.Values?.Select(v => v.DisplayName) ?? []]); if (value?.Values != null) { value.Values.CollectionChanged += OnValuesCollectionChanged; @@ -84,7 +84,7 @@ void Remove(int index, IList items) SelectedIndex.Value = Value.Value?.Values.IndexOf(Value.Value.SelectedValue) ?? -1; } - public CoreList Items { get; } = new(); + public CoreList Items { get; } = []; public ReadOnlyReactivePropertySlim SelectedValue { get; } diff --git a/src/Beutl/ViewModels/Editors/EnumEditorViewModel.cs b/src/Beutl/ViewModels/Editors/EnumEditorViewModel.cs index 754c262fe..96813a934 100644 --- a/src/Beutl/ViewModels/Editors/EnumEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/EnumEditorViewModel.cs @@ -4,14 +4,9 @@ namespace Beutl.ViewModels.Editors; -public sealed class EnumEditorViewModel : ValueEditorViewModel +public sealed class EnumEditorViewModel(IAbstractProperty property) : ValueEditorViewModel(property) where T : struct, Enum { - public EnumEditorViewModel(IAbstractProperty property) - : base(property) - { - } - public override void Accept(IPropertyEditorContextVisitor visitor) { base.Accept(visitor); diff --git a/src/Beutl/ViewModels/Editors/FontFamilyEditorViewModel.cs b/src/Beutl/ViewModels/Editors/FontFamilyEditorViewModel.cs index ab216aa8c..a5fbe74c0 100644 --- a/src/Beutl/ViewModels/Editors/FontFamilyEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/FontFamilyEditorViewModel.cs @@ -5,13 +5,8 @@ namespace Beutl.ViewModels.Editors; -public sealed class FontFamilyEditorViewModel : ValueEditorViewModel +public sealed class FontFamilyEditorViewModel(IAbstractProperty property) : ValueEditorViewModel(property) { - public FontFamilyEditorViewModel(IAbstractProperty property) - : base(property) - { - } - public override void Accept(IPropertyEditorContextVisitor visitor) { base.Accept(visitor); diff --git a/src/Beutl/ViewModels/Editors/GradientStopsEditorViewModel.cs b/src/Beutl/ViewModels/Editors/GradientStopsEditorViewModel.cs index 41599d636..5e669a49c 100644 --- a/src/Beutl/ViewModels/Editors/GradientStopsEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/GradientStopsEditorViewModel.cs @@ -18,7 +18,7 @@ public GradientStopsEditorViewModel(IAbstractProperty property) GradientStops? initValue = property.GetValue(); if (initValue == null) { - property.SetValue(initValue = new GradientStops()); + property.SetValue(initValue = []); } Value = property.GetObservable() @@ -38,7 +38,7 @@ public GradientStopsEditorViewModel(IAbstractProperty property) public ReadOnlyReactivePropertySlim Value { get; } - public AM.GradientStops Stops { get; } = new(); + public AM.GradientStops Stops { get; } = []; public ReactivePropertySlim SelectedItem { get; } = new(); diff --git a/src/Beutl/ViewModels/Editors/ImageSourceEditorViewModel.cs b/src/Beutl/ViewModels/Editors/ImageSourceEditorViewModel.cs index 780d2e2ac..0097be79a 100644 --- a/src/Beutl/ViewModels/Editors/ImageSourceEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/ImageSourceEditorViewModel.cs @@ -32,22 +32,12 @@ public void SetValueAndDispose(IImageSource? oldValue, IImageSource? newValue) } } - private sealed class SetKeyFrameValueCommand : IRecordableCommand + private sealed class SetKeyFrameValueCommand(KeyFrame setter, IImageSource? oldValue, IImageSource? newValue) : IRecordableCommand { - private readonly KeyFrame _keyframe; - private readonly string? _oldName; - private readonly string? _newName; - private IImageSource? _oldValue; - private IImageSource? _newValue; - - public SetKeyFrameValueCommand(KeyFrame setter, IImageSource? oldValue, IImageSource? newValue) - { - _keyframe = setter; - _oldValue = oldValue; - _newValue = newValue; - _oldName = oldValue?.Name; - _newName = newValue?.Name; - } + private readonly string? _oldName = oldValue?.Name; + private readonly string? _newName = newValue?.Name; + private IImageSource? _oldValue = oldValue; + private IImageSource? _newValue = newValue; public void Do() { @@ -57,7 +47,7 @@ public void Do() _newValue = newValue; } - _keyframe.SetValue(KeyFrame.ValueProperty, _newValue); + setter.SetValue(KeyFrame.ValueProperty, _newValue); _oldValue?.Dispose(); _oldValue = null; } @@ -75,28 +65,18 @@ public void Undo() _oldValue = oldValue; } - _keyframe.SetValue(KeyFrame.ValueProperty, _oldValue); + setter.SetValue(KeyFrame.ValueProperty, _oldValue); _newValue?.Dispose(); _newValue = null; } } - private sealed class SetCommand : IRecordableCommand + private sealed class SetCommand(IAbstractProperty setter, IImageSource? oldValue, IImageSource? newValue) : IRecordableCommand { - private readonly IAbstractProperty _setter; - private readonly string? _oldName; - private readonly string? _newName; - private IImageSource? _oldValue; - private IImageSource? _newValue; - - public SetCommand(IAbstractProperty setter, IImageSource? oldValue, IImageSource? newValue) - { - _setter = setter; - _oldValue = oldValue; - _newValue = newValue; - _oldName = oldValue?.Name; - _newName = newValue?.Name; - } + private readonly string? _oldName = oldValue?.Name; + private readonly string? _newName = newValue?.Name; + private IImageSource? _oldValue = oldValue; + private IImageSource? _newValue = newValue; public void Do() { @@ -106,7 +86,7 @@ public void Do() _newValue = newValue; } - _setter.SetValue(_newValue); + setter.SetValue(_newValue); _oldValue?.Dispose(); _oldValue = null; } @@ -124,7 +104,7 @@ public void Undo() _oldValue = oldValue; } - _setter.SetValue(_oldValue); + setter.SetValue(_oldValue); _newValue?.Dispose(); _newValue = null; } diff --git a/src/Beutl/ViewModels/Editors/ListEditorViewModel.cs b/src/Beutl/ViewModels/Editors/ListEditorViewModel.cs index b32a87769..0a24daf81 100644 --- a/src/Beutl/ViewModels/Editors/ListEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/ListEditorViewModel.cs @@ -153,7 +153,7 @@ public ListEditorViewModel(IAbstractProperty property) public ReadOnlyReactivePropertySlim?> List { get; } - public CoreList> Items { get; } = new(); + public CoreList> Items { get; } = []; public ReactivePropertySlim IsExpanded { get; } = new(false); diff --git a/src/Beutl/ViewModels/Editors/NumberEditorViewModel.cs b/src/Beutl/ViewModels/Editors/NumberEditorViewModel.cs index 24ba09be7..18e0eda1f 100644 --- a/src/Beutl/ViewModels/Editors/NumberEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/NumberEditorViewModel.cs @@ -6,14 +6,9 @@ namespace Beutl.ViewModels.Editors; -public sealed class NumberEditorViewModel : ValueEditorViewModel +public sealed class NumberEditorViewModel(IAbstractProperty property) : ValueEditorViewModel(property) where T : struct, INumber { - public NumberEditorViewModel(IAbstractProperty property) - : base(property) - { - } - public override void Accept(IPropertyEditorContextVisitor visitor) { base.Accept(visitor); diff --git a/src/Beutl/ViewModels/Editors/PenEditorViewModel.cs b/src/Beutl/ViewModels/Editors/PenEditorViewModel.cs index 75f606995..33c7ca29b 100644 --- a/src/Beutl/ViewModels/Editors/PenEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/PenEditorViewModel.cs @@ -93,9 +93,9 @@ private void AcceptChildren() public ReadOnlyReactivePropertySlim Value { get; } - public CoreList MajorProperties { get; } = new(); + public CoreList MajorProperties { get; } = []; - public CoreList MinorProperties { get; } = new(); + public CoreList MinorProperties { get; } = []; public override void Reset() { diff --git a/src/Beutl/ViewModels/Editors/PropertiesEditorViewModel.cs b/src/Beutl/ViewModels/Editors/PropertiesEditorViewModel.cs index 9c759ae57..23a63477a 100644 --- a/src/Beutl/ViewModels/Editors/PropertiesEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/PropertiesEditorViewModel.cs @@ -30,7 +30,7 @@ public PropertiesEditorViewModel(ICoreObject obj, Func Properties { get; } = new(); + public CoreList Properties { get; } = []; public void Dispose() { @@ -83,7 +83,7 @@ private void InitializeCoreObject(ICoreObject obj, Func); bool isAnimatable = obj is IAnimatable; - List cprops = PropertyRegistry.GetRegistered(objType).ToList(); + List cprops = [.. PropertyRegistry.GetRegistered(objType)]; cprops.RemoveAll(x => !(predicate?.Invoke(x, x.GetMetadata(objType)) ?? true)); List props = cprops.ConvertAll(x => { diff --git a/src/Beutl/ViewModels/Editors/PropertyEditorGroupContext.cs b/src/Beutl/ViewModels/Editors/PropertyEditorGroupContext.cs index 188acb64b..e368be4bf 100644 --- a/src/Beutl/ViewModels/Editors/PropertyEditorGroupContext.cs +++ b/src/Beutl/ViewModels/Editors/PropertyEditorGroupContext.cs @@ -2,24 +2,15 @@ namespace Beutl.ViewModels.Editors; -public sealed class PropertyEditorGroupContext : IPropertyEditorContext +public sealed class PropertyEditorGroupContext(IPropertyEditorContext?[] children, string groupName, bool isFirst) : IPropertyEditorContext { - private IPropertyEditorContext?[] _properties; - - public PropertyEditorGroupContext(IPropertyEditorContext?[] children, string groupName, bool isFirst) - { - _properties = children; - GroupName = groupName; - IsFirst = isFirst; - } - - public IReadOnlyList Properties => _properties; + public IReadOnlyList Properties => children; public PropertyEditorExtension Extension => PropertyEditorExtension.Instance; - public string GroupName { get; } + public string GroupName { get; } = groupName; - public bool IsFirst { get; } + public bool IsFirst { get; } = isFirst; public void Accept(IPropertyEditorContextVisitor visitor) { @@ -28,12 +19,12 @@ public void Accept(IPropertyEditorContextVisitor visitor) public void Dispose() { - foreach (IPropertyEditorContext? item in _properties.AsSpan()) + foreach (IPropertyEditorContext? item in children.AsSpan()) { item?.Dispose(); } - _properties = Array.Empty(); + children = []; } public void ReadFromJson(JsonObject json) @@ -41,7 +32,7 @@ public void ReadFromJson(JsonObject json) if (json.TryGetPropertyValue(nameof(Properties), out JsonNode? childrenNode) && childrenNode is JsonArray childrenArray) { - foreach ((JsonNode? node, IPropertyEditorContext? context) in childrenArray.Zip(_properties)) + foreach ((JsonNode? node, IPropertyEditorContext? context) in childrenArray.Zip(children)) { if (context != null && node != null) { @@ -55,7 +46,7 @@ public void WriteToJson(JsonObject json) { var array = new JsonArray(); - foreach (IPropertyEditorContext? item in _properties.AsSpan()) + foreach (IPropertyEditorContext? item in children.AsSpan()) { if (item == null) { diff --git a/src/Beutl/ViewModels/Editors/SoundSourceEditorViewModel.cs b/src/Beutl/ViewModels/Editors/SoundSourceEditorViewModel.cs index a93fa7d09..cd3644068 100644 --- a/src/Beutl/ViewModels/Editors/SoundSourceEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/SoundSourceEditorViewModel.cs @@ -32,22 +32,12 @@ public void SetValueAndDispose(ISoundSource? oldValue, ISoundSource? newValue) } } - private sealed class SetKeyFrameValueCommand : IRecordableCommand + private sealed class SetKeyFrameValueCommand(KeyFrame setter, ISoundSource? oldValue, ISoundSource? newValue) : IRecordableCommand { - private readonly KeyFrame _keyframe; - private readonly string? _oldName; - private readonly string? _newName; - private ISoundSource? _oldValue; - private ISoundSource? _newValue; - - public SetKeyFrameValueCommand(KeyFrame setter, ISoundSource? oldValue, ISoundSource? newValue) - { - _keyframe = setter; - _oldValue = oldValue; - _newValue = newValue; - _oldName = oldValue?.Name; - _newName = newValue?.Name; - } + private readonly string? _oldName = oldValue?.Name; + private readonly string? _newName = newValue?.Name; + private ISoundSource? _oldValue = oldValue; + private ISoundSource? _newValue = newValue; public void Do() { @@ -57,7 +47,7 @@ public void Do() _newValue = newValue; } - _keyframe.SetValue(KeyFrame.ValueProperty, _newValue); + setter.SetValue(KeyFrame.ValueProperty, _newValue); _oldValue?.Dispose(); _oldValue = null; } @@ -75,28 +65,18 @@ public void Undo() _oldValue = oldValue; } - _keyframe.SetValue(KeyFrame.ValueProperty, _oldValue); + setter.SetValue(KeyFrame.ValueProperty, _oldValue); _newValue?.Dispose(); _newValue = null; } } - private sealed class SetCommand : IRecordableCommand + private sealed class SetCommand(IAbstractProperty setter, ISoundSource? oldValue, ISoundSource? newValue) : IRecordableCommand { - private readonly IAbstractProperty _setter; - private readonly string? _oldName; - private readonly string? _newName; - private ISoundSource? _oldValue; - private ISoundSource? _newValue; - - public SetCommand(IAbstractProperty setter, ISoundSource? oldValue, ISoundSource? newValue) - { - _setter = setter; - _oldValue = oldValue; - _newValue = newValue; - _oldName = oldValue?.Name; - _newName = newValue?.Name; - } + private readonly string? _oldName = oldValue?.Name; + private readonly string? _newName = newValue?.Name; + private ISoundSource? _oldValue = oldValue; + private ISoundSource? _newValue = newValue; public void Do() { @@ -106,7 +86,7 @@ public void Do() _newValue = newValue; } - _setter.SetValue(_newValue); + setter.SetValue(_newValue); _oldValue?.Dispose(); _oldValue = null; } @@ -124,7 +104,7 @@ public void Undo() _oldValue = oldValue; } - _setter.SetValue(_oldValue); + setter.SetValue(_oldValue); _newValue?.Dispose(); _newValue = null; } diff --git a/src/Beutl/ViewModels/Editors/StringEditorViewModel.cs b/src/Beutl/ViewModels/Editors/StringEditorViewModel.cs index 2c96bf7d7..457297916 100644 --- a/src/Beutl/ViewModels/Editors/StringEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/StringEditorViewModel.cs @@ -6,13 +6,8 @@ namespace Beutl.ViewModels.Editors; -public sealed class StringEditorViewModel : ValueEditorViewModel +public sealed class StringEditorViewModel(IAbstractProperty property) : ValueEditorViewModel(property) { - public StringEditorViewModel(IAbstractProperty property) - : base(property) - { - } - public override void Accept(IPropertyEditorContextVisitor visitor) { base.Accept(visitor); diff --git a/src/Beutl/ViewModels/Editors/VideoSourceEditorViewModel.cs b/src/Beutl/ViewModels/Editors/VideoSourceEditorViewModel.cs index 5ecae9b05..43cc6d121 100644 --- a/src/Beutl/ViewModels/Editors/VideoSourceEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/VideoSourceEditorViewModel.cs @@ -32,22 +32,12 @@ public void SetValueAndDispose(IVideoSource? oldValue, IVideoSource? newValue) } } - private sealed class SetKeyFrameValueCommand : IRecordableCommand + private sealed class SetKeyFrameValueCommand(KeyFrame setter, IVideoSource? oldValue, IVideoSource? newValue) : IRecordableCommand { - private readonly KeyFrame _keyframe; - private readonly string? _oldName; - private readonly string? _newName; - private IVideoSource? _oldValue; - private IVideoSource? _newValue; - - public SetKeyFrameValueCommand(KeyFrame setter, IVideoSource? oldValue, IVideoSource? newValue) - { - _keyframe = setter; - _oldValue = oldValue; - _newValue = newValue; - _oldName = oldValue?.Name; - _newName = newValue?.Name; - } + private readonly string? _oldName = oldValue?.Name; + private readonly string? _newName = newValue?.Name; + private IVideoSource? _oldValue = oldValue; + private IVideoSource? _newValue = newValue; public void Do() { @@ -57,7 +47,7 @@ public void Do() _newValue = newValue; } - _keyframe.SetValue(KeyFrame.ValueProperty, _newValue); + setter.SetValue(KeyFrame.ValueProperty, _newValue); _oldValue?.Dispose(); _oldValue = null; } @@ -75,28 +65,18 @@ public void Undo() _oldValue = oldValue; } - _keyframe.SetValue(KeyFrame.ValueProperty, _oldValue); + setter.SetValue(KeyFrame.ValueProperty, _oldValue); _newValue?.Dispose(); _newValue = null; } } - private sealed class SetCommand : IRecordableCommand + private sealed class SetCommand(IAbstractProperty setter, IVideoSource? oldValue, IVideoSource? newValue) : IRecordableCommand { - private readonly IAbstractProperty _setter; - private readonly string? _oldName; - private readonly string? _newName; - private IVideoSource? _oldValue; - private IVideoSource? _newValue; - - public SetCommand(IAbstractProperty setter, IVideoSource? oldValue, IVideoSource? newValue) - { - _setter = setter; - _oldValue = oldValue; - _newValue = newValue; - _oldName = oldValue?.Name; - _newName = newValue?.Name; - } + private readonly string? _oldName = oldValue?.Name; + private readonly string? _newName = newValue?.Name; + private IVideoSource? _oldValue = oldValue; + private IVideoSource? _newValue = newValue; public void Do() { @@ -106,7 +86,7 @@ public void Do() _newValue = newValue; } - _setter.SetValue(_newValue); + setter.SetValue(_newValue); _oldValue?.Dispose(); _oldValue = null; } @@ -124,7 +104,7 @@ public void Undo() _oldValue = oldValue; } - _setter.SetValue(_oldValue); + setter.SetValue(_oldValue); _newValue?.Dispose(); _newValue = null; } diff --git a/src/Beutl/ViewModels/ElementScopeViewModel.cs b/src/Beutl/ViewModels/ElementScopeViewModel.cs index 5f2d84247..41e4c788b 100644 --- a/src/Beutl/ViewModels/ElementScopeViewModel.cs +++ b/src/Beutl/ViewModels/ElementScopeViewModel.cs @@ -11,7 +11,7 @@ namespace Beutl.ViewModels; public sealed class ElementScopeViewModel : IDisposable { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private TakeAfterOperator? _model; public ElementScopeViewModel(Element element, ElementViewModel parent) diff --git a/src/Beutl/ViewModels/ElementViewModel.cs b/src/Beutl/ViewModels/ElementViewModel.cs index 3d97b64dc..bce39c530 100644 --- a/src/Beutl/ViewModels/ElementViewModel.cs +++ b/src/Beutl/ViewModels/ElementViewModel.cs @@ -23,7 +23,7 @@ namespace Beutl.ViewModels; public sealed class ElementViewModel : IDisposable { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; public ElementViewModel(Element element, TimelineViewModel timeline) { diff --git a/src/Beutl/ViewModels/ExtensionsPageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPageViewModel.cs index 9732001df..6ad64bce7 100644 --- a/src/Beutl/ViewModels/ExtensionsPageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPageViewModel.cs @@ -8,8 +8,8 @@ namespace Beutl.ViewModels; public sealed class ExtensionsPageViewModel : IPageContext { - private readonly CompositeDisposable _disposables = new(); - private readonly CompositeDisposable _authDisposables = new(); + private readonly CompositeDisposable _disposables = []; + private readonly CompositeDisposable _authDisposables = []; private readonly BeutlApiApplication _clients; private Lazy? _discover; private Lazy? _library; diff --git a/src/Beutl/ViewModels/ExtensionsPages/DevelopPageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/DevelopPageViewModel.cs index f5b9050d5..4878babb7 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DevelopPageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DevelopPageViewModel.cs @@ -14,7 +14,7 @@ namespace Beutl.ViewModels.ExtensionsPages; public sealed class DevelopPageViewModel : BasePageViewModel, ISupportRefreshViewModel { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly AuthorizedUser _user; public DevelopPageViewModel(AuthorizedUser user, BeutlApiApplication apiApplication) @@ -73,7 +73,7 @@ public DevelopPageViewModel(AuthorizedUser user, BeutlApiApplication apiApplicat Refresh.Execute(); } - public CoreList Packages { get; } = new(); + public CoreList Packages { get; } = []; public ReactivePropertySlim IsBusy { get; } = new(); diff --git a/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/DataContextFactory.cs b/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/DataContextFactory.cs index 6bdd1eab4..bc311e49c 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/DataContextFactory.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/DataContextFactory.cs @@ -6,49 +6,42 @@ namespace Beutl.ViewModels.ExtensionsPages.DevelopPages; -public class DataContextFactory +public class DataContextFactory(AuthorizedUser user, BeutlApiApplication apiApplication) { - private readonly AuthorizedUser _user; - private readonly DiscoverService _discoverService; - - public DataContextFactory(AuthorizedUser user, BeutlApiApplication apiApplication) - { - _user = user; - _discoverService = apiApplication.GetResource(); - } + private readonly DiscoverService _discoverService = apiApplication.GetResource(); public AddReleaseDialogViewModel AddReleaseDialog(Package package) { - return new AddReleaseDialogViewModel(_user, package); + return new AddReleaseDialogViewModel(user, package); } public CreatePackageDialogViewModel CreatePackageDialog() { - return new CreatePackageDialogViewModel(_user, _discoverService); + return new CreatePackageDialogViewModel(user, _discoverService); } public UpdatePackageDialogViewModel UpdatePackageDialog() { - return new UpdatePackageDialogViewModel(_user, _discoverService); + return new UpdatePackageDialogViewModel(user, _discoverService); } public PackageDetailsPageViewModel PackageDetailsPage(Package package) { - return new PackageDetailsPageViewModel(_user, package); + return new PackageDetailsPageViewModel(user, package); } public PackageReleasesPageViewModel PackageReleasesPage(Package package) { - return new PackageReleasesPageViewModel(_user, package); + return new PackageReleasesPageViewModel(user, package); } public PackageSettingsPageViewModel PackageSettingsPage(Package package) { - return new PackageSettingsPageViewModel(_user, package); + return new PackageSettingsPageViewModel(user, package); } public ReleasePageViewModel ReleasePage(Release release) { - return new ReleasePageViewModel(_user, release); + return new ReleasePageViewModel(user, release); } } diff --git a/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageDetailsPageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageDetailsPageViewModel.cs index 8c7f74566..dc207df4b 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageDetailsPageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageDetailsPageViewModel.cs @@ -11,7 +11,7 @@ namespace Beutl.ViewModels.ExtensionsPages.DevelopPages; public sealed class PackageDetailsPageViewModel : BasePageViewModel, ISupportRefreshViewModel { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly AuthorizedUser _user; public PackageDetailsPageViewModel(AuthorizedUser user, Package package) diff --git a/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageReleasesPageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageReleasesPageViewModel.cs index 4205619ef..e735d6071 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageReleasesPageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageReleasesPageViewModel.cs @@ -76,7 +76,7 @@ public PackageReleasesPageViewModel(AuthorizedUser user, Package package) public Package Package { get; } - public CoreList Items { get; } = new(); + public CoreList Items { get; } = []; public ReactivePropertySlim IsBusy { get; } = new(); diff --git a/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageSettingsPageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageSettingsPageViewModel.cs index 0f5a286dc..273eddcc8 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageSettingsPageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/PackageSettingsPageViewModel.cs @@ -16,7 +16,7 @@ namespace Beutl.ViewModels.ExtensionsPages.DevelopPages; public sealed class PackageSettingsPageViewModel : BasePageViewModel, ISupportRefreshViewModel { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly AuthorizedUser _user; private readonly ReactivePropertySlim _screenshotsChange = new(); @@ -59,7 +59,7 @@ public PackageSettingsPageViewModel(AuthorizedUser user, Package package) .CopyToReactiveProperty() .DisposeWith(_disposables); - Screenshots = new AvaloniaList(); + Screenshots = []; package.Screenshots.Subscribe(async x => await ResetScreenshots(x)) .DisposeWith(_disposables); diff --git a/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/ReleasePageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/ReleasePageViewModel.cs index 76d6dc792..729b626d9 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/ReleasePageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DevelopPages/ReleasePageViewModel.cs @@ -18,7 +18,7 @@ namespace Beutl.ViewModels.ExtensionsPages.DevelopPages; public sealed class ReleasePageViewModel : BasePageViewModel, ISupportRefreshViewModel { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly AuthorizedUser _user; public ReleasePageViewModel(AuthorizedUser user, Release release) diff --git a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPageViewModel.cs index 1996c1153..254c517ba 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPageViewModel.cs @@ -97,13 +97,13 @@ static async Task LoadAsync(CoreList packages, Func Top10 { get; } = new(); + public CoreList Top10 { get; } = []; - public CoreList DailyRanking { get; } = new(); + public CoreList DailyRanking { get; } = []; - public CoreList WeeklyRanking { get; } = new(); + public CoreList WeeklyRanking { get; } = []; - public CoreList RecentlyRanking { get; } = new(); + public CoreList RecentlyRanking { get; } = []; public ReactivePropertySlim IsBusy { get; } = new(); diff --git a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/DataContextFactory.cs b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/DataContextFactory.cs index 61ee0baeb..13b5bc3f3 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/DataContextFactory.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/DataContextFactory.cs @@ -3,29 +3,20 @@ using Beutl.Api.Services; namespace Beutl.ViewModels.ExtensionsPages.DiscoverPages; -public class DataContextFactory +public class DataContextFactory(DiscoverService discoverService, BeutlApiApplication application) { - private readonly DiscoverService _discoverService; - private readonly BeutlApiApplication _application; - - public DataContextFactory(DiscoverService discoverService, BeutlApiApplication application) - { - _discoverService = discoverService; - _application = application; - } - public RankingPageViewModel RankingPage(RankingType rankingType = RankingType.Overall) { - return new RankingPageViewModel(_discoverService, rankingType); + return new RankingPageViewModel(discoverService, rankingType); } public SearchPageViewModel SearchPage(string keyword) { - return new SearchPageViewModel(_discoverService, keyword); + return new SearchPageViewModel(discoverService, keyword); } public PublicPackageDetailsPageViewModel PublicPackageDetailPage(Package package) { - return new PublicPackageDetailsPageViewModel(package, _application); + return new PublicPackageDetailsPageViewModel(package, application); } } diff --git a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/PublicPackageDetailsPageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/PublicPackageDetailsPageViewModel.cs index 67251311e..ad1b111d4 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/PublicPackageDetailsPageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/PublicPackageDetailsPageViewModel.cs @@ -19,7 +19,7 @@ namespace Beutl.ViewModels.ExtensionsPages.DiscoverPages; public sealed class PublicPackageDetailsPageViewModel : BasePageViewModel, ISupportRefreshViewModel { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly InstalledPackageRepository _installedPackageRepository; private readonly PackageChangesQueue _queue; private readonly LibraryService _library; @@ -290,7 +290,7 @@ public PublicPackageDetailsPageViewModel(Package package, BeutlApiApplication ap public ReadOnlyReactivePropertySlim DisplayName { get; } - public CoreList AllReleases { get; } = new(); + public CoreList AllReleases { get; } = []; public ReactivePropertySlim SelectedRelease { get; } = new(); diff --git a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/RankingPageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/RankingPageViewModel.cs index bf3e533fa..100a7868c 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/RankingPageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/RankingPageViewModel.cs @@ -24,18 +24,18 @@ public record RankingModel(string DisplayName, RankingType Type); public sealed class RankingPageViewModel : BasePageViewModel, ISupportRefreshViewModel { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly DiscoverService _discover; public RankingPageViewModel(DiscoverService discover, RankingType rankingType) { - Rankings = new RankingModel[] - { + Rankings = + [ new RankingModel(ExtensionsPage.Overall, RankingType.Overall), new RankingModel(ExtensionsPage.Daily, RankingType.Daily), new RankingModel(ExtensionsPage.Weekly, RankingType.Weekly), new RankingModel(ExtensionsPage.Recently, RankingType.Recently), - }; + ]; SelectedRanking = new ReactivePropertySlim(Rankings.First(x => x.Type == rankingType)); _discover = discover; @@ -112,7 +112,7 @@ public RankingPageViewModel(DiscoverService discover, RankingType rankingType) public RankingModel[] Rankings { get; } - public AvaloniaList Items { get; } = new(); + public AvaloniaList Items { get; } = []; public AsyncReactiveCommand Refresh { get; } diff --git a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/SearchPageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/SearchPageViewModel.cs index 3f29aeebe..23863e350 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/SearchPageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/SearchPageViewModel.cs @@ -14,7 +14,7 @@ namespace Beutl.ViewModels.ExtensionsPages.DiscoverPages; public sealed class SearchPageViewModel : BasePageViewModel, ISupportRefreshViewModel { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly DiscoverService _discoverService; public SearchPageViewModel(DiscoverService discoverService, string keyword) @@ -109,9 +109,9 @@ public SearchPageViewModel(DiscoverService discoverService, string keyword) public string Keyword { get; } - public AvaloniaList Packages { get; } = new(); + public AvaloniaList Packages { get; } = []; - public AvaloniaList Users { get; } = new(); + public AvaloniaList Users { get; } = []; public AsyncReactiveCommand Refresh { get; } diff --git a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/UserProfilePageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/UserProfilePageViewModel.cs index b05c07308..e0c75469c 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/UserProfilePageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/DiscoverPages/UserProfilePageViewModel.cs @@ -13,7 +13,7 @@ namespace Beutl.ViewModels.ExtensionsPages.DiscoverPages; public sealed class UserProfilePageViewModel : BasePageViewModel, ISupportRefreshViewModel { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; public UserProfilePageViewModel(Profile profile) { @@ -108,7 +108,7 @@ public UserProfilePageViewModel(Profile profile) public IReadOnlyReactiveProperty Email { get; } - public AvaloniaList Packages { get; } = new(); + public AvaloniaList Packages { get; } = []; public AsyncReactiveCommand Refresh { get; } diff --git a/src/Beutl/ViewModels/ExtensionsPages/LibraryPageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/LibraryPageViewModel.cs index 9c578bf0b..2d7e230db 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/LibraryPageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/LibraryPageViewModel.cs @@ -21,7 +21,7 @@ public sealed class LibraryPageViewModel : BasePageViewModel, ISupportRefreshVie private readonly ILogger _logger = Log.ForContext(); private readonly AuthorizedUser _user; private readonly BeutlApiApplication _clients; - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly LibraryService _service; public LibraryPageViewModel(AuthorizedUser user, BeutlApiApplication clients) @@ -159,9 +159,9 @@ public LibraryPageViewModel(AuthorizedUser user, BeutlApiApplication clients) .DisposeWith(_disposables); } - public AvaloniaList Packages { get; } = new(); + public AvaloniaList Packages { get; } = []; - public AvaloniaList LocalPackages { get; } = new(); + public AvaloniaList LocalPackages { get; } = []; public AsyncReactiveCommand Refresh { get; } diff --git a/src/Beutl/ViewModels/ExtensionsPages/LocalYourPackageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/LocalYourPackageViewModel.cs index 3fb098b91..38d8a5513 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/LocalYourPackageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/LocalYourPackageViewModel.cs @@ -17,7 +17,7 @@ namespace Beutl.ViewModels.ExtensionsPages; public sealed class LocalYourPackageViewModel : BaseViewModel, IYourPackageViewModel { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly InstalledPackageRepository _installedPackageRepository; private readonly PackageChangesQueue _queue; private readonly PackageIdentity _packageIdentity; diff --git a/src/Beutl/ViewModels/ExtensionsPages/RemoteYourPackageViewModel.cs b/src/Beutl/ViewModels/ExtensionsPages/RemoteYourPackageViewModel.cs index 9fea7da48..6ade05b08 100644 --- a/src/Beutl/ViewModels/ExtensionsPages/RemoteYourPackageViewModel.cs +++ b/src/Beutl/ViewModels/ExtensionsPages/RemoteYourPackageViewModel.cs @@ -19,7 +19,7 @@ namespace Beutl.ViewModels.ExtensionsPages; public sealed class RemoteYourPackageViewModel : BaseViewModel, IYourPackageViewModel { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly InstalledPackageRepository _installedPackageRepository; private readonly PackageChangesQueue _queue; private readonly BeutlApiApplication _app; diff --git a/src/Beutl/ViewModels/GraphEditorKeyFrameViewModel.cs b/src/Beutl/ViewModels/GraphEditorKeyFrameViewModel.cs index 48a9263fc..2b39eed04 100644 --- a/src/Beutl/ViewModels/GraphEditorKeyFrameViewModel.cs +++ b/src/Beutl/ViewModels/GraphEditorKeyFrameViewModel.cs @@ -13,7 +13,7 @@ namespace Beutl.ViewModels; public sealed class GraphEditorKeyFrameViewModel : IDisposable { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly GraphEditorViewViewModel _parent; internal readonly ReactivePropertySlim _previous = new(); internal GraphEditorKeyFrameViewModel? _next; @@ -299,32 +299,21 @@ public void SubmitKeyTimeAndValue(TimeSpan oldKeyTime) Right.Value = Model.KeyTime.ToPixel(_parent.Parent.Options.Value.Scale); } - private sealed class SubmitControlPointCommand : IRecordableCommand + private sealed class SubmitControlPointCommand( + (float, float) oldValue, (float, float) newValue, SplineEasing splineEasing, bool first) + : IRecordableCommand { - private readonly (float, float) _oldValue; - private readonly (float, float) _newValue; - private readonly SplineEasing _splineEasing; - private readonly bool _first; - - public SubmitControlPointCommand((float, float) oldValue, (float, float) newValue, SplineEasing splineEasing, bool first) - { - _oldValue = oldValue; - _newValue = newValue; - _splineEasing = splineEasing; - _first = first; - } - public void Do() { - if (_first) + if (first) { - _splineEasing.X1 = _newValue.Item1; - _splineEasing.Y1 = _newValue.Item2; + splineEasing.X1 = newValue.Item1; + splineEasing.Y1 = newValue.Item2; } else { - _splineEasing.X2 = _newValue.Item1; - _splineEasing.Y2 = _newValue.Item2; + splineEasing.X2 = newValue.Item1; + splineEasing.Y2 = newValue.Item2; } } @@ -332,48 +321,34 @@ public void Do() public void Undo() { - if (_first) + if (first) { - _splineEasing.X1 = _oldValue.Item1; - _splineEasing.Y1 = _oldValue.Item2; + splineEasing.X1 = oldValue.Item1; + splineEasing.Y1 = oldValue.Item2; } else { - _splineEasing.X2 = _oldValue.Item1; - _splineEasing.Y2 = _oldValue.Item2; + splineEasing.X2 = oldValue.Item1; + splineEasing.Y2 = oldValue.Item2; } } } - private sealed class SubmitKeyFrameCommand : IRecordableCommand + private sealed class SubmitKeyFrameCommand(IKeyFrame keyframe, TimeSpan oldTime, TimeSpan newTime, object? oldValue, object? newValue) + : IRecordableCommand { - private readonly IKeyFrame _keyframe; - private readonly TimeSpan _oldTime; - private readonly TimeSpan _newTime; - private readonly object? _oldValue; - private readonly object? _newValue; - - public SubmitKeyFrameCommand(IKeyFrame keyframe, TimeSpan oldTime, TimeSpan newTime, object? oldValue, object? newValue) - { - _keyframe = keyframe; - _oldTime = oldTime; - _newTime = newTime; - _oldValue = oldValue; - _newValue = newValue; - } - public void Do() { - _keyframe.Value = _newValue; - _keyframe.KeyTime = _newTime; + keyframe.Value = newValue; + keyframe.KeyTime = newTime; } public void Redo() => Do(); public void Undo() { - _keyframe.Value = _oldValue; - _keyframe.KeyTime = _oldTime; + keyframe.Value = oldValue; + keyframe.KeyTime = oldTime; } } } diff --git a/src/Beutl/ViewModels/GraphEditorViewModel.cs b/src/Beutl/ViewModels/GraphEditorViewModel.cs index 402b7edb5..3b7191a72 100644 --- a/src/Beutl/ViewModels/GraphEditorViewModel.cs +++ b/src/Beutl/ViewModels/GraphEditorViewModel.cs @@ -10,13 +10,10 @@ namespace Beutl.ViewModels; -public sealed class GraphEditorViewModel : GraphEditorViewModel +public sealed class GraphEditorViewModel( + EditViewModel editViewModel, KeyFrameAnimation animation, Element? element) + : GraphEditorViewModel(editViewModel, animation, element) { - public GraphEditorViewModel(EditViewModel editViewModel, KeyFrameAnimation animation, Element? element) - : base(editViewModel, animation, element) - { - } - public override void DropEasing(Easing easing, TimeSpan keyTime) { var originalKeyTime = keyTime; @@ -56,20 +53,11 @@ public override void InsertKeyFrame(Easing easing, TimeSpan keyTime) } } - private sealed class AddKeyFrameCommand : IRecordableCommand + private sealed class AddKeyFrameCommand(KeyFrames keyFrames, IKeyFrame keyFrame) : IRecordableCommand { - private readonly KeyFrames _keyFrames; - private readonly IKeyFrame _keyFrame; - - public AddKeyFrameCommand(KeyFrames keyFrames, IKeyFrame keyFrame) - { - _keyFrames = keyFrames; - _keyFrame = keyFrame; - } - public void Do() { - _keyFrames.Add(_keyFrame, out _); + keyFrames.Add(keyFrame, out _); } public void Redo() @@ -79,14 +67,14 @@ public void Redo() public void Undo() { - _keyFrames.Remove(_keyFrame); + keyFrames.Remove(keyFrame); } } } public abstract class GraphEditorViewModel : IDisposable { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly EditViewModel _editViewModel; private readonly GraphEditorViewViewModelFactory[] _factories; protected Element? Element; diff --git a/src/Beutl/ViewModels/GraphEditorViewViewModel.cs b/src/Beutl/ViewModels/GraphEditorViewViewModel.cs index f5bb8e730..fa35f8104 100644 --- a/src/Beutl/ViewModels/GraphEditorViewViewModel.cs +++ b/src/Beutl/ViewModels/GraphEditorViewViewModel.cs @@ -14,7 +14,7 @@ namespace Beutl.ViewModels; public sealed class GraphEditorViewViewModel : IDisposable { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly ConvertToDelegate? _convertTo; private readonly TryConvertFromDelegate? _convertFrom; private readonly ImmutableSolidColorBrush? _specifiedColor; @@ -58,7 +58,7 @@ public GraphEditorViewViewModel( public ReadOnlyReactivePropertySlim IsSelected { get; } - public CoreList KeyFrames { get; } = new(); + public CoreList KeyFrames { get; } = []; public ReadOnlyReactivePropertySlim Stroke { get; } diff --git a/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.Impl.cs b/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.Impl.cs index 9215e0b4d..7506579fe 100644 --- a/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.Impl.cs +++ b/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.Impl.cs @@ -28,8 +28,8 @@ private sealed class PixelPointFactory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "X", @@ -41,7 +41,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "Y", obj => ConvertTo(1, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(1, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(int.MaxValue); @@ -107,8 +107,8 @@ private sealed class PixelSizeFactory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "Width", @@ -120,7 +120,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "Height", obj => ConvertTo(1, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(1, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(int.MaxValue); @@ -186,8 +186,8 @@ private sealed class PointFactory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "X", @@ -199,7 +199,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "Y", obj => ConvertTo(1, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(1, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(float.MaxValue); @@ -265,8 +265,8 @@ private sealed class SizeFactory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "Width", @@ -278,7 +278,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "Height", obj => ConvertTo(1, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(1, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(float.MaxValue); @@ -344,8 +344,8 @@ private sealed class VectorFactory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "X", @@ -357,7 +357,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "Y", obj => ConvertTo(1, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(1, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(float.MaxValue); @@ -423,8 +423,8 @@ private sealed class Vector2Factory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "X", @@ -436,7 +436,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "Y", obj => ConvertTo(1, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(1, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(float.MaxValue); @@ -504,8 +504,8 @@ private sealed class Vector3Factory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "X", @@ -523,7 +523,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "Z", obj => ConvertTo(2, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(2, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(float.MaxValue); @@ -596,8 +596,8 @@ private sealed class PixelRectFactory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "X", @@ -621,7 +621,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "Height", obj => ConvertTo(3, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(3, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(int.MaxValue); @@ -697,8 +697,8 @@ private sealed class RectFactory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "X", @@ -722,7 +722,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "Height", obj => ConvertTo(3, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(3, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(float.MaxValue); @@ -798,8 +798,8 @@ private sealed class CornerRadiusFactory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "TopLeft", @@ -823,7 +823,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "BottomLeft", obj => ConvertTo(3, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(3, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(float.MaxValue); @@ -899,8 +899,8 @@ private sealed class ThicknessFactory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "Left", @@ -924,7 +924,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "Bottom", obj => ConvertTo(3, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(3, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(float.MaxValue); @@ -1000,8 +1000,8 @@ private sealed class Vector4Factory : GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "X", @@ -1025,7 +1025,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod "W", obj => ConvertTo(3, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(3, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(float.MaxValue); diff --git a/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.Impl.tt b/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.Impl.tt index 5b24fc625..f7a4bea54 100644 --- a/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.Impl.tt +++ b/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.Impl.tt @@ -77,8 +77,8 @@ public abstract partial class GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "<#= t.FieldX #>", @@ -90,7 +90,7 @@ public abstract partial class GraphEditorViewViewModelFactory "<#= t.FieldY #>", obj => ConvertTo(1, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(1, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(<#= t.Element #>.MaxValue); @@ -161,8 +161,8 @@ public abstract partial class GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "<#= t.FieldX #>", @@ -180,7 +180,7 @@ public abstract partial class GraphEditorViewViewModelFactory "<#= t.FieldZ #>", obj => ConvertTo(2, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(2, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(<#= t.Element #>.MaxValue); @@ -256,8 +256,8 @@ public abstract partial class GraphEditorViewViewModelFactory { protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "<#= t.FieldX #>", @@ -281,7 +281,7 @@ public abstract partial class GraphEditorViewViewModelFactory "<#= t.FieldW #>", obj => ConvertTo(3, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(3, old, value, out obj)) - }; + ]; } public override double MaxValue => double.CreateTruncating(<#= t.Element #>.MaxValue); diff --git a/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.cs b/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.cs index 128c282b3..a40e45c8c 100644 --- a/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.cs +++ b/src/Beutl/ViewModels/GraphEditorViewViewModelFactory.cs @@ -5,7 +5,7 @@ namespace Beutl.ViewModels; public abstract partial class GraphEditorViewViewModelFactory { - private static readonly Dictionary s_registry = new(); + private static readonly Dictionary s_registry = []; static GraphEditorViewViewModelFactory() { @@ -56,7 +56,7 @@ static bool IsAssignableToGenericType(Type givenType, Type genericType) public static GraphEditorViewViewModel[] CreateViews(GraphEditorViewModel parent, GraphEditorViewViewModelFactory? factory) { - return factory?.CreateViewsCore(parent) ?? Array.Empty(); + return factory?.CreateViewsCore(parent) ?? []; } protected abstract GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent); @@ -70,8 +70,8 @@ private sealed class NumberFactory : GraphEditorViewViewModelFactory protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "Self", @@ -91,7 +91,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod obj = T.CreateTruncating(value); return true; }) - }; + ]; } } @@ -99,7 +99,7 @@ private sealed class ColorFactory : GraphEditorViewViewModelFactory { private static double OECF_sRGB(double linear) { - return linear <= 0.0031308 ? linear * 12.92 : (Math.Pow(linear, 1.0 / 2.4) * 1.055 - 0.055); + return linear <= 0.0031308 ? linear * 12.92 : ((Math.Pow(linear, 1.0 / 2.4) * 1.055) - 0.055); } private static double EOCF_sRGB(double srgb) @@ -109,8 +109,8 @@ private static double EOCF_sRGB(double srgb) protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewModel parent) { - return new GraphEditorViewViewModel[] - { + return + [ new GraphEditorViewViewModel( parent, "Alpha", @@ -138,7 +138,7 @@ protected override GraphEditorViewViewModel[] CreateViewsCore(GraphEditorViewMod obj => ConvertTo(3, obj), (object? old, double value, Type _, out object? obj) => TryConvertFrom(3, old, value, out obj), Avalonia.Media.Colors.Blue) - }; + ]; } public override double MaxValue => double.CreateTruncating(byte.MaxValue); diff --git a/src/Beutl/ViewModels/InlineAnimationLayerViewModel.cs b/src/Beutl/ViewModels/InlineAnimationLayerViewModel.cs index ac12f3b60..48e666415 100644 --- a/src/Beutl/ViewModels/InlineAnimationLayerViewModel.cs +++ b/src/Beutl/ViewModels/InlineAnimationLayerViewModel.cs @@ -9,13 +9,10 @@ namespace Beutl.ViewModels; -public sealed class InlineAnimationLayerViewModel : InlineAnimationLayerViewModel +public sealed class InlineAnimationLayerViewModel( + IAbstractAnimatableProperty property, TimelineViewModel timeline, ElementViewModel element) + : InlineAnimationLayerViewModel(property, timeline, element) { - public InlineAnimationLayerViewModel(IAbstractAnimatableProperty property, TimelineViewModel timeline, ElementViewModel element) - : base(property, timeline, element) - { - } - public override void DropEasing(Easing easing, TimeSpan keyTime) { if (Property.Animation is KeyFrameAnimation kfAnimation) @@ -60,20 +57,11 @@ public override void InsertKeyFrame(Easing easing, TimeSpan keyTime) } } - private sealed class AddKeyFrameCommand : IRecordableCommand + private sealed class AddKeyFrameCommand(KeyFrames keyFrames, IKeyFrame keyFrame) : IRecordableCommand { - private readonly KeyFrames _keyFrames; - private readonly IKeyFrame _keyFrame; - - public AddKeyFrameCommand(KeyFrames keyFrames, IKeyFrame keyFrame) - { - _keyFrames = keyFrames; - _keyFrame = keyFrame; - } - public void Do() { - _keyFrames.Add(_keyFrame, out _); + keyFrames.Add(keyFrame, out _); } public void Redo() @@ -83,15 +71,15 @@ public void Redo() public void Undo() { - _keyFrames.Remove(_keyFrame); + keyFrames.Remove(keyFrame); } } } public abstract class InlineAnimationLayerViewModel : IDisposable { - private readonly CompositeDisposable _disposables = new(); - private readonly CompositeDisposable _innerDisposables = new(); + private readonly CompositeDisposable _disposables = []; + private readonly CompositeDisposable _innerDisposables = []; private readonly ReactivePropertySlim _useGlobalClock = new(true); private LayerHeaderViewModel? _lastLayerHeader; @@ -173,7 +161,7 @@ protected InlineAnimationLayerViewModel( [Obsolete("Use Element property instead.")] public ElementViewModel Layer => Element; - public CoreList Items { get; } = new(); + public CoreList Items { get; } = []; public ReactiveProperty Margin { get; } @@ -282,20 +270,14 @@ private void ClearItems() public record struct PrepareAnimationContext(Thickness Margin, Thickness LeftMargin); - private sealed class TrackedInlineLayerTopObservable : LightweightObservableBase + private sealed class TrackedInlineLayerTopObservable(InlineAnimationLayerViewModel inline) : LightweightObservableBase { - private readonly InlineAnimationLayerViewModel _inline; private IDisposable? _disposable1; private IDisposable? _disposable2; private IDisposable? _disposable3; private int _prevIndex = -1; private LayerHeaderViewModel? _prevLayerHeader; - public TrackedInlineLayerTopObservable(InlineAnimationLayerViewModel inline) - { - _inline = inline; - } - protected override void Deinitialize() { _disposable1?.Dispose(); @@ -308,10 +290,10 @@ protected override void Deinitialize() protected override void Initialize() { - _disposable1 = _inline.LayerHeader + _disposable1 = inline.LayerHeader .Subscribe(OnLayerHeaderChanged); - _disposable2 = _inline.Index.Subscribe(OnIndexChanged); + _disposable2 = inline.Index.Subscribe(OnIndexChanged); } private void OnLayerHeaderChanged(LayerHeaderViewModel? obj) @@ -348,7 +330,7 @@ private void PublishValue(IObserver? observer = null) { if (_prevLayerHeader != null) { - _prevIndex = _prevLayerHeader.Inlines.IndexOf(_inline); + _prevIndex = _prevLayerHeader.Inlines.IndexOf(inline); double value = _prevLayerHeader.CalculateInlineTop(_prevIndex) + FrameNumberHelper.LayerHeight; if (observer == null) diff --git a/src/Beutl/ViewModels/InlineKeyFrameViewModel.cs b/src/Beutl/ViewModels/InlineKeyFrameViewModel.cs index 51f8662da..7c3b500e7 100644 --- a/src/Beutl/ViewModels/InlineKeyFrameViewModel.cs +++ b/src/Beutl/ViewModels/InlineKeyFrameViewModel.cs @@ -7,7 +7,7 @@ namespace Beutl.ViewModels; public sealed class InlineKeyFrameViewModel : IDisposable { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly InlineAnimationLayerViewModel _parent; public InlineKeyFrameViewModel(IKeyFrame keyframe, IKeyFrameAnimation animation, InlineAnimationLayerViewModel parent) diff --git a/src/Beutl/ViewModels/LayerHeaderViewModel.cs b/src/Beutl/ViewModels/LayerHeaderViewModel.cs index 30168ad7f..7e2f24e2e 100644 --- a/src/Beutl/ViewModels/LayerHeaderViewModel.cs +++ b/src/Beutl/ViewModels/LayerHeaderViewModel.cs @@ -14,7 +14,7 @@ namespace Beutl.ViewModels; public sealed class LayerHeaderViewModel : IDisposable, IJsonSerializable { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; public LayerHeaderViewModel(int num, TimelineViewModel timeline) { @@ -182,20 +182,11 @@ public void SetColor(Color color) .DoAndRecord(CommandRecorder.Default); } - private sealed class SetColorCommand : IRecordableCommand + private sealed class SetColorCommand(LayerHeaderViewModel viewModel, Color color) : IRecordableCommand { - private readonly LayerHeaderViewModel _viewModel; - private Color _color; - - public SetColorCommand(LayerHeaderViewModel viewModel, Color color) - { - _viewModel = viewModel; - _color = color; - } - public void Do() { - (_color, _viewModel.Color.Value) = (_viewModel.Color.Value, _color); + (color, viewModel.Color.Value) = (viewModel.Color.Value, color); } public void Redo() diff --git a/src/Beutl/ViewModels/LibraryViewModel.cs b/src/Beutl/ViewModels/LibraryViewModel.cs index 082af0ca0..a8cac0430 100644 --- a/src/Beutl/ViewModels/LibraryViewModel.cs +++ b/src/Beutl/ViewModels/LibraryViewModel.cs @@ -23,7 +23,7 @@ public class LibraryItemViewModel public string? Type { get; init; } - public List Children { get; } = new(); + public List Children { get; } = []; public static LibraryItemViewModel CreateFromNodeRegistryItem(NodeRegistry.BaseRegistryItem registryItem, string? parentFullName = null) { @@ -232,8 +232,8 @@ public LibraryViewModel(EditViewModel editViewModel) AddAllItems(Nodes); } - public ReactiveCollection Easings { get; } = new() - { + public ReactiveCollection Easings { get; } = + [ new BackEaseIn(), new BackEaseInOut(), new BackEaseOut(), @@ -265,7 +265,7 @@ public LibraryViewModel(EditViewModel editViewModel) new SineEaseInOut(), new SineEaseOut(), new LinearEasing(), - }; + ]; public List LibraryItems { get; } @@ -273,7 +273,7 @@ public LibraryViewModel(EditViewModel editViewModel) public List> AllItems { get; } - public ReactiveCollection> SearchResult { get; } = new(); + public ReactiveCollection> SearchResult { get; } = []; public int SelectedTab { get; set; } = 2; diff --git a/src/Beutl/ViewModels/MainViewModel.cs b/src/Beutl/ViewModels/MainViewModel.cs index 63401e14b..2ed309785 100644 --- a/src/Beutl/ViewModels/MainViewModel.cs +++ b/src/Beutl/ViewModels/MainViewModel.cs @@ -61,12 +61,12 @@ public MainViewModel() WindowTitle = NameOfOpenProject.Select(v => string.IsNullOrWhiteSpace(v) ? "Beutl" : $"Beutl - {v}") .ToReadOnlyReactivePropertySlim("Beutl"); - Pages = new() - { + Pages = + [ new(EditPageExtension.Instance), new(ExtensionsPageExtension.Instance, new ExtensionsPageViewModel(_beutlClients)), new(OutputPageExtension.Instance), - }; + ]; SettingsPage = new(SettingsPageExtension.Instance, new SettingsPageViewModel(_beutlClients)); SelectedPage.Value = Pages[0]; diff --git a/src/Beutl/ViewModels/MenuBarViewModel.Files.cs b/src/Beutl/ViewModels/MenuBarViewModel.Files.cs index c9d1af18c..c9d3d061d 100644 --- a/src/Beutl/ViewModels/MenuBarViewModel.Files.cs +++ b/src/Beutl/ViewModels/MenuBarViewModel.Files.cs @@ -86,9 +86,9 @@ private void InitializeFilesCommands() public ReactiveCommandSlim OpenRecentProject { get; } = new(); - public CoreList RecentFileItems { get; } = new(); + public CoreList RecentFileItems { get; } = []; - public CoreList RecentProjectItems { get; } = new(); + public CoreList RecentProjectItems { get; } = []; public ReactiveCommandSlim Exit { get; } = new(); diff --git a/src/Beutl/ViewModels/NodeTree/NodeInputViewModel.cs b/src/Beutl/ViewModels/NodeTree/NodeInputViewModel.cs index 069297bc3..4e71dda64 100644 --- a/src/Beutl/ViewModels/NodeTree/NodeInputViewModel.cs +++ b/src/Beutl/ViewModels/NodeTree/NodeInputViewModel.cs @@ -12,7 +12,7 @@ namespace Beutl.ViewModels.NodeTree; public sealed class NodeInputViewModel : IDisposable, IPropertyEditorContextVisitor, IServiceProvider { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly string _defaultName; private NodeTreeModel _nodeTree; private NodeTreeInputViewModel _parent; @@ -57,7 +57,7 @@ public NodeInputViewModel(LayerInputNode node, int originalIndex, NodeTreeInputV public ReactiveProperty IsExpanded { get; } = new(true); - public CoreList Properties { get; } = new(); + public CoreList Properties { get; } = []; public void Remove() { diff --git a/src/Beutl/ViewModels/NodeTree/NodeTreeInputTabViewModel.cs b/src/Beutl/ViewModels/NodeTree/NodeTreeInputTabViewModel.cs index 9726abb74..975dbac1c 100644 --- a/src/Beutl/ViewModels/NodeTree/NodeTreeInputTabViewModel.cs +++ b/src/Beutl/ViewModels/NodeTree/NodeTreeInputTabViewModel.cs @@ -9,7 +9,7 @@ namespace Beutl.ViewModels.NodeTree; public sealed class NodeTreeInputTabViewModel : IToolContext { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private EditViewModel _editViewModel; public NodeTreeInputTabViewModel(EditViewModel editViewModel) diff --git a/src/Beutl/ViewModels/NodeTree/NodeTreeInputViewModel.cs b/src/Beutl/ViewModels/NodeTree/NodeTreeInputViewModel.cs index 1b8730f4d..e9bf39198 100644 --- a/src/Beutl/ViewModels/NodeTree/NodeTreeInputViewModel.cs +++ b/src/Beutl/ViewModels/NodeTree/NodeTreeInputViewModel.cs @@ -9,7 +9,7 @@ namespace Beutl.ViewModels.NodeTree; public sealed class NodeTreeInputViewModel : IDisposable, IServiceProvider { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private NodeTreeInputTabViewModel _parent; public NodeTreeInputViewModel(Element element, NodeTreeInputTabViewModel parent) @@ -70,7 +70,7 @@ public NodeTreeInputViewModel(Element element, NodeTreeInputTabViewModel parent) public ReactiveProperty UseNode { get; } - public CoreList Items { get; } = new(); + public CoreList Items { get; } = []; // NodesのIndexから、ItemsのIndexに変換。 public int ConvertFromOriginalIndex(int originalIndex) diff --git a/src/Beutl/ViewModels/NodeTree/NodeTreeTabViewModel.cs b/src/Beutl/ViewModels/NodeTree/NodeTreeTabViewModel.cs index 3407fd088..357f20e3e 100644 --- a/src/Beutl/ViewModels/NodeTree/NodeTreeTabViewModel.cs +++ b/src/Beutl/ViewModels/NodeTree/NodeTreeTabViewModel.cs @@ -60,7 +60,7 @@ public void ReadFromJson(JsonObject json) public sealed class NodeTreeTabViewModel : IToolContext { private readonly ReactiveProperty _isSelected = new(false); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private EditViewModel _editViewModel; private Element? _oldElement; @@ -119,7 +119,7 @@ public NodeTreeTabViewModel(EditViewModel editViewModel) public ReactivePropertySlim NodeTree { get; } = new(); - public CoreList Items { get; } = new(); + public CoreList Items { get; } = []; public void Dispose() { diff --git a/src/Beutl/ViewModels/NodeTree/NodeTreeViewModel.cs b/src/Beutl/ViewModels/NodeTree/NodeTreeViewModel.cs index 59b9348e6..7160a6162 100644 --- a/src/Beutl/ViewModels/NodeTree/NodeTreeViewModel.cs +++ b/src/Beutl/ViewModels/NodeTree/NodeTreeViewModel.cs @@ -11,7 +11,7 @@ namespace Beutl.ViewModels.NodeTree; public sealed class NodeTreeViewModel : IDisposable, IJsonSerializable { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; public NodeTreeViewModel(NodeTreeModel nodeTree) { @@ -40,7 +40,7 @@ public NodeTreeViewModel(NodeTreeModel nodeTree) .DisposeWith(_disposables); } - public CoreList Nodes { get; } = new(); + public CoreList Nodes { get; } = []; public ReactiveProperty Matrix { get; } = new(Avalonia.Matrix.Identity); diff --git a/src/Beutl/ViewModels/NodeTree/NodeViewModel.cs b/src/Beutl/ViewModels/NodeTree/NodeViewModel.cs index 2cc93e92b..7ece6d630 100644 --- a/src/Beutl/ViewModels/NodeTree/NodeViewModel.cs +++ b/src/Beutl/ViewModels/NodeTree/NodeViewModel.cs @@ -19,7 +19,7 @@ namespace Beutl.ViewModels.NodeTree; public sealed class NodeViewModel : IDisposable, IJsonSerializable { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly string _defaultName; public NodeViewModel(Node node) @@ -92,7 +92,7 @@ public NodeViewModel(Node node) public ReactiveCommand Delete { get; } = new(); - public CoreList Items { get; } = new(); + public CoreList Items { get; } = []; public void Dispose() { diff --git a/src/Beutl/ViewModels/NodeTree/OutputSocketViewModel.cs b/src/Beutl/ViewModels/NodeTree/OutputSocketViewModel.cs index 5cca35706..eda6c983a 100644 --- a/src/Beutl/ViewModels/NodeTree/OutputSocketViewModel.cs +++ b/src/Beutl/ViewModels/NodeTree/OutputSocketViewModel.cs @@ -2,13 +2,9 @@ namespace Beutl.ViewModels.NodeTree; -public class OutputSocketViewModel : SocketViewModel +public class OutputSocketViewModel(IOutputSocket? socket, IPropertyEditorContext? propertyEditorContext, Node node) + : SocketViewModel(socket, propertyEditorContext, node) { - public OutputSocketViewModel(IOutputSocket? socket, IPropertyEditorContext? propertyEditorContext, Node node) - : base(socket, propertyEditorContext, node) - { - } - public new IOutputSocket? Model => base.Model as IOutputSocket; protected override void OnIsConnectedChanged() diff --git a/src/Beutl/ViewModels/NodeTree/SocketViewModel.cs b/src/Beutl/ViewModels/NodeTree/SocketViewModel.cs index 733907687..438903c45 100644 --- a/src/Beutl/ViewModels/NodeTree/SocketViewModel.cs +++ b/src/Beutl/ViewModels/NodeTree/SocketViewModel.cs @@ -226,20 +226,11 @@ public void Undo() } } - private sealed class DisconnectCommand : IRecordableCommand + private sealed class DisconnectCommand(IInputSocket inputSocket, IOutputSocket outputSocket) : IRecordableCommand { - private readonly IInputSocket _inputSocket; - private readonly IOutputSocket _outputSocket; - - public DisconnectCommand(IInputSocket inputSocket, IOutputSocket outputSocket) - { - _inputSocket = inputSocket; - _outputSocket = outputSocket; - } - public void Do() { - _outputSocket.Disconnect(_inputSocket); + outputSocket.Disconnect(inputSocket); } public void Redo() @@ -249,26 +240,17 @@ public void Redo() public void Undo() { - _outputSocket.TryConnect(_inputSocket); + outputSocket.TryConnect(inputSocket); } } - private sealed class ConnectCommand : IRecordableCommand + private sealed class ConnectCommand(IInputSocket inputSocket, IOutputSocket outputSocket) : IRecordableCommand { - private readonly IInputSocket _inputSocket; - private readonly IOutputSocket _outputSocket; - - public ConnectCommand(IInputSocket inputSocket, IOutputSocket outputSocket) - { - _inputSocket = inputSocket; - _outputSocket = outputSocket; - } - public bool IsConnected { get; set; } public void Do() { - IsConnected = _outputSocket.TryConnect(_inputSocket); + IsConnected = outputSocket.TryConnect(inputSocket); } public void Redo() @@ -278,7 +260,7 @@ public void Redo() public void Undo() { - _outputSocket.Disconnect(_inputSocket); + outputSocket.Disconnect(inputSocket); } } } diff --git a/src/Beutl/ViewModels/PlayerViewModel.cs b/src/Beutl/ViewModels/PlayerViewModel.cs index 35d59c23c..474d4ffcf 100644 --- a/src/Beutl/ViewModels/PlayerViewModel.cs +++ b/src/Beutl/ViewModels/PlayerViewModel.cs @@ -31,7 +31,7 @@ public sealed class PlayerViewModel : IDisposable { private static readonly TimeSpan s_second = TimeSpan.FromSeconds(1); private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly ReactivePropertySlim _isEnabled; private readonly EditViewModel _editViewModel; private CancellationTokenSource? _cts; diff --git a/src/Beutl/ViewModels/SettingsPages/AccountSettingsPageViewModel.cs b/src/Beutl/ViewModels/SettingsPages/AccountSettingsPageViewModel.cs index 1c94021a8..a1349266d 100644 --- a/src/Beutl/ViewModels/SettingsPages/AccountSettingsPageViewModel.cs +++ b/src/Beutl/ViewModels/SettingsPages/AccountSettingsPageViewModel.cs @@ -15,7 +15,7 @@ namespace Beutl.ViewModels.SettingsPages; public sealed class AccountSettingsPageViewModel : BasePageViewModel { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly BeutlApiApplication _clients; private readonly ReactivePropertySlim _cts = new(); diff --git a/src/Beutl/ViewModels/SettingsPages/AnExtensionSettingsPageViewModel.cs b/src/Beutl/ViewModels/SettingsPages/AnExtensionSettingsPageViewModel.cs index 254efe423..f680a8acc 100644 --- a/src/Beutl/ViewModels/SettingsPages/AnExtensionSettingsPageViewModel.cs +++ b/src/Beutl/ViewModels/SettingsPages/AnExtensionSettingsPageViewModel.cs @@ -27,14 +27,14 @@ public AnExtensionSettingsPageViewModel(Extension extension) public AsyncReactiveCommand NavigateParent { get; } = new(); - public CoreList Properties { get; } = new(); + public CoreList Properties { get; } = []; private void InitializeCoreObject(ExtensionSettings obj, Func? predicate = null) { Type objType = obj.GetType(); Type wrapperType = typeof(CorePropertyImpl<>); - List cprops = PropertyRegistry.GetRegistered(objType).ToList(); + List cprops = [.. PropertyRegistry.GetRegistered(objType)]; cprops.RemoveAll(x => !(predicate?.Invoke(x, x.GetMetadata(objType)) ?? true)); List props = cprops.ConvertAll(x => { diff --git a/src/Beutl/ViewModels/SettingsPages/EditorExtensionPriorityPageViewModel.cs b/src/Beutl/ViewModels/SettingsPages/EditorExtensionPriorityPageViewModel.cs index 6f21d1dc3..75d5b7151 100644 --- a/src/Beutl/ViewModels/SettingsPages/EditorExtensionPriorityPageViewModel.cs +++ b/src/Beutl/ViewModels/SettingsPages/EditorExtensionPriorityPageViewModel.cs @@ -170,7 +170,7 @@ public EditorExtensionPriorityPageViewModel() }); } - public CoreList FileExtensions { get; } = new(); + public CoreList FileExtensions { get; } = []; public ReactivePropertySlim SelectedFileExtension { get; } = new(); @@ -180,9 +180,9 @@ public EditorExtensionPriorityPageViewModel() // EditorExtensions2: // ExtensionProvider.AllExtensionsで取得されるItems // 上のアイテムでMatchされなかったときこれが使われる。 - public CoreList EditorExtensions1 { get; } = new(); + public CoreList EditorExtensions1 { get; } = []; - public CoreList EditorExtensions2 { get; } = new(); + public CoreList EditorExtensions2 { get; } = []; public ReactiveCommand HighPriority { get; } = new(); diff --git a/src/Beutl/ViewModels/SettingsPages/StorageDetailPageViewModel.cs b/src/Beutl/ViewModels/SettingsPages/StorageDetailPageViewModel.cs index 804d813b8..bb735cb9f 100644 --- a/src/Beutl/ViewModels/SettingsPages/StorageDetailPageViewModel.cs +++ b/src/Beutl/ViewModels/SettingsPages/StorageDetailPageViewModel.cs @@ -86,7 +86,7 @@ public StorageDetailPageViewModel(AuthorizedUser user, StorageSettingsPageViewMo public string TypeString { get; } - public AvaloniaList Items { get; } = new(); + public AvaloniaList Items { get; } = []; public ReactivePropertySlim IsBusy { get; } = new(); diff --git a/src/Beutl/ViewModels/SettingsPages/TelemetrySettingsPageViewModel.cs b/src/Beutl/ViewModels/SettingsPages/TelemetrySettingsPageViewModel.cs index 4d2ce6f9b..a13309d2b 100644 --- a/src/Beutl/ViewModels/SettingsPages/TelemetrySettingsPageViewModel.cs +++ b/src/Beutl/ViewModels/SettingsPages/TelemetrySettingsPageViewModel.cs @@ -7,7 +7,7 @@ namespace Beutl.ViewModels.SettingsPages; public sealed class TelemetrySettingsPageViewModel : BasePageViewModel { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly TelemetryConfig _config; public TelemetrySettingsPageViewModel() diff --git a/src/Beutl/ViewModels/SettingsPages/ViewSettingsPageViewModel.cs b/src/Beutl/ViewModels/SettingsPages/ViewSettingsPageViewModel.cs index aeb089b4a..c0b3887a4 100644 --- a/src/Beutl/ViewModels/SettingsPages/ViewSettingsPageViewModel.cs +++ b/src/Beutl/ViewModels/SettingsPages/ViewSettingsPageViewModel.cs @@ -92,7 +92,7 @@ await nav.NavigateAsync( public IEnumerable Cultures { get; } = LocalizeService.Instance.SupportedCultures(); public ReactiveProperty UseCustomAccent { get; } - + public ReactiveProperty ListBoxColor { get; } public ReactiveProperty CustomAccentColor { get; } @@ -104,8 +104,8 @@ await nav.NavigateAsync( // https://github.com/amwx/FluentAvalonia/blob/master/samples/FAControlsGallery/ViewModels/SettingsPageViewModel.cs private static Color[] GetPredefColors() { - return new Color[] - { + return + [ Color.FromRgb(255,185,0), Color.FromRgb(255,140,0), Color.FromRgb(247,99,12), @@ -154,7 +154,7 @@ private static Color[] GetPredefColors() Color.FromRgb(82,94,84), Color.FromRgb(132,117,69), Color.FromRgb(126,115,95) - }; + ]; } private static void UpdateAppAccentColor(Color? color) diff --git a/src/Beutl/ViewModels/TimelineViewModel.cs b/src/Beutl/ViewModels/TimelineViewModel.cs index 7a34e9cc4..7c2c68166 100644 --- a/src/Beutl/ViewModels/TimelineViewModel.cs +++ b/src/Beutl/ViewModels/TimelineViewModel.cs @@ -43,9 +43,9 @@ public interface ITimelineOptionsProvider public sealed class TimelineViewModel : IToolContext { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly Subject _layerHeightChanged = new(); - private readonly Dictionary _trackerCache = new(); + private readonly Dictionary _trackerCache = []; public TimelineViewModel(EditViewModel editViewModel) { @@ -95,7 +95,7 @@ public TimelineViewModel(EditViewModel editViewModel) }, () => { - ElementViewModel[] tmp = Elements.ToArray(); + ElementViewModel[] tmp = [.. Elements]; Elements.Clear(); foreach (ElementViewModel? item in Elements.GetMarshal().Value) { @@ -116,7 +116,7 @@ public TimelineViewModel(EditViewModel editViewModel) AutoAdjustSceneDuration.Subscribe(b => editorConfig.AutoAdjustSceneDuration = b); // Todo: 設定からショートカットを変更できるようにする。 - KeyBindings = new List(); + KeyBindings = []; PlatformHotkeyConfiguration? keyConf = Application.Current?.PlatformSettings?.HotkeyConfiguration; if (keyConf != null) { @@ -173,14 +173,14 @@ private void OnAdjustDurationToCurrent() [Obsolete("Use AddElement property instead.")] public ReactiveCommand AddLayer => AddElement; - public CoreList Elements { get; } = new(); + public CoreList Elements { get; } = []; [Obsolete("Use Elements property instead.")] public CoreList Layers => Elements; - public CoreList Inlines { get; } = new(); + public CoreList Inlines { get; } = []; - public CoreList LayerHeaders { get; } = new(); + public CoreList LayerHeaders { get; } = []; public ReactiveCommand Paste { get; } = new(); @@ -583,56 +583,48 @@ internal void RaiseLayerHeightChanged(LayerHeaderViewModel value) return Elements.FirstOrDefault(x => x.Model == element); } - private sealed class TrackedLayerTopObservable : LightweightObservableBase, IDisposable + private sealed class TrackedLayerTopObservable(int layerNum, TimelineViewModel timeline) : LightweightObservableBase, IDisposable { - private readonly TimelineViewModel _timeline; - private readonly int _layerNum; private IDisposable? _disposable1; private IDisposable? _disposable2; - public TrackedLayerTopObservable(int layerNum, TimelineViewModel timeline) - { - _layerNum = layerNum; - _timeline = timeline; - } - protected override void Deinitialize() { _disposable1?.Dispose(); _disposable2?.Dispose(); - _timeline._trackerCache.Remove(_layerNum); + timeline._trackerCache.Remove(layerNum); } protected override void Initialize() { - _disposable1 = _timeline.LayerHeaders.CollectionChangedAsObservable() + _disposable1 = timeline.LayerHeaders.CollectionChangedAsObservable() .Subscribe(OnCollectionChanged); - _disposable2 = _timeline.LayerHeightChanged.Subscribe(OnLayerHeightChanged); + _disposable2 = timeline.LayerHeightChanged.Subscribe(OnLayerHeightChanged); } private void OnLayerHeightChanged(LayerHeaderViewModel obj) { - if (obj.Number.Value < _layerNum) + if (obj.Number.Value < layerNum) { - PublishNext(_timeline.CalculateLayerTop(_layerNum)); + PublishNext(timeline.CalculateLayerTop(layerNum)); } } protected override void Subscribed(IObserver observer, bool first) { - observer.OnNext(_timeline.CalculateLayerTop(_layerNum)); + observer.OnNext(timeline.CalculateLayerTop(layerNum)); } private void OnCollectionChanged(NotifyCollectionChangedEventArgs obj) { if (obj.Action == NotifyCollectionChangedAction.Move) { - if (_layerNum != obj.OldStartingIndex - && ((_layerNum > obj.OldStartingIndex && _layerNum <= obj.NewStartingIndex) - || (_layerNum < obj.OldStartingIndex && _layerNum >= obj.NewStartingIndex))) + if (layerNum != obj.OldStartingIndex + && ((layerNum > obj.OldStartingIndex && layerNum <= obj.NewStartingIndex) + || (layerNum < obj.OldStartingIndex && layerNum >= obj.NewStartingIndex))) { - PublishNext(_timeline.CalculateLayerTop(_layerNum)); + PublishNext(timeline.CalculateLayerTop(layerNum)); } } } diff --git a/src/Beutl/ViewModels/Tools/ObjectPropertyEditorViewModel.cs b/src/Beutl/ViewModels/Tools/ObjectPropertyEditorViewModel.cs index 3134a8d3b..cb20ce0df 100644 --- a/src/Beutl/ViewModels/Tools/ObjectPropertyEditorViewModel.cs +++ b/src/Beutl/ViewModels/Tools/ObjectPropertyEditorViewModel.cs @@ -9,7 +9,7 @@ namespace Beutl.ViewModels.Tools; public sealed class ObjectPropertyEditorViewModel : IToolContext { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private readonly EditViewModel _viewModel; // インデックスが大きい方が新しい private readonly List _cache = new(8); diff --git a/src/Beutl/ViewModels/Tools/SceneSettingsTabViewModel.cs b/src/Beutl/ViewModels/Tools/SceneSettingsTabViewModel.cs index 80f7eafd5..257bb641f 100644 --- a/src/Beutl/ViewModels/Tools/SceneSettingsTabViewModel.cs +++ b/src/Beutl/ViewModels/Tools/SceneSettingsTabViewModel.cs @@ -11,7 +11,7 @@ namespace Beutl.ViewModels.Tools; public sealed class SceneSettingsTabViewModel : IToolContext { - private readonly CompositeDisposable _disposable = new(); + private readonly CompositeDisposable _disposable = []; private EditViewModel _editViewModel; private Scene _scene; @@ -148,27 +148,15 @@ public void ReadFromJson(JsonObject json) return null; } - private sealed class UpdateSceneSettingsCommand : IRecordableCommand + private sealed class UpdateSceneSettingsCommand(PixelSize newSize, TimeSpan newDuration, Scene scene) : IRecordableCommand { - private readonly PixelSize _newSize; - private readonly PixelSize _oldSize; - private readonly TimeSpan _newDuration; - private readonly TimeSpan _oldDuration; - private readonly Scene _scene; - - public UpdateSceneSettingsCommand(PixelSize newSize, TimeSpan newDuration, Scene scene) - { - _newSize = newSize; - _oldSize = new(scene.Width, scene.Height); - _newDuration = newDuration; - _oldDuration = scene.Duration; - _scene = scene; - } + private readonly PixelSize _oldSize = new(scene.Width, scene.Height); + private readonly TimeSpan _oldDuration = scene.Duration; public void Do() { - _scene.Initialize(_newSize.Width, _newSize.Height); - _scene.Duration = _newDuration; + scene.Initialize(newSize.Width, newSize.Height); + scene.Duration = newDuration; } public void Redo() @@ -178,8 +166,8 @@ public void Redo() public void Undo() { - _scene.Initialize(_oldSize.Width, _oldSize.Height); - _scene.Duration = _oldDuration; + scene.Initialize(_oldSize.Width, _oldSize.Height); + scene.Duration = _oldDuration; } } } diff --git a/src/Beutl/ViewModels/Tools/SourceOperatorViewModel.cs b/src/Beutl/ViewModels/Tools/SourceOperatorViewModel.cs index b5f910bf1..3c4f82699 100644 --- a/src/Beutl/ViewModels/Tools/SourceOperatorViewModel.cs +++ b/src/Beutl/ViewModels/Tools/SourceOperatorViewModel.cs @@ -53,7 +53,7 @@ private void Properties_CollectionChanged(object? sender, NotifyCollectionChange public ReactiveProperty IsEnabled { get; } - public CoreList Properties { get; } = new(); + public CoreList Properties { get; } = []; public IReadOnlyReactiveProperty IsDummy { get; } @@ -125,7 +125,7 @@ public void Dispose() private void Init() { - List props = Model.Properties.ToList(); + List props = [.. Model.Properties]; var tempItems = new List(props.Count); IAbstractProperty[]? foundItems; PropertyEditorExtension? extension; @@ -228,24 +228,11 @@ public void SetJsonString(string? str) } } - private sealed class ReplaceItemCommand : IRecordableCommand + private sealed class ReplaceItemCommand(IList list, int index, SourceOperator item, SourceOperator oldItem) : IRecordableCommand { - private readonly IList _list; - private readonly int _index; - private readonly SourceOperator _newItem; - private readonly SourceOperator _oldItem; - - public ReplaceItemCommand(IList list, int index, SourceOperator item, SourceOperator oldItem) - { - _list = list; - _index = index; - _newItem = item; - _oldItem = oldItem; - } - public void Do() { - _list[_index] = _newItem; + list[index] = item; } public void Redo() @@ -255,7 +242,7 @@ public void Redo() public void Undo() { - _list[_index] = _oldItem; + list[index] = oldItem; } } } diff --git a/src/Beutl/ViewModels/Tools/SourceOperatorsTabViewModel.cs b/src/Beutl/ViewModels/Tools/SourceOperatorsTabViewModel.cs index c44eaf3b3..e8565a8bd 100644 --- a/src/Beutl/ViewModels/Tools/SourceOperatorsTabViewModel.cs +++ b/src/Beutl/ViewModels/Tools/SourceOperatorsTabViewModel.cs @@ -118,7 +118,7 @@ void RemoveItems(CoreList items, int index, int count) [Obsolete("Use Element property instead.")] public ReactiveProperty Layer => Element; - public CoreList Items { get; } = new(); + public CoreList Items { get; } = []; public ToolTabExtension Extension => SourceOperatorsTabExtension.Instance; diff --git a/src/Beutl/Views/Cache.cs b/src/Beutl/Views/Cache.cs index 4d9a9e0d2..adfe8b4da 100644 --- a/src/Beutl/Views/Cache.cs +++ b/src/Beutl/Views/Cache.cs @@ -1,14 +1,9 @@ namespace Beutl.Views; -internal readonly struct Cache +internal readonly struct Cache(int size) where T : class { - public readonly T?[] Items; - - public Cache(int size) - { - Items = new T?[size]; - } + public readonly T?[] Items = new T?[size]; public bool Set(T item) { diff --git a/src/Beutl/Views/EditView.axaml.MouseControl.cs b/src/Beutl/Views/EditView.axaml.MouseControl.cs index c791e8b67..254ffdbb4 100644 --- a/src/Beutl/Views/EditView.axaml.MouseControl.cs +++ b/src/Beutl/Views/EditView.axaml.MouseControl.cs @@ -43,23 +43,15 @@ private static double Length(AvaPoint point) return Math.Sqrt((point.X * point.X) + (point.Y * point.Y)); } - private sealed class KeyFrameState + private sealed class KeyFrameState(KeyFrame? previous, KeyFrame? next) { - public KeyFrameState(KeyFrame? previous, KeyFrame? next) - { - Previous = previous; - Next = next; - OldPreviousValue = previous?.Value ?? 0; - OldNextValue = next?.Value ?? 0; - } - - public KeyFrame? Previous { get; } + public KeyFrame? Previous { get; } = previous; - public KeyFrame? Next { get; } + public KeyFrame? Next { get; } = next; - public float OldPreviousValue { get; } + public float OldPreviousValue { get; } = previous?.Value ?? 0; - public float OldNextValue { get; } + public float OldNextValue { get; } = next?.Value ?? 0; public IRecordableCommand? CreateCommand() { diff --git a/src/Beutl/Views/EditView.axaml.cs b/src/Beutl/Views/EditView.axaml.cs index c1e8ce042..12c010e37 100644 --- a/src/Beutl/Views/EditView.axaml.cs +++ b/src/Beutl/Views/EditView.axaml.cs @@ -27,9 +27,9 @@ public sealed partial class EditView : UserControl private static readonly Binding s_isSelectedBinding = new("Context.IsSelected.Value", BindingMode.TwoWay); private static readonly Binding s_headerBinding = new("Context.Header"); private static readonly ILogger s_logger = Log.ForContext(); - private readonly AvaloniaList _bottomTabItems = new(); - private readonly AvaloniaList _rightTabItems = new(); - private readonly CompositeDisposable _disposables = new(); + private readonly AvaloniaList _bottomTabItems = []; + private readonly AvaloniaList _rightTabItems = []; + private readonly CompositeDisposable _disposables = []; private Image? _image; public EditView() diff --git a/src/Beutl/Views/Editors/ListEditor.axaml.cs b/src/Beutl/Views/Editors/ListEditor.axaml.cs index ec6ac88f1..cdea40891 100644 --- a/src/Beutl/Views/Editors/ListEditor.axaml.cs +++ b/src/Beutl/Views/Editors/ListEditor.axaml.cs @@ -414,10 +414,10 @@ await Task.Run(async () => Type[]? availableTypes = null; if (itemType.IsSealed - && (itemType.GetConstructor(Array.Empty()) != null + && (itemType.GetConstructor([]) != null || itemType.GetConstructors().Length == 0)) { - availableTypes = new[] { itemType }; + availableTypes = [itemType]; } else { @@ -426,7 +426,7 @@ await Task.Run(async () => .Where(x => !x.IsAbstract && x.IsPublic && x.IsAssignableTo(itemType) - && (itemType.GetConstructor(Array.Empty()) != null + && (itemType.GetConstructor([]) != null || itemType.GetConstructors().Length == 0)) .ToArray(); } diff --git a/src/Beutl/Views/Editors/NavigateButton.axaml.cs b/src/Beutl/Views/Editors/NavigateButton.axaml.cs index a61c4f92e..fa269dbaf 100644 --- a/src/Beutl/Views/Editors/NavigateButton.axaml.cs +++ b/src/Beutl/Views/Editors/NavigateButton.axaml.cs @@ -81,7 +81,7 @@ await Task.Run(async () => .Where(x => !x.IsAbstract && x.IsPublic && x.IsAssignableTo(type) - && x.GetConstructor(Array.Empty()) != null) + && x.GetConstructor([]) != null) .ToArray(); Type? type2 = null; ConstructorInfo? constructorInfo = null; @@ -123,7 +123,7 @@ await Task.Run(async () => type2 = type; } - constructorInfo = type2?.GetConstructor(Array.Empty()); + constructorInfo = type2?.GetConstructor([]); if (constructorInfo?.Invoke(null) is T typed) { diff --git a/src/Beutl/Views/ElementView.axaml.cs b/src/Beutl/Views/ElementView.axaml.cs index b203e4368..b4fd11c32 100644 --- a/src/Beutl/Views/ElementView.axaml.cs +++ b/src/Beutl/Views/ElementView.axaml.cs @@ -31,7 +31,7 @@ namespace Beutl.Views; public sealed partial class ElementView : UserControl { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private Timeline? _timeline; private TimeSpan _pointerPosition; private static ColorPickerFlyout? s_colorPickerFlyout; @@ -577,7 +577,7 @@ private async void OnBorderPointerReleased(object? sender, PointerReleasedEventA int newIndex = viewModel.Timeline.ToLayerNumber(viewModel.Margin.Value); int deltaIndex = newIndex - viewModel.Model.ZIndex; - viewModel.Scene.MoveChildren(deltaIndex, deltaStart, elems.ToArray()) + viewModel.Scene.MoveChildren(deltaIndex, deltaStart, [.. elems]) .DoAndRecord(CommandRecorder.Default); foreach (var (item, context) in animations) diff --git a/src/Beutl/Views/GraphEditorView.axaml.cs b/src/Beutl/Views/GraphEditorView.axaml.cs index e4c0fa9de..d4c955a29 100644 --- a/src/Beutl/Views/GraphEditorView.axaml.cs +++ b/src/Beutl/Views/GraphEditorView.axaml.cs @@ -21,7 +21,7 @@ namespace Beutl.Views; public partial class GraphEditorView : UserControl { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private bool _pressed; private TimeSpan _lastRightClickPoint; private TimeSpan _pointerFrame; diff --git a/src/Beutl/Views/LayerHeader.axaml.cs b/src/Beutl/Views/LayerHeader.axaml.cs index f4ef98319..da094b467 100644 --- a/src/Beutl/Views/LayerHeader.axaml.cs +++ b/src/Beutl/Views/LayerHeader.axaml.cs @@ -26,7 +26,7 @@ public static readonly DirectProperty PositionYProperty private Timeline? _timeline; private Point _startRel; private Point _start; - private ElementViewModel[] _elements = Array.Empty(); + private ElementViewModel[] _elements = []; private int _newLayer; private double _positionY; @@ -96,7 +96,7 @@ private void Border_PointerReleased(object? sender, PointerReleasedEventArgs e) int newLayerNum = _newLayer; int oldLayerNum = ViewModel.Number.Value; new MoveLayerCommand(ViewModel, newLayerNum, oldLayerNum, _elements).DoAndRecord(CommandRecorder.Default); - _elements = Array.Empty(); + _elements = []; } private void Border_PointerPressed(object? sender, PointerPressedEventArgs e) @@ -147,7 +147,7 @@ public MoveLayerCommand(LayerHeaderViewModel viewModel, int newLayerNum, int old _newLayerNum = newLayerNum; _oldLayerNum = oldLayerNum; _items1 = items; - _items2 = new(); + _items2 = []; CoreListMarshal span1 = _viewModel.Timeline.Elements.GetMarshal(); CoreListMarshal span2 = _viewModel.Timeline.LayerHeaders.GetMarshal(); @@ -161,7 +161,7 @@ public MoveLayerCommand(LayerHeaderViewModel viewModel, int newLayerNum, int old } } - _viewModels = new List(); + _viewModels = []; foreach (LayerHeaderViewModel item in span2.Value) { if (item.Number.Value != oldLayerNum diff --git a/src/Beutl/Views/MainView.axaml.InitializeMenuBar.cs b/src/Beutl/Views/MainView.axaml.InitializeMenuBar.cs index ea9bb0fec..ea3fcb311 100644 --- a/src/Beutl/Views/MainView.axaml.InitializeMenuBar.cs +++ b/src/Beutl/Views/MainView.axaml.InitializeMenuBar.cs @@ -23,8 +23,8 @@ namespace Beutl.Views; public partial class MainView { - private readonly AvaloniaList _rawRecentFileItems = new(); - private readonly AvaloniaList _rawRecentProjItems = new(); + private readonly AvaloniaList _rawRecentFileItems = []; + private readonly AvaloniaList _rawRecentProjItems = []; private readonly Cache _menuItemCache = new(4); private void InitializeCommands(MainViewModel viewModel) diff --git a/src/Beutl/Views/MainView.axaml.InitializePages.cs b/src/Beutl/Views/MainView.axaml.InitializePages.cs index 2d389a2a1..8b404e125 100644 --- a/src/Beutl/Views/MainView.axaml.InitializePages.cs +++ b/src/Beutl/Views/MainView.axaml.InitializePages.cs @@ -39,7 +39,7 @@ public Control GetPageFromObject(object target) } private static readonly Binding s_headerBinding = new("Context.Header"); - private readonly AvaloniaList _navigationItems = new(); + private readonly AvaloniaList _navigationItems = []; private NavigationTransitionInfo? _navigationTransition; private void NavigationView_ItemInvoked(object? sender, NavigationViewItemInvokedEventArgs e) diff --git a/src/Beutl/Views/MainView.axaml.cs b/src/Beutl/Views/MainView.axaml.cs index 7ad9b7841..1a57f641a 100644 --- a/src/Beutl/Views/MainView.axaml.cs +++ b/src/Beutl/Views/MainView.axaml.cs @@ -29,7 +29,7 @@ namespace Beutl.Views; public sealed partial class MainView : UserControl { private readonly ILogger _logger = Log.ForContext(); - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; public MainView() { diff --git a/src/Beutl/Views/NodeTree/NodeTreeView.axaml.cs b/src/Beutl/Views/NodeTree/NodeTreeView.axaml.cs index 2701c5868..46dd61cdc 100644 --- a/src/Beutl/Views/NodeTree/NodeTreeView.axaml.cs +++ b/src/Beutl/Views/NodeTree/NodeTreeView.axaml.cs @@ -15,11 +15,11 @@ namespace Beutl.Views.NodeTree; public partial class NodeTreeView : UserControl { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private Point _rightClickedPosition; internal Point _leftClickedPosition; private bool _rangeSelectionPressed; - private List<(NodeView Node, bool IsSelectedOriginal)> _rangeSelection = new(); + private List<(NodeView Node, bool IsSelectedOriginal)> _rangeSelection = []; private bool _matrixUpdating; public NodeTreeView() diff --git a/src/Beutl/Views/NodeTree/SocketPoint.cs b/src/Beutl/Views/NodeTree/SocketPoint.cs index fee38ade2..198bcdae3 100644 --- a/src/Beutl/Views/NodeTree/SocketPoint.cs +++ b/src/Beutl/Views/NodeTree/SocketPoint.cs @@ -15,17 +15,11 @@ namespace Beutl.Views.NodeTree; -public class SocketConnectRequestedEventArgs : EventArgs +public class SocketConnectRequestedEventArgs(SocketViewModel target, bool isConnected) : EventArgs { - public SocketConnectRequestedEventArgs(SocketViewModel target, bool isConnected) - { - Target = target; - IsConnected = isConnected; - } - - public SocketViewModel Target { get; } + public SocketViewModel Target { get; } = target; - public bool IsConnected { get; set; } + public bool IsConnected { get; set; } = isConnected; } public sealed class ConnectionLine : Line diff --git a/src/Beutl/Views/NodeTree/SocketView.axaml.cs b/src/Beutl/Views/NodeTree/SocketView.axaml.cs index aac5aa784..1488c580c 100644 --- a/src/Beutl/Views/NodeTree/SocketView.axaml.cs +++ b/src/Beutl/Views/NodeTree/SocketView.axaml.cs @@ -17,7 +17,7 @@ namespace Beutl.Views.NodeTree; public partial class SocketView : UserControl { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private SocketPoint? _socketPt; private NodeView? _nodeView; private Canvas? _canvas; diff --git a/src/Beutl/Views/Timeline.axaml.cs b/src/Beutl/Views/Timeline.axaml.cs index f51ea8634..d66dadc15 100644 --- a/src/Beutl/Views/Timeline.axaml.cs +++ b/src/Beutl/Views/Timeline.axaml.cs @@ -35,9 +35,9 @@ internal enum MouseFlags internal MouseFlags _mouseFlag = MouseFlags.Free; internal TimeSpan _pointerFrame; private TimelineViewModel? _viewModel; - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; private ElementView? _selectedElement; - private readonly List<(ElementViewModel Element, bool IsSelectedOriginal)> _rangeSelection = new(); + private readonly List<(ElementViewModel Element, bool IsSelectedOriginal)> _rangeSelection = []; public Timeline() { diff --git a/src/Beutl/Views/Tools/SceneSettingsTab.axaml.cs b/src/Beutl/Views/Tools/SceneSettingsTab.axaml.cs index c991f5574..e57108993 100644 --- a/src/Beutl/Views/Tools/SceneSettingsTab.axaml.cs +++ b/src/Beutl/Views/Tools/SceneSettingsTab.axaml.cs @@ -8,7 +8,7 @@ namespace Beutl.Views.Tools; public partial class SceneSettingsTab : UserControl { - private readonly CompositeDisposable _disposables = new(); + private readonly CompositeDisposable _disposables = []; public SceneSettingsTab() { diff --git a/src/Beutl/Views/Tools/SourceOperatorView.axaml.cs b/src/Beutl/Views/Tools/SourceOperatorView.axaml.cs index 4633ec22e..b73e80533 100644 --- a/src/Beutl/Views/Tools/SourceOperatorView.axaml.cs +++ b/src/Beutl/Views/Tools/SourceOperatorView.axaml.cs @@ -18,14 +18,14 @@ public sealed partial class SourceOperatorView : UserControl public SourceOperatorView() { InitializeComponent(); - Interaction.SetBehaviors(this, new BehaviorCollection - { + Interaction.SetBehaviors(this, + [ new _DragBehavior() { Orientation = Orientation.Vertical, DragControl = dragBorder }, - }); + ]); AddHandler(DragDrop.DragOverEvent, DragOver); AddHandler(DragDrop.DropEvent, Drop); } diff --git a/tests/Beutl.Engine.UnitTests/ShapeTests.cs b/tests/Beutl.Engine.UnitTests/ShapeTests.cs index 8986d6b5b..4c5a31ae5 100644 --- a/tests/Beutl.Engine.UnitTests/ShapeTests.cs +++ b/tests/Beutl.Engine.UnitTests/ShapeTests.cs @@ -59,10 +59,7 @@ public void DrawRectangleWithPen() Brush = Brushes.White, Thickness = 10, StrokeCap = StrokeCap.Round, - DashArray = new CoreList() - { - 2 - }, + DashArray = [2], } }; diff --git a/tests/Beutl.Engine.UnitTests/StyleTests.cs b/tests/Beutl.Engine.UnitTests/StyleTests.cs index bed036a62..711fcd5d0 100644 --- a/tests/Beutl.Engine.UnitTests/StyleTests.cs +++ b/tests/Beutl.Engine.UnitTests/StyleTests.cs @@ -49,12 +49,7 @@ public void Setup() } }; - _styles1 = new Style[] - { - style1, - style2, - style3 - }; + _styles1 = [style1, style2, style3]; _obj2 = new RectShape { @@ -83,11 +78,7 @@ public void Setup() } }; - _styles2 = new Style[] - { - style1, - style2, - }; + _styles2 = [style1, style2]; } [Test] diff --git a/tests/Beutl.Engine.UnitTests/TextElementsTests.cs b/tests/Beutl.Engine.UnitTests/TextElementsTests.cs index afa39a6cf..c2fb973fc 100644 --- a/tests/Beutl.Engine.UnitTests/TextElementsTests.cs +++ b/tests/Beutl.Engine.UnitTests/TextElementsTests.cs @@ -82,8 +82,8 @@ public void Parse() [Test] public void LinesEnumerator() { - var items = new TextElements(new TextElement[] - { + var items = new TextElements( + [ new TextElement() { Size = 72, @@ -99,7 +99,7 @@ public void LinesEnumerator() Size = 56, Text = "\nMNO" } - }); + ]); foreach (Span _ in items.Lines) { diff --git a/tests/Beutl.Engine.UnitTests/TypefaceProvider.cs b/tests/Beutl.Engine.UnitTests/TypefaceProvider.cs index 87ad22748..4423c1fda 100644 --- a/tests/Beutl.Engine.UnitTests/TypefaceProvider.cs +++ b/tests/Beutl.Engine.UnitTests/TypefaceProvider.cs @@ -12,8 +12,8 @@ static TypefaceProvider() GlobalConfiguration.Instance.Save(Path.Combine(ArtifactProvider.GetArtifactDirectory(), "settings.json")); GlobalConfiguration.Instance.FontConfig.FontDirectories.Clear(); Assembly asm = typeof(TypefaceProvider).Assembly; - string[] array = new string[] - { + string[] array = + [ "NotoSansJP-Black.otf", "NotoSansJP-Bold.otf", "NotoSansJP-Light.otf", @@ -22,7 +22,7 @@ static TypefaceProvider() "NotoSansJP-Thin.otf", "Roboto-Medium.ttf", "Roboto-Regular.ttf", - }; + ]; foreach (string item in array) { diff --git a/tests/KeySplineEditor/MainWindow.axaml.cs b/tests/KeySplineEditor/MainWindow.axaml.cs index 0572f740b..dc4539b9e 100644 --- a/tests/KeySplineEditor/MainWindow.axaml.cs +++ b/tests/KeySplineEditor/MainWindow.axaml.cs @@ -122,11 +122,8 @@ private void SetControlPoint(Thickness ctrlPt1, Thickness ctrlPt2) _keySpline.ControlPointY2 = Math.Clamp(Math.Abs(ctrlPt2.Top / height - 1), 0, 1); } - private sealed class KeySplineDrawing : Control + private sealed class KeySplineDrawing(Panel panel, KeySpline keySpline) : Control { - private readonly Panel _panel; - private readonly KeySpline _keySpline; - private readonly Pen _pen = new() { Brush = Brushes.DarkGray, @@ -135,15 +132,9 @@ private sealed class KeySplineDrawing : Control Thickness = 2.5, }; - public KeySplineDrawing(Panel panel, KeySpline keySpline) - { - _panel = panel; - _keySpline = keySpline; - } - public override void Render(DrawingContext context) { - Size size = _panel.Bounds.Size; + Size size = panel.Bounds.Size; var geometry = new StreamGeometry(); using (StreamGeometryContext ctxt = geometry.Open()) @@ -153,8 +144,8 @@ public override void Render(DrawingContext context) ctxt.BeginFigure(new Point(0, height), false); ctxt.CubicBezierTo( - new Point(_keySpline.ControlPointX1 * width, (1 - _keySpline.ControlPointY1) * height), - new Point(_keySpline.ControlPointX2 * width, (1 - _keySpline.ControlPointY2) * height), + new Point(keySpline.ControlPointX1 * width, (1 - keySpline.ControlPointY1) * height), + new Point(keySpline.ControlPointX2 * width, (1 - keySpline.ControlPointY2) * height), new Point(width, 0)); ctxt.EndFigure(false); diff --git a/tests/PackageSample/ChoicesProviderSample/EditWellKnownSizeTabViewModel.cs b/tests/PackageSample/ChoicesProviderSample/EditWellKnownSizeTabViewModel.cs index 185dfa8a6..fdccd7ac6 100644 --- a/tests/PackageSample/ChoicesProviderSample/EditWellKnownSizeTabViewModel.cs +++ b/tests/PackageSample/ChoicesProviderSample/EditWellKnownSizeTabViewModel.cs @@ -6,16 +6,9 @@ namespace PackageSample; -public sealed class EditWellKnownSizeTabViewModel : IToolContext +public sealed class EditWellKnownSizeTabViewModel(ToolTabExtension extension) : IToolContext { - public EditWellKnownSizeTabViewModel(ToolTabExtension extension) - { - Extension = extension; - AddScreen = new AddWellKnownSizeScreenViewModel(); - RemoveScreen = new RemoveWellKnownSizeScreenViewModel(); - } - - public ToolTabExtension Extension { get; } + public ToolTabExtension Extension { get; } = extension; public IReactiveProperty IsSelected { get; } = new ReactivePropertySlim(); @@ -23,9 +16,9 @@ public EditWellKnownSizeTabViewModel(ToolTabExtension extension) public ToolTabExtension.TabPlacement Placement => ToolTabExtension.TabPlacement.Right; - public AddWellKnownSizeScreenViewModel AddScreen { get; } - - public RemoveWellKnownSizeScreenViewModel RemoveScreen { get; } + public AddWellKnownSizeScreenViewModel AddScreen { get; } = new AddWellKnownSizeScreenViewModel(); + + public RemoveWellKnownSizeScreenViewModel RemoveScreen { get; } = new RemoveWellKnownSizeScreenViewModel(); public void Dispose() { diff --git a/tests/PackageSample/ChoicesProviderSample/WellKnownSizesProvider.cs b/tests/PackageSample/ChoicesProviderSample/WellKnownSizesProvider.cs index 7be85593b..3626b6320 100644 --- a/tests/PackageSample/ChoicesProviderSample/WellKnownSizesProvider.cs +++ b/tests/PackageSample/ChoicesProviderSample/WellKnownSizesProvider.cs @@ -6,12 +6,12 @@ namespace PackageSample; public sealed class WellKnownSizesProvider : IChoicesProvider { - private static readonly CoreList s_choices = new() - { + private static readonly CoreList s_choices = + [ new("WQHD", new(2560, 1440)), new("Full HD", new(1920, 1080)), new("HD", new(1280, 720)) - }; + ]; public static void AddChoice(string name, PixelSize size) { diff --git a/tests/PackageSample/SSETExtenison.cs b/tests/PackageSample/SSETExtenison.cs index ccbf45e3c..b87ff84b5 100644 --- a/tests/PackageSample/SSETExtenison.cs +++ b/tests/PackageSample/SSETExtenison.cs @@ -40,17 +40,11 @@ public override bool TryCreateContext(IEditorContext editorContext, [NotNullWhen return true; } - private sealed class Context : IToolContext + private sealed class Context(ToolTabExtension extension) : IToolContext { - public Context(ToolTabExtension extension) - { - Extension = extension; - IsSelected = new ReactiveProperty(); - } - - public ToolTabExtension Extension { get; } + public ToolTabExtension Extension { get; } = extension; - public IReactiveProperty IsSelected { get; } + public IReactiveProperty IsSelected { get; } = new ReactiveProperty(); public string Header => "Sample tab"; diff --git a/tests/PackageSample/SampleEditorExtension.cs b/tests/PackageSample/SampleEditorExtension.cs index b581cfd33..c1568104c 100644 --- a/tests/PackageSample/SampleEditorExtension.cs +++ b/tests/PackageSample/SampleEditorExtension.cs @@ -61,17 +61,13 @@ public bool OpenToolTab(IToolContext item) return false; } - private sealed class CommandsImpl : IKnownEditorCommands + private sealed class CommandsImpl(TextEditorContext context) : IKnownEditorCommands { - private readonly TextEditorContext _context; - - public CommandsImpl(TextEditorContext context) => _context = context; - public async ValueTask OnSave() { try { - await File.WriteAllTextAsync(_context.EdittingFile, _context.Text.Value); + await File.WriteAllTextAsync(context.EdittingFile, context.Text.Value); return true; } catch diff --git a/tests/PackageSample/SamplePageExtension.cs b/tests/PackageSample/SamplePageExtension.cs index 4471df9cd..5b02a1686 100644 --- a/tests/PackageSample/SamplePageExtension.cs +++ b/tests/PackageSample/SamplePageExtension.cs @@ -8,11 +8,9 @@ namespace PackageSample; -public sealed class SamplePageViewModel : IPageContext +public sealed class SamplePageViewModel(SamplePageExtension extension) : IPageContext { - public SamplePageViewModel(SamplePageExtension extension) => Extension = extension; - - public PageExtension Extension { get; } + public PageExtension Extension { get; } = extension; public string Header => "Mail"; From 5dd6882ff2b1c04e297d54c4b447409c04127778 Mon Sep 17 00:00:00 2001 From: indigo-san Date: Sun, 31 Dec 2023 18:22:58 +0900 Subject: [PATCH 2/4] =?UTF-8?q?=E4=BE=8B=E5=A4=96=E3=81=AE=E3=82=B9?= =?UTF-8?q?=E3=83=AD=E3=83=BC=E3=81=A7ThrowIf=E7=B3=BB=E3=81=AE=E3=83=A1?= =?UTF-8?q?=E3=82=BD=E3=83=83=E3=83=89=E3=82=92=E4=BD=BF=E3=81=86=E3=82=88?= =?UTF-8?q?=E3=81=86=E3=81=AB=E3=81=97=E3=81=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Beutl.Core/Collections/CoreList.cs | 5 +- src/Beutl.Core/CoreProperty.cs | 5 +- src/Beutl.Engine/Audio/Effects/Delay.cs | 3 +- src/Beutl.Engine/Audio/IAudio.cs | 3 +- .../Audio/Platforms/OpenAL/AudioContext.cs | 5 +- .../Graphics/CanvasPushedState.cs | 12 +-- .../FilterEffects/FilterEffectActivator.cs | 96 ++++++++----------- src/Beutl.Engine/Graphics/ImmediateCanvas.cs | 95 +++++++++--------- .../Graphics/Shapes/TextElements.cs | 5 +- .../Graphics/Shapes/TextElementsBuilder.cs | 4 +- src/Beutl.Engine/Media/Bitmap.cs | 5 +- src/Beutl.Engine/Media/Music/Pcm.cs | 2 +- src/Beutl.Engine/Media/Source/BitmapSource.cs | 3 +- src/Beutl.Engine/Media/Source/Counter.cs | 9 +- src/Beutl.Engine/Media/Source/SoundSource.cs | 3 +- src/Beutl.Engine/Media/Source/VideoSource.cs | 3 +- .../ProjectSystem/TimelineOptions.cs | 9 +- .../SceneGraphicsEvaluator.cs | 13 ++- .../PooledArrayBufferWriter.cs | 14 +-- 19 files changed, 123 insertions(+), 171 deletions(-) diff --git a/src/Beutl.Core/Collections/CoreList.cs b/src/Beutl.Core/Collections/CoreList.cs index 7c6d0d3a1..8de20699d 100644 --- a/src/Beutl.Core/Collections/CoreList.cs +++ b/src/Beutl.Core/Collections/CoreList.cs @@ -508,10 +508,7 @@ void IList.RemoveAt(int index) void ICollection.CopyTo(Array array, int index) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (array.Rank != 1) { diff --git a/src/Beutl.Core/CoreProperty.cs b/src/Beutl.Core/CoreProperty.cs index 213d6b5bc..56377fa66 100644 --- a/src/Beutl.Core/CoreProperty.cs +++ b/src/Beutl.Core/CoreProperty.cs @@ -156,10 +156,7 @@ public void OverrideMetadata(Type type, CorePropertyMetadata metadata) private TMetadata? GetMetadataWithOverrides(Type type) where TMetadata : ICorePropertyMetadata { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); if (_metadataCache.TryGetValue(type, out ICorePropertyMetadata? result) && result is TMetadata resultT) { diff --git a/src/Beutl.Engine/Audio/Effects/Delay.cs b/src/Beutl.Engine/Audio/Effects/Delay.cs index 5e9b9a8cc..0b6adeb0f 100644 --- a/src/Beutl.Engine/Audio/Effects/Delay.cs +++ b/src/Beutl.Engine/Audio/Effects/Delay.cs @@ -72,8 +72,7 @@ public void Dispose() private void ThrowIfDisposed() { - if (_disposedValue) - throw new ObjectDisposedException(GetType().Name); + ObjectDisposedException.ThrowIf(_disposedValue, this); } } diff --git a/src/Beutl.Engine/Audio/IAudio.cs b/src/Beutl.Engine/Audio/IAudio.cs index 617fef787..4eeed8cc2 100644 --- a/src/Beutl.Engine/Audio/IAudio.cs +++ b/src/Beutl.Engine/Audio/IAudio.cs @@ -44,8 +44,7 @@ public TimeSpan Offset private void VerifyAccess() { - if (IsDisposed) - throw new ObjectDisposedException(nameof(Audio)); + ObjectDisposedException.ThrowIf(IsDisposed, this); } public void Dispose() diff --git a/src/Beutl.Engine/Audio/Platforms/OpenAL/AudioContext.cs b/src/Beutl.Engine/Audio/Platforms/OpenAL/AudioContext.cs index e7034f5e0..73df77b7f 100644 --- a/src/Beutl.Engine/Audio/Platforms/OpenAL/AudioContext.cs +++ b/src/Beutl.Engine/Audio/Platforms/OpenAL/AudioContext.cs @@ -67,10 +67,7 @@ internal void CheckError() private void ThrowIfDisposed() { - if (IsDisposed) - { - throw new ObjectDisposedException(GetType().Name); - } + ObjectDisposedException.ThrowIf(IsDisposed, this); } public void MakeCurrent() diff --git a/src/Beutl.Engine/Graphics/CanvasPushedState.cs b/src/Beutl.Engine/Graphics/CanvasPushedState.cs index 2a036b83d..de826ecef 100644 --- a/src/Beutl.Engine/Graphics/CanvasPushedState.cs +++ b/src/Beutl.Engine/Graphics/CanvasPushedState.cs @@ -10,8 +10,8 @@ internal record SKCanvasPushedState(int Count) : CanvasPushedState { public override void Pop(ImmediateCanvas canvas) { - canvas._canvas.RestoreToCount(Count); - canvas._currentTransform = canvas._canvas.TotalMatrix.ToMatrix(); + canvas.Canvas.RestoreToCount(Count); + canvas._currentTransform = canvas.Canvas.TotalMatrix.ToMatrix(); } } @@ -22,15 +22,15 @@ public override void Pop(ImmediateCanvas canvas) canvas._sharedFillPaint.Reset(); canvas._sharedFillPaint.BlendMode = Invert ? SKBlendMode.DstOut : SKBlendMode.DstIn; - canvas._canvas.SaveLayer(canvas._sharedFillPaint); + canvas.Canvas.SaveLayer(canvas._sharedFillPaint); using (SKPaint maskPaint = Paint) { - canvas._canvas.DrawPaint(maskPaint); + canvas.Canvas.DrawPaint(maskPaint); } - canvas._canvas.Restore(); + canvas.Canvas.Restore(); - canvas._canvas.RestoreToCount(Count); + canvas.Canvas.RestoreToCount(Count); } } diff --git a/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectActivator.cs b/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectActivator.cs index 5579bac96..5d0974743 100644 --- a/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectActivator.cs +++ b/src/Beutl.Engine/Graphics/FilterEffects/FilterEffectActivator.cs @@ -6,47 +6,33 @@ namespace Beutl.Graphics.Effects; -public sealed class FilterEffectActivator : IDisposable +public sealed class FilterEffectActivator(Rect bounds, EffectTarget target, SKImageFilterBuilder builder, ImmediateCanvas canvas) : IDisposable { - private readonly SKImageFilterBuilder _builder; - private readonly ImmediateCanvas _canvas; - private readonly EffectTarget _initialTarget; + private readonly ImmediateCanvas _canvas = canvas; + private readonly EffectTarget _initialTarget = target; - private EffectTarget _target; - private Rect _originalBounds; - private Rect _bounds; + public Rect OriginalBounds { get; private set; } = bounds; - public FilterEffectActivator(Rect bounds, EffectTarget target, SKImageFilterBuilder builder, ImmediateCanvas canvas) - { - _bounds = _originalBounds = bounds; - _initialTarget = target; - _target = target; - _builder = builder; - _canvas = canvas; - } - - public Rect OriginalBounds => _originalBounds; - - public Rect Bounds => _bounds; + public Rect Bounds { get; private set; } = bounds; - public SKImageFilterBuilder Builder => _builder; + public SKImageFilterBuilder Builder { get; } = builder; - public EffectTarget CurrentTarget => _target; + public EffectTarget CurrentTarget { get; private set; } = target; public void Dispose() { - if (_initialTarget != _target) + if (_initialTarget != CurrentTarget) { - _target.Dispose(); + CurrentTarget.Dispose(); } } public Bitmap Snapshot() { Flush(true); - if (_target.Surface != null) + if (CurrentTarget.Surface != null) { - return _target.Surface.Value.Snapshot().ToBitmap(); + return CurrentTarget.Surface.Value.Snapshot().ToBitmap(); } else { @@ -56,37 +42,37 @@ public Bitmap Snapshot() public void Flush(bool force = true) { - if (force || _builder.HasFilter()) + if (force || Builder.HasFilter()) { - SKSurface? surface = _canvas.CreateRenderTarget((int)_originalBounds.Width, (int)_originalBounds.Height); + SKSurface? surface = _canvas.CreateRenderTarget((int)OriginalBounds.Width, (int)OriginalBounds.Height); if (surface != null) { using ImmediateCanvas canvas = _canvas.CreateCanvas(surface, true); using var paint = new SKPaint { - ImageFilter = _builder.GetFilter(), + ImageFilter = Builder.GetFilter(), }; - using (canvas.PushTransform(Matrix.CreateTranslation(-_originalBounds.X, -_originalBounds.Y))) + using (canvas.PushTransform(Matrix.CreateTranslation(-OriginalBounds.X, -OriginalBounds.Y))) using (canvas.PushPaint(paint)) { - _target.Draw(canvas); + CurrentTarget.Draw(canvas); } - _target?.Dispose(); + CurrentTarget?.Dispose(); using var surfaceRef = Ref.Create(surface); - _target = new EffectTarget(surfaceRef, _originalBounds.Size); + CurrentTarget = new EffectTarget(surfaceRef, OriginalBounds.Size); } else { - _target?.Dispose(); + CurrentTarget?.Dispose(); - _target = EffectTarget.Empty; + CurrentTarget = EffectTarget.Empty; } - _builder.Clear(); + Builder.Clear(); } } @@ -102,22 +88,22 @@ public void Apply(FilterEffectContext context, Range range) { if (item is IFEItem_Skia skia) { - skia.Accepts(this, _builder); - _bounds = item.TransformBounds(_bounds); - _originalBounds = item.TransformBounds(_originalBounds); + skia.Accepts(this, Builder); + Bounds = item.TransformBounds(Bounds); + OriginalBounds = item.TransformBounds(OriginalBounds); } else if (item is IFEItem_Custom custom) { Flush(true); - var customContext = new FilterEffectCustomOperationContext(_canvas, _target); + var customContext = new FilterEffectCustomOperationContext(_canvas, CurrentTarget); custom.Accepts(customContext); - if (_target != customContext.Target) + if (CurrentTarget != customContext.Target) { - _target?.Dispose(); - _target = customContext.Target; + CurrentTarget?.Dispose(); + CurrentTarget = customContext.Target; } - _bounds = item.TransformBounds(_bounds); - _originalBounds = _bounds.WithX(0).WithY(0); + Bounds = item.TransformBounds(Bounds); + OriginalBounds = Bounds.WithX(0).WithY(0); } } @@ -137,20 +123,20 @@ private void ApplyFEItem(IFEItem item) { if (item is IFEItem_Skia skia) { - skia.Accepts(this, _builder); - _bounds = item.TransformBounds(_bounds); + skia.Accepts(this, Builder); + Bounds = item.TransformBounds(Bounds); } else if (item is IFEItem_Custom custom) { Flush(true); - var customContext = new FilterEffectCustomOperationContext(_canvas, _target); + var customContext = new FilterEffectCustomOperationContext(_canvas, CurrentTarget); custom.Accepts(customContext); - if (_target != customContext.Target) + if (CurrentTarget != customContext.Target) { - _target?.Dispose(); - _target = customContext.Target; + CurrentTarget?.Dispose(); + CurrentTarget = customContext.Target; } - _bounds = item.TransformBounds(_bounds); + Bounds = item.TransformBounds(Bounds); } } @@ -158,18 +144,18 @@ private void ApplyFEItem(IFEItem item) { SKImageFilter? filter; Flush(false); - using (EffectTarget cloned = _target.Clone()) + using (EffectTarget cloned = CurrentTarget.Clone()) using (var builder = new SKImageFilterBuilder()) - using (var activator = new FilterEffectActivator(_bounds, cloned, builder, _canvas)) + using (var activator = new FilterEffectActivator(Bounds, cloned, builder, _canvas)) { activator.Apply(context); activator.Flush(false); filter = builder.GetFilter(); - if (filter == null && activator._target.Surface != null) + if (filter == null && activator.CurrentTarget.Surface != null) { - SKSurface innerSurface = activator._target.Surface.Value; + SKSurface innerSurface = activator.CurrentTarget.Surface.Value; using (SKImage skImage = innerSurface.Snapshot()) { filter = SKImageFilter.CreateImage(skImage); diff --git a/src/Beutl.Engine/Graphics/ImmediateCanvas.cs b/src/Beutl.Engine/Graphics/ImmediateCanvas.cs index 4ba66b7fe..97941fb46 100644 --- a/src/Beutl.Engine/Graphics/ImmediateCanvas.cs +++ b/src/Beutl.Engine/Graphics/ImmediateCanvas.cs @@ -14,7 +14,6 @@ namespace Beutl.Graphics; public partial class ImmediateCanvas : ICanvas, IImmediateCanvasFactory { - private readonly SKCanvas _canvas; private readonly SKSurface _surface; private readonly Dispatcher? _dispatcher; private readonly SKPaint _sharedFillPaint = new(); @@ -28,8 +27,8 @@ public ImmediateCanvas(SKSurface surface, bool leaveOpen) _dispatcher = Dispatcher.Current; Size = surface.Canvas.DeviceClipBounds.Size.ToGraphicsSize(); _surface = surface; - _canvas = _surface.Canvas; - _currentTransform = _canvas.TotalMatrix.ToMatrix(); + Canvas = _surface.Canvas; + _currentTransform = Canvas.TotalMatrix.ToMatrix(); _leaveOpen = leaveOpen; } @@ -58,13 +57,13 @@ public Matrix Transform return; _currentTransform = value; - _canvas.SetMatrix(_currentTransform.ToSKMatrix()); + Canvas.SetMatrix(_currentTransform.ToSKMatrix()); } } internal IImmediateCanvasFactory? Factory { get; set; } - internal SKCanvas Canvas => _canvas; + internal SKCanvas Canvas { get; } public RenderCacheContext? GetCacheContext() { @@ -104,25 +103,25 @@ public ImmediateCanvas CreateCanvas(SKSurface surface, bool leaveOpen) public void Clear() { VerifyAccess(); - _canvas.Clear(); + Canvas.Clear(); } public void Clear(Color color) { VerifyAccess(); - _canvas.Clear(color.ToSKColor()); + Canvas.Clear(color.ToSKColor()); } public void ClipRect(Rect clip, ClipOperation operation = ClipOperation.Intersect) { VerifyAccess(); - _canvas.ClipRect(clip.ToSKRect(), operation.ToSKClipOperation()); + Canvas.ClipRect(clip.ToSKRect(), operation.ToSKClipOperation()); } public void ClipPath(Geometry geometry, ClipOperation operation = ClipOperation.Intersect) { VerifyAccess(); - _canvas.ClipPath(geometry.GetNativeObject(), operation.ToSKClipOperation(), true); + Canvas.ClipPath(geometry.GetNativeObject(), operation.ToSKClipOperation(), true); } public void Dispose() @@ -160,7 +159,7 @@ public void DrawSurface(SKSurface surface, Point point) _sharedFillPaint.IsAntialias = true; _sharedFillPaint.BlendMode = (SKBlendMode)BlendMode; - _canvas.DrawSurface(surface, point.X, point.Y, _sharedFillPaint); + Canvas.DrawSurface(surface, point.X, point.Y, _sharedFillPaint); } public void DrawDrawable(Drawable drawable) @@ -227,8 +226,7 @@ void AcceptsAll(IGraphicNode node) public void DrawBitmap(IBitmap bmp, IBrush? fill, IPen? pen) { - if (bmp.IsDisposed) - throw new ObjectDisposedException(nameof(IBitmap)); + ObjectDisposedException.ThrowIf(bmp.IsDisposed, bmp); if (bmp.ByteCount <= 0) return; @@ -242,12 +240,12 @@ public void DrawBitmap(IBitmap bmp, IBrush? fill, IPen? pen) { using var img = SKImage.FromPixels(new SKImageInfo(bmp.Width, bmp.Height, SKColorType.Bgra8888), bmp.Data); - _canvas.DrawImage(img, SKPoint.Empty, _sharedFillPaint); + Canvas.DrawImage(img, SKPoint.Empty, _sharedFillPaint); } else { using var skbmp = bmp.ToSKBitmap(); - _canvas.DrawBitmap(skbmp, SKPoint.Empty, _sharedFillPaint); + Canvas.DrawBitmap(skbmp, SKPoint.Empty, _sharedFillPaint); } } @@ -284,14 +282,14 @@ public void DrawEllipse(Rect rect, IBrush? fill, IPen? pen) { VerifyAccess(); ConfigureFillPaint(rect.Size, fill); - _canvas.DrawOval(rect.ToSKRect(), _sharedFillPaint); + Canvas.DrawOval(rect.ToSKRect(), _sharedFillPaint); if (pen != null && pen.Thickness != 0) { if (pen.StrokeAlignment == StrokeAlignment.Center) { ConfigureStrokePaint(rect, pen); - _canvas.DrawOval(rect.ToSKRect(), _sharedStrokePaint); + Canvas.DrawOval(rect.ToSKRect(), _sharedStrokePaint); } else { @@ -308,14 +306,14 @@ public void DrawRectangle(Rect rect, IBrush? fill, IPen? pen) { VerifyAccess(); ConfigureFillPaint(rect.Size, fill); - _canvas.DrawRect(rect.ToSKRect(), _sharedFillPaint); + Canvas.DrawRect(rect.ToSKRect(), _sharedFillPaint); if (pen != null && pen.Thickness != 0) { if (pen.StrokeAlignment == StrokeAlignment.Center) { ConfigureStrokePaint(rect, pen); - _canvas.DrawRect(rect.ToSKRect(), _sharedStrokePaint); + Canvas.DrawRect(rect.ToSKRect(), _sharedStrokePaint); } else { @@ -350,7 +348,7 @@ private void DrawTextStroke(FormattedText text, IPen pen, SKTextBlob textBlob, ConfigureStrokePaint(new(text.Bounds), pen!); if (pen.StrokeAlignment == StrokeAlignment.Center) { - _canvas.DrawText(textBlob, 0, 0, _sharedStrokePaint); + Canvas.DrawText(textBlob, 0, 0, _sharedStrokePaint); } else { @@ -359,17 +357,17 @@ private void DrawTextStroke(FormattedText text, IPen pen, SKTextBlob textBlob, switch (pen!.StrokeAlignment) { case StrokeAlignment.Inside: - _canvas.Save(); - _canvas.ClipPath(path, SKClipOperation.Intersect, true); - _canvas.DrawText(textBlob, 0, 0, _sharedStrokePaint); - _canvas.Restore(); + Canvas.Save(); + Canvas.ClipPath(path, SKClipOperation.Intersect, true); + Canvas.DrawText(textBlob, 0, 0, _sharedStrokePaint); + Canvas.Restore(); break; case StrokeAlignment.Outside: - _canvas.Save(); - _canvas.ClipPath(path, SKClipOperation.Difference, true); - _canvas.DrawText(textBlob, 0, 0, _sharedStrokePaint); - _canvas.Restore(); + Canvas.Save(); + Canvas.ClipPath(path, SKClipOperation.Difference, true); + Canvas.DrawText(textBlob, 0, 0, _sharedStrokePaint); + Canvas.Restore(); break; } } @@ -413,7 +411,7 @@ public void DrawText(FormattedText text, IBrush? fill, IPen? pen) // draw filled ConfigureFillPaint(text.Bounds, fill); - _canvas.DrawText(textBlob, 0, 0, _sharedFillPaint); + Canvas.DrawText(textBlob, 0, 0, _sharedFillPaint); // draw stroke if (pen != null && pen.Thickness != 0) @@ -429,7 +427,7 @@ internal void DrawSKPath(SKPath skPath, bool strokeOnly, IBrush? fill, IPen? pen if (!strokeOnly) { ConfigureFillPaint(rect.Size, fill); - _canvas.DrawPath(skPath, _sharedFillPaint); + Canvas.DrawPath(skPath, _sharedFillPaint); } if (pen != null && pen.Thickness != 0) @@ -438,21 +436,21 @@ internal void DrawSKPath(SKPath skPath, bool strokeOnly, IBrush? fill, IPen? pen switch (pen.StrokeAlignment) { case StrokeAlignment.Center: - _canvas.DrawPath(skPath, _sharedStrokePaint); + Canvas.DrawPath(skPath, _sharedStrokePaint); break; case StrokeAlignment.Inside: - _canvas.Save(); - _canvas.ClipPath(skPath, SKClipOperation.Intersect, true); - _canvas.DrawPath(skPath, _sharedStrokePaint); - _canvas.Restore(); + Canvas.Save(); + Canvas.ClipPath(skPath, SKClipOperation.Intersect, true); + Canvas.DrawPath(skPath, _sharedStrokePaint); + Canvas.Restore(); break; case StrokeAlignment.Outside: - _canvas.Save(); - _canvas.ClipPath(skPath, SKClipOperation.Difference, true); - _canvas.DrawPath(skPath, _sharedStrokePaint); - _canvas.Restore(); + Canvas.Save(); + Canvas.ClipPath(skPath, SKClipOperation.Difference, true); + Canvas.DrawPath(skPath, _sharedStrokePaint); + Canvas.Restore(); break; } } @@ -501,7 +499,7 @@ public void Pop(int count = -1) public PushedState Push() { VerifyAccess(); - int count = _canvas.Save(); + int count = Canvas.Save(); _states.Push(new CanvasPushedState.SKCanvasPushedState(count)); return new PushedState(this, _states.Count); @@ -513,13 +511,13 @@ public PushedState PushLayer(Rect limit = default) int count; if (limit == default) { - count = _canvas.SaveLayer(); + count = Canvas.SaveLayer(); } else { using (var paint = new SKPaint()) { - count = _canvas.SaveLayer(limit.ToSKRect(), paint); + count = Canvas.SaveLayer(limit.ToSKRect(), paint); } } @@ -532,9 +530,9 @@ internal PushedState PushPaint(SKPaint paint, Rect? rect = null) VerifyAccess(); int count; if (rect.HasValue) - count = _canvas.SaveLayer(rect.Value.ToSKRect(), paint); + count = Canvas.SaveLayer(rect.Value.ToSKRect(), paint); else - count = _canvas.SaveLayer(paint); + count = Canvas.SaveLayer(paint); _states.Push(new CanvasPushedState.SKCanvasPushedState(count)); return new PushedState(this, _states.Count); @@ -543,7 +541,7 @@ internal PushedState PushPaint(SKPaint paint, Rect? rect = null) public PushedState PushClip(Rect clip, ClipOperation operation = ClipOperation.Intersect) { VerifyAccess(); - int count = _canvas.Save(); + int count = Canvas.Save(); ClipRect(clip, operation); _states.Push(new CanvasPushedState.SKCanvasPushedState(count)); @@ -553,7 +551,7 @@ public PushedState PushClip(Rect clip, ClipOperation operation = ClipOperation.I public PushedState PushClip(Geometry geometry, ClipOperation operation = ClipOperation.Intersect) { VerifyAccess(); - int count = _canvas.Save(); + int count = Canvas.Save(); ClipPath(geometry, operation); _states.Push(new CanvasPushedState.SKCanvasPushedState(count)); @@ -565,7 +563,7 @@ public PushedState PushOpacityMask(IBrush mask, Rect bounds, bool invert = false VerifyAccess(); var paint = new SKPaint(); - int count = _canvas.SaveLayer(paint); + int count = Canvas.SaveLayer(paint); new BrushConstructor(bounds.Size, mask, (BlendMode)paint.BlendMode, this).ConfigurePaint(paint); _states.Push(new CanvasPushedState.MaskPushedState(count, invert, paint)); return new PushedState(this, _states.Count); @@ -574,7 +572,7 @@ public PushedState PushOpacityMask(IBrush mask, Rect bounds, bool invert = false public PushedState PushTransform(Matrix matrix, TransformOperator transformOperator = TransformOperator.Prepend) { VerifyAccess(); - int count = _canvas.Save(); + int count = Canvas.Save(); if (transformOperator == TransformOperator.Prepend) { @@ -609,8 +607,7 @@ public PushedState PushFilterEffect(FilterEffect effect) private void VerifyAccess() { - if (IsDisposed) - throw new ObjectDisposedException(nameof(ImmediateCanvas)); + ObjectDisposedException.ThrowIf(IsDisposed, this); _dispatcher?.VerifyAccess(); } diff --git a/src/Beutl.Engine/Graphics/Shapes/TextElements.cs b/src/Beutl.Engine/Graphics/Shapes/TextElements.cs index b507b8cd2..db52c53e2 100644 --- a/src/Beutl.Engine/Graphics/Shapes/TextElements.cs +++ b/src/Beutl.Engine/Graphics/Shapes/TextElements.cs @@ -108,10 +108,7 @@ internal LineEnumerator(FormattedText[] array, int count) public bool MoveNext() { - if (_array == null) - { - throw new ObjectDisposedException("LineEnumerator"); - } + ObjectDisposedException.ThrowIf(_array == null, this); int index = _prevIndex + 1; _index = _prevIndex; diff --git a/src/Beutl.Engine/Graphics/Shapes/TextElementsBuilder.cs b/src/Beutl.Engine/Graphics/Shapes/TextElementsBuilder.cs index ad9542168..c4a880b3f 100644 --- a/src/Beutl.Engine/Graphics/Shapes/TextElementsBuilder.cs +++ b/src/Beutl.Engine/Graphics/Shapes/TextElementsBuilder.cs @@ -169,7 +169,7 @@ public void AppendTokens(Span tokens) } else if (!noParse) { - Options options = ToOptions(closeTagType, token.Text.AsSpan()); + Options options = ToOptions(closeTagType); Pop(options); } } @@ -181,7 +181,7 @@ public void AppendTokens(Span tokens) } } - private static Options ToOptions(TagType tagType, ReadOnlySpan text) + private static Options ToOptions(TagType tagType) { return tagType switch { diff --git a/src/Beutl.Engine/Media/Bitmap.cs b/src/Beutl.Engine/Media/Bitmap.cs index b82a6a35b..3ecd161bf 100644 --- a/src/Beutl.Engine/Media/Bitmap.cs +++ b/src/Beutl.Engine/Media/Bitmap.cs @@ -215,10 +215,7 @@ public bool Save(Stream stream, EncodedImageFormat format = EncodedImageFormat.D [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ThrowIfDisposed() { - if (IsDisposed) - { - throw new ObjectDisposedException(nameof(Bitmap)); - } + ObjectDisposedException.ThrowIf(IsDisposed, this); } public void Dispose() diff --git a/src/Beutl.Engine/Media/Music/Pcm.cs b/src/Beutl.Engine/Media/Music/Pcm.cs index cf25b87fa..79dda2824 100644 --- a/src/Beutl.Engine/Media/Music/Pcm.cs +++ b/src/Beutl.Engine/Media/Music/Pcm.cs @@ -100,7 +100,7 @@ public void ConvertTo(Pcm dst) [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ThrowIfDisposed() { - if (IsDisposed) throw new ObjectDisposedException(nameof(Pcm)); + ObjectDisposedException.ThrowIf(IsDisposed, this); } public void Dispose() diff --git a/src/Beutl.Engine/Media/Source/BitmapSource.cs b/src/Beutl.Engine/Media/Source/BitmapSource.cs index c2fa825f9..0354bc484 100644 --- a/src/Beutl.Engine/Media/Source/BitmapSource.cs +++ b/src/Beutl.Engine/Media/Source/BitmapSource.cs @@ -43,8 +43,7 @@ public static bool TryOpen(string fileName, out BitmapSource? result) public override IImageSource Clone() { - if (IsDisposed) - throw new ObjectDisposedException(nameof(VideoSource)); + ObjectDisposedException.ThrowIf(IsDisposed, this); return new BitmapSource(_bitmap, Name); } diff --git a/src/Beutl.Engine/Media/Source/Counter.cs b/src/Beutl.Engine/Media/Source/Counter.cs index ac555604d..664e8ad24 100644 --- a/src/Beutl.Engine/Media/Source/Counter.cs +++ b/src/Beutl.Engine/Media/Source/Counter.cs @@ -29,10 +29,11 @@ public void AddRef() var old = _refs; while (true) { - if (old == 0) - { - throw new ObjectDisposedException("Cannot add a reference to a nonreferenced item"); - } + ObjectDisposedException.ThrowIf(old == 0, this); + //if (old == 0) + //{ + // throw new ObjectDisposedException("Cannot add a reference to a nonreferenced item"); + //} var current = Interlocked.CompareExchange(ref _refs, old + 1, old); if (current == old) { diff --git a/src/Beutl.Engine/Media/Source/SoundSource.cs b/src/Beutl.Engine/Media/Source/SoundSource.cs index 699d96b5d..be3961179 100644 --- a/src/Beutl.Engine/Media/Source/SoundSource.cs +++ b/src/Beutl.Engine/Media/Source/SoundSource.cs @@ -54,8 +54,7 @@ public void Dispose() public SoundSource Clone() { - if (IsDisposed) - throw new ObjectDisposedException(nameof(VideoSource)); + ObjectDisposedException.ThrowIf(IsDisposed, this); return new SoundSource(mediaReader.Clone(), Name); } diff --git a/src/Beutl.Engine/Media/Source/VideoSource.cs b/src/Beutl.Engine/Media/Source/VideoSource.cs index e12f39b89..135dd3246 100644 --- a/src/Beutl.Engine/Media/Source/VideoSource.cs +++ b/src/Beutl.Engine/Media/Source/VideoSource.cs @@ -66,8 +66,7 @@ public void Dispose() public VideoSource Clone() { - if (IsDisposed) - throw new ObjectDisposedException(nameof(VideoSource)); + ObjectDisposedException.ThrowIf(IsDisposed, this); return new VideoSource(_mediaReader.Clone(), Name); } diff --git a/src/Beutl.ProjectSystem/ProjectSystem/TimelineOptions.cs b/src/Beutl.ProjectSystem/ProjectSystem/TimelineOptions.cs index 4b7abe6b7..3dcb5cc71 100644 --- a/src/Beutl.ProjectSystem/ProjectSystem/TimelineOptions.cs +++ b/src/Beutl.ProjectSystem/ProjectSystem/TimelineOptions.cs @@ -6,7 +6,6 @@ public readonly record struct TimelineOptions { private readonly float _scale; private readonly Vector2 _offset; - private readonly int _maxLayerCount; public TimelineOptions() : this(1, Vector2.Zero) @@ -22,7 +21,7 @@ public TimelineOptions(float scale, Vector2 offset, int maxLayerCount) { _scale = scale; _offset = offset; - _maxLayerCount = maxLayerCount; + MaxLayerCount = maxLayerCount; } public float Scale @@ -37,9 +36,5 @@ public Vector2 Offset init => _offset = Vector2.Max(value, new Vector2(0, 0)); } - public int MaxLayerCount - { - get => _maxLayerCount; - init => _maxLayerCount = value; - } + public int MaxLayerCount { get; init; } } diff --git a/src/Beutl.ProjectSystem/SceneGraphicsEvaluator.cs b/src/Beutl.ProjectSystem/SceneGraphicsEvaluator.cs index 5f64e0b9c..c7b5a797c 100644 --- a/src/Beutl.ProjectSystem/SceneGraphicsEvaluator.cs +++ b/src/Beutl.ProjectSystem/SceneGraphicsEvaluator.cs @@ -14,10 +14,9 @@ internal sealed class SceneGraphicsEvaluator(Scene scene, IRenderer renderer) : { private readonly List _entered = []; private readonly List _exited = []; - private readonly List _current = []; private TimeSpan _lastTime = TimeSpan.MinValue; - public List CurrentElements => _current; + public List CurrentElements { get; } = []; public void Evaluate() { @@ -39,9 +38,9 @@ public void Evaluate() EnterSourceOperators(item); } - for (int i = 0; i < _current.Count; i++) + for (int i = 0; i < CurrentElements.Count; i++) { - Element element = _current[i]; + Element element = CurrentElements[i]; using (PooledList list = element.Evaluate(EvaluationTarget.Graphics, clock, renderer)) { foreach (Renderable item in list.Span) @@ -79,7 +78,7 @@ private void SortLayers(TimeSpan timeSpan, out TimeRange enterAffectsRange) { _entered.Clear(); _exited.Clear(); - _current.Clear(); + CurrentElements.Clear(); TimeSpan enterStart = TimeSpan.MaxValue; TimeSpan enterEnd = TimeSpan.Zero; @@ -90,7 +89,7 @@ private void SortLayers(TimeSpan timeSpan, out TimeRange enterAffectsRange) if (current) { - _current.OrderedAdd(item, x => x.ZIndex); + CurrentElements.OrderedAdd(item, x => x.ZIndex); } if (!recent && current) @@ -124,6 +123,6 @@ public void Dispose() { _entered.Clear(); _exited.Clear(); - _current.Clear(); + CurrentElements.Clear(); } } diff --git a/src/Beutl.Utilities/PooledArrayBufferWriter.cs b/src/Beutl.Utilities/PooledArrayBufferWriter.cs index 808e74fb8..d4f6acf53 100644 --- a/src/Beutl.Utilities/PooledArrayBufferWriter.cs +++ b/src/Beutl.Utilities/PooledArrayBufferWriter.cs @@ -22,8 +22,7 @@ public PooledArrayBufferWriter(ArrayPool? pool = null) public PooledArrayBufferWriter(int initialCapacity, ArrayPool? pool = null) { - if (initialCapacity <= 0) - throw new ArgumentException(null, nameof(initialCapacity)); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(initialCapacity, 0, nameof(initialCapacity)); _pool = pool ?? ArrayPool.Shared; _buffer = _pool.Rent(initialCapacity); @@ -63,10 +62,7 @@ public ReadOnlySpan WrittenSpan private void Verify() { - if (IsDisposed) - { - throw new ObjectDisposedException(nameof(PooledArrayBufferWriter)); - } + ObjectDisposedException.ThrowIf(IsDisposed, this); } public void Clear() @@ -80,8 +76,7 @@ public void Clear() public void Advance(int count) { Verify(); - if (count < 0) - throw new ArgumentException(null, nameof(count)); + ArgumentOutOfRangeException.ThrowIfLessThan(count, 0, nameof(count)); if (WrittenCount > _buffer.Length - count) ThrowInvalidOperationException_AdvancedTooFar(_buffer.Length); @@ -109,8 +104,7 @@ public Span GetSpan(int sizeHint = 0) private void CheckAndResizeBuffer(int sizeHint) { - if (sizeHint < 0) - throw new ArgumentException(null, nameof(sizeHint)); + ArgumentOutOfRangeException.ThrowIfLessThan(sizeHint, 0, nameof(sizeHint)); if (sizeHint == 0) { From a23e94bcb5e9bbcc2d2b1caa4c3592e1072babac Mon Sep 17 00:00:00 2001 From: indigo-san Date: Sun, 31 Dec 2023 18:34:05 +0900 Subject: [PATCH 3/4] =?UTF-8?q?=E6=98=8E=E7=A4=BA=E7=9A=84=E3=81=AA?= =?UTF-8?q?=E5=9E=8B=E3=81=AE=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../generators/ResourcesGenerator/Program.cs | 2 +- nukebuild/Build.cs | 2 +- .../Collections/Pooled/PooledList.cs | 20 ++++++++--------- src/Beutl.Core/CoreProperty.cs | 2 +- .../Serialization/ArrayTypeHelpers.cs | 2 +- .../Graphics/Operations/CropOperation.cs | 4 ++-- .../Graphics/Operations/ReplaceOperation.cs | 4 ++-- src/Beutl.Engine/Media/Pixel/Bgr565.cs | 16 +++++++------- src/Beutl.Engine/Media/Pixel/Grayscale8.cs | 8 +++---- src/Beutl.Engine/Media/Source/Counter.cs | 8 +++---- .../Rendering/Cache/RenderCache.cs | 4 ++-- .../NodeTree/ElementNodeTreeModel.cs | 2 +- .../NodeTree/OutputSocket.cs | 2 +- src/Beutl/Services/OutputService.cs | 8 +++---- src/Beutl/Services/PropertyEditorService.cs | 10 ++++----- src/Beutl/ViewModels/EditViewModel.cs | 4 ++-- .../Editors/BrushEditorViewModel.cs | 2 +- .../ViewModels/Editors/PenEditorViewModel.cs | 2 +- src/Beutl/ViewModels/ElementViewModel.cs | 8 +++---- src/Beutl/ViewModels/GraphEditorViewModel.cs | 2 +- .../InlineAnimationLayerViewModel.cs | 6 ++--- .../ViewModels/MenuBarViewModel.Files.cs | 2 +- .../ViewModels/NodeTree/NodeTreeViewModel.cs | 2 +- src/Beutl/ViewModels/PlayerViewModel.cs | 22 +++++++++---------- .../AnExtensionSettingsPageViewModel.cs | 2 +- src/Beutl/ViewModels/TimelineViewModel.cs | 6 ++--- .../Tools/SourceOperatorViewModel.cs | 2 +- src/Beutl/Views/EditView.axaml.cs | 6 ++--- .../Views/NodeTree/NodeTreeView.axaml.cs | 4 ++-- 29 files changed, 80 insertions(+), 84 deletions(-) diff --git a/build/generators/ResourcesGenerator/Program.cs b/build/generators/ResourcesGenerator/Program.cs index b9593aef9..8771c69a2 100644 --- a/build/generators/ResourcesGenerator/Program.cs +++ b/build/generators/ResourcesGenerator/Program.cs @@ -254,7 +254,7 @@ public void GenerateGetObservableCode(Span indentStr, StringBuilder sb, st { sb.AppendLine($"{indentStr}private static IObservable? _{Key}Observable;"); - if (redirects.TryGetValue(RawKey, out var rawKey1)) + if (redirects.TryGetValue(RawKey, out string? rawKey1)) { sb.AppendLine($"{indentStr}public static IObservable {Key}Observable => _{Key}Observable ??= \"{RawKey}\".GetStringObservable(global::{rootNamespace}.Resources.{rawKey1});"); } diff --git a/nukebuild/Build.cs b/nukebuild/Build.cs index cfe61e7d1..20418ea61 100644 --- a/nukebuild/Build.cs +++ b/nukebuild/Build.cs @@ -77,7 +77,7 @@ partial class Build : NukeBuild } AbsolutePath mainProj = SourceDirectory / "Beutl" / "Beutl.csproj"; - var mainOutput = OutputDirectory / "Beutl"; + AbsolutePath mainOutput = OutputDirectory / "Beutl"; DotNetPublish(s => s .EnableNoRestore() diff --git a/src/Beutl.Core/Collections/Pooled/PooledList.cs b/src/Beutl.Core/Collections/Pooled/PooledList.cs index e65f28641..bce3e0b30 100644 --- a/src/Beutl.Core/Collections/Pooled/PooledList.cs +++ b/src/Beutl.Core/Collections/Pooled/PooledList.cs @@ -274,7 +274,7 @@ public PooledList(IEnumerable collection, ClearMode clearMode, ArrayPool c default: _size = 0; _items = s_emptyArray; - using (var en = collection.GetEnumerator()) + using (IEnumerator en = collection.GetEnumerator()) { while (en.MoveNext()) Add(en.Current); @@ -310,7 +310,7 @@ public int Capacity { if (value > 0) { - var newItems = _pool.Rent(value); + T[] newItems = _pool.Rent(value); if (_size > 0) { Array.Copy(_items, newItems, _size); @@ -478,16 +478,14 @@ public void AddRange(IEnumerable collection) public void AddRange(T[] array) => AddRange(array.AsSpan()); -#pragma warning disable CS0419 /// /// Adds the elements of the given to the end of this list. If /// required, the capacity of the list is increased to twice the previous /// capacity or the new size, whichever is larger. /// -#pragma warning restore CS0419 public void AddRange(ReadOnlySpan span) { - var newSpan = InsertSpan(_size, span.Length, false); + Span newSpan = InsertSpan(_size, span.Length, false); span.CopyTo(newSpan); } @@ -502,7 +500,7 @@ public Span AddSpan(int count) => InsertSpan(_size, count); public ReadOnlyCollection AsReadOnly() - => new ReadOnlyCollection(this); + => new(this); /// /// Searches a section of the list for a given element using a binary search @@ -829,7 +827,7 @@ public void ForEach(Action action) /// GetObject methods of the enumerator will throw an exception. /// public Enumerator GetEnumerator() - => new Enumerator(this); + => new(this); IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this); @@ -988,7 +986,7 @@ public void InsertRange(int index, IEnumerable collection) break; default: - using (var en = collection.GetEnumerator()) + using (IEnumerator en = collection.GetEnumerator()) { while (en.MoveNext()) { @@ -1009,7 +1007,7 @@ public void InsertRange(int index, IEnumerable collection) /// public void InsertRange(int index, ReadOnlySpan span) { - var newSpan = InsertSpan(index, span.Length, false); + Span newSpan = InsertSpan(index, span.Length, false); span.CopyTo(newSpan); } @@ -1047,7 +1045,7 @@ private Span InsertSpan(int index, int count, bool clearOutput) _size += count; _version++; - var output = _items.AsSpan(index, count); + Span output = _items.AsSpan(index, count); if (clearOutput && _clearOnFree) { @@ -1449,7 +1447,7 @@ public void Dispose() public bool MoveNext() { - var localList = _list; + PooledList localList = _list; if (_version == localList._version && (uint)_index < (uint)localList._size) { diff --git a/src/Beutl.Core/CoreProperty.cs b/src/Beutl.Core/CoreProperty.cs index 56377fa66..b5658cc12 100644 --- a/src/Beutl.Core/CoreProperty.cs +++ b/src/Beutl.Core/CoreProperty.cs @@ -318,7 +318,7 @@ protected override IObservable GetChanged() internal override void RouteSerialize(ICoreSerializationContext context, object? value) { - var metadata = GetMetadata>(context.OwnerType); + CorePropertyMetadata metadata = GetMetadata>(context.OwnerType); if (metadata.ShouldSerialize && (this is not IStaticProperty sprop || sprop.CanWrite)) { if (context is IJsonSerializationContext jsonCtxt diff --git a/src/Beutl.Core/Serialization/ArrayTypeHelpers.cs b/src/Beutl.Core/Serialization/ArrayTypeHelpers.cs index 2b9108fe8..f6b0cc733 100644 --- a/src/Beutl.Core/Serialization/ArrayTypeHelpers.cs +++ b/src/Beutl.Core/Serialization/ArrayTypeHelpers.cs @@ -88,7 +88,7 @@ public static (Type? Key, Type? Value) GetEntryType(Type dictType) { if (GetElementType(dictType) is Type elementType) { - if (!s_genericArgsTypes.TryGetValue(elementType, out var result)) + if (!s_genericArgsTypes.TryGetValue(elementType, out (Type Key, Type Value) result)) { if (elementType.IsGenericType && elementType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) diff --git a/src/Beutl.Engine/Graphics/Operations/CropOperation.cs b/src/Beutl.Engine/Graphics/Operations/CropOperation.cs index 328790761..0c7642243 100644 --- a/src/Beutl.Engine/Graphics/Operations/CropOperation.cs +++ b/src/Beutl.Engine/Graphics/Operations/CropOperation.cs @@ -8,8 +8,8 @@ public readonly unsafe struct CropOperation(Bitmap src, Bitmap sourceRow = src[y + roi.Y].Slice(roi.X, roi.Width); + Span targetRow = dst[y]; sourceRow.Slice(0, roi.Width).CopyTo(targetRow); } diff --git a/src/Beutl.Engine/Graphics/Operations/ReplaceOperation.cs b/src/Beutl.Engine/Graphics/Operations/ReplaceOperation.cs index 92a8d5336..7115e8a2f 100644 --- a/src/Beutl.Engine/Graphics/Operations/ReplaceOperation.cs +++ b/src/Beutl.Engine/Graphics/Operations/ReplaceOperation.cs @@ -8,8 +8,8 @@ public readonly unsafe struct ReplaceOperation(Bitmap src, Bitma { public readonly void Invoke(int y) { - var sourceRow = src[y]; - var targetRow = dst[y + roi.Y].Slice(roi.X, roi.Width); + Span sourceRow = src[y]; + Span targetRow = dst[y + roi.Y].Slice(roi.X, roi.Width); sourceRow.CopyTo(targetRow); } diff --git a/src/Beutl.Engine/Media/Pixel/Bgr565.cs b/src/Beutl.Engine/Media/Pixel/Bgr565.cs index 063692f7c..e291f239b 100644 --- a/src/Beutl.Engine/Media/Pixel/Bgr565.cs +++ b/src/Beutl.Engine/Media/Pixel/Bgr565.cs @@ -7,20 +7,20 @@ public struct Bgr565(ushort value) : IPixel { public ushort Value = value; - public Bgr565 FromColor(Color color) + public readonly Bgr565 FromColor(Color color) { - var b = color.B >> 3 & 0x1f; - var g = (color.G >> 2 & 0x3f) << 5; - var r = (color.R >> 3 & 0x1f) << 11; + int b = color.B >> 3 & 0x1f; + int g = (color.G >> 2 & 0x3f) << 5; + int r = (color.R >> 3 & 0x1f) << 11; return new Bgr565((ushort)(r | g | b)); } - public Color ToColor() + public readonly Color ToColor() { - var b = (Value & 0x1f) << 3; - var g = (Value >> 5 & 0x3f) << 2; - var r = (Value >> 11 & 0x1f) << 3; + int b = (Value & 0x1f) << 3; + int g = (Value >> 5 & 0x3f) << 2; + int r = (Value >> 11 & 0x1f) << 3; return Color.FromArgb(255, (byte)r, (byte)g, (byte)b); } diff --git a/src/Beutl.Engine/Media/Pixel/Grayscale8.cs b/src/Beutl.Engine/Media/Pixel/Grayscale8.cs index 096bc569d..c81cc1deb 100644 --- a/src/Beutl.Engine/Media/Pixel/Grayscale8.cs +++ b/src/Beutl.Engine/Media/Pixel/Grayscale8.cs @@ -7,12 +7,12 @@ public struct Grayscale8(byte value) : IPixel { public byte Value = value; - public Grayscale8 FromColor(Color color) + public readonly Grayscale8 FromColor(Color color) { - var value = color.R * 0.11448 + + double value = color.R * 0.11448 + color.G * 0.58661 + color.B * 0.29891; - var ntsc = value switch + double ntsc = value switch { > 255 => 255, < 0 => 0, @@ -22,7 +22,7 @@ public Grayscale8 FromColor(Color color) return new Grayscale8((byte)ntsc); } - public Color ToColor() + public readonly Color ToColor() { return Color.FromArgb(Value, Value, Value, Value); } diff --git a/src/Beutl.Engine/Media/Source/Counter.cs b/src/Beutl.Engine/Media/Source/Counter.cs index 664e8ad24..ea3b5b39d 100644 --- a/src/Beutl.Engine/Media/Source/Counter.cs +++ b/src/Beutl.Engine/Media/Source/Counter.cs @@ -26,7 +26,7 @@ public Counter(T value, Action? onRelease) public void AddRef() { - var old = _refs; + int old = _refs; while (true) { ObjectDisposedException.ThrowIf(old == 0, this); @@ -34,7 +34,7 @@ public void AddRef() //{ // throw new ObjectDisposedException("Cannot add a reference to a nonreferenced item"); //} - var current = Interlocked.CompareExchange(ref _refs, old + 1, old); + int current = Interlocked.CompareExchange(ref _refs, old + 1, old); if (current == old) { break; @@ -45,10 +45,10 @@ public void AddRef() public void Release() { - var old = _refs; + int old = _refs; while (true) { - var current = Interlocked.CompareExchange(ref _refs, old - 1, old); + int current = Interlocked.CompareExchange(ref _refs, old - 1, old); if (current == old) { diff --git a/src/Beutl.Engine/Rendering/Cache/RenderCache.cs b/src/Beutl.Engine/Rendering/Cache/RenderCache.cs index 66cd04813..edee5710b 100644 --- a/src/Beutl.Engine/Rendering/Cache/RenderCache.cs +++ b/src/Beutl.Engine/Rendering/Cache/RenderCache.cs @@ -12,7 +12,7 @@ namespace Beutl.Rendering.Cache; public sealed class RenderCache(IGraphicNode node) : IDisposable { - private readonly WeakReference _node = new WeakReference(node); + private readonly WeakReference _node = new(node); private Ref? _cache; private Rect _cacheBounds; @@ -111,7 +111,7 @@ public void Invalidate() #if DEBUG if (_cache != null) { - Debug.WriteLine($"[RenderCache:Invalildated] '{(_node.TryGetTarget(out var node) ? node : null)}'"); + Debug.WriteLine($"[RenderCache:Invalildated] '{(_node.TryGetTarget(out IGraphicNode? node) ? node : null)}'"); } #endif diff --git a/src/Beutl.ProjectSystem/NodeTree/ElementNodeTreeModel.cs b/src/Beutl.ProjectSystem/NodeTree/ElementNodeTreeModel.cs index 7332c1c89..330e35009 100644 --- a/src/Beutl.ProjectSystem/NodeTree/ElementNodeTreeModel.cs +++ b/src/Beutl.ProjectSystem/NodeTree/ElementNodeTreeModel.cs @@ -84,7 +84,7 @@ public PooledList Evaluate(EvaluationTarget target, IRenderer render private void Uninitialize() { - foreach (var item in CollectionsMarshal.AsSpan(_evalContexts)) + foreach (NodeEvaluationContext[]? item in CollectionsMarshal.AsSpan(_evalContexts)) { foreach (NodeEvaluationContext? context in item.AsSpan()) { diff --git a/src/Beutl.ProjectSystem/NodeTree/OutputSocket.cs b/src/Beutl.ProjectSystem/NodeTree/OutputSocket.cs index 1561bd9dc..08abccfc1 100644 --- a/src/Beutl.ProjectSystem/NodeTree/OutputSocket.cs +++ b/src/Beutl.ProjectSystem/NodeTree/OutputSocket.cs @@ -138,7 +138,7 @@ public override void PostEvaluate(EvaluationContext context) public override void ReadFromJson(JsonObject json) { base.ReadFromJson(json); - if (json.TryGetPropertyValue("connection-inputs", out var srcNode) + if (json.TryGetPropertyValue("connection-inputs", out JsonNode? srcNode) && srcNode is JsonArray srcArray) { if (_inputIds != null) diff --git a/src/Beutl/Services/OutputService.cs b/src/Beutl/Services/OutputService.cs index 625e6dde0..e70a7e213 100644 --- a/src/Beutl/Services/OutputService.cs +++ b/src/Beutl/Services/OutputService.cs @@ -61,11 +61,11 @@ public static JsonNode ToJson(OutputQueueItem item) { try { - var obj = json.AsObject(); - var contextJson = json[nameof(Context)]; + JsonObject obj = json.AsObject(); + JsonNode? contextJson = json[nameof(Context)]; - var extensionStr = obj["Extension"]!.AsValue().GetValue(); - var extensionType = TypeFormat.ToType(extensionStr); + string extensionStr = obj["Extension"]!.AsValue().GetValue(); + Type? extensionType = TypeFormat.ToType(extensionStr); ExtensionProvider provider = ExtensionProvider.Current; OutputExtension? extension = Array.Find(provider.GetExtensions(), x => x.GetType() == extensionType); diff --git a/src/Beutl/Services/PropertyEditorService.cs b/src/Beutl/Services/PropertyEditorService.cs index 193b4b808..2c7092494 100644 --- a/src/Beutl/Services/PropertyEditorService.cs +++ b/src/Beutl/Services/PropertyEditorService.cs @@ -217,7 +217,7 @@ public IEnumerable MatchProperty(IReadOnlyList(item.ImplementedType, out var metadata)) + if (coreProp.TryGetMetadata(item.ImplementedType, out CorePropertyMetadata? metadata)) { // 特殊処理 if (metadata.Attributes.OfType().Any()) @@ -319,9 +319,9 @@ private static bool TryCreateContextCore(PropertyEditorExtension extension, IRea if (property.GetCoreProperty() is { Id: int propId } coreProp) { // 特殊処理 - if (coreProp.TryGetMetadata(property.ImplementedType, out var metadata)) + if (coreProp.TryGetMetadata(property.ImplementedType, out CorePropertyMetadata? metadata)) { - var choiceAtt = metadata.Attributes.OfType().FirstOrDefault(); + ChoicesProviderAttribute? choiceAtt = metadata.Attributes.OfType().FirstOrDefault(); if (choiceAtt != null) { viewModel = CreateChoiceViewModel(property, choiceAtt.ProviderType); @@ -379,7 +379,7 @@ private static bool TryCreateContextCore(PropertyEditorExtension extension, IRea public bool TryCreateControl(IPropertyEditorContext context, [NotNullWhen(true)] out Control? control) { - if (TryCreateControlCore(context, out var control1)) + if (TryCreateControlCore(context, out Control? control1)) { if (control1 is PropertyEditor editor) { @@ -497,7 +497,7 @@ private static bool TryCreateControlCore(IPropertyEditorContext context, [NotNul { if (property.GetCoreProperty() is { Id: int propId } coreProp) { - if (coreProp.TryGetMetadata(property.ImplementedType, out var metadata)) + if (coreProp.TryGetMetadata(property.ImplementedType, out CorePropertyMetadata? metadata)) { // 特殊処理 if (metadata.Attributes.OfType().Any()) diff --git a/src/Beutl/ViewModels/EditViewModel.cs b/src/Beutl/ViewModels/EditViewModel.cs index a02c17c5c..ad7bceb45 100644 --- a/src/Beutl/ViewModels/EditViewModel.cs +++ b/src/Beutl/ViewModels/EditViewModel.cs @@ -154,7 +154,7 @@ public void Dispose() { for (int i = 0; i < BottomTabItems.Count; i++) { - var item = BottomTabItems[i]; + ToolTabViewModel item = BottomTabItems[i]; if (item.Context is T typed && condition(typed)) { return typed; @@ -163,7 +163,7 @@ public void Dispose() for (int i = 0; i < RightTabItems.Count; i++) { - var item = RightTabItems[i]; + ToolTabViewModel item = RightTabItems[i]; if (item.Context is T typed && condition(typed)) { return typed; diff --git a/src/Beutl/ViewModels/Editors/BrushEditorViewModel.cs b/src/Beutl/ViewModels/Editors/BrushEditorViewModel.cs index b637401bd..8cef5fc6d 100644 --- a/src/Beutl/ViewModels/Editors/BrushEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/BrushEditorViewModel.cs @@ -130,7 +130,7 @@ public override void ReadFromJson(JsonObject json) base.ReadFromJson(json); try { - if (json.TryGetPropertyValue(nameof(IsExpanded), out var isExpandedNode) + if (json.TryGetPropertyValue(nameof(IsExpanded), out JsonNode? isExpandedNode) && isExpandedNode is JsonValue isExpanded) { IsExpanded.Value = (bool)isExpanded; diff --git a/src/Beutl/ViewModels/Editors/PenEditorViewModel.cs b/src/Beutl/ViewModels/Editors/PenEditorViewModel.cs index 33c7ca29b..6bb003c6c 100644 --- a/src/Beutl/ViewModels/Editors/PenEditorViewModel.cs +++ b/src/Beutl/ViewModels/Editors/PenEditorViewModel.cs @@ -126,7 +126,7 @@ public override void Accept(IPropertyEditorContextVisitor visitor) public override void ReadFromJson(JsonObject json) { base.ReadFromJson(json); - if (json.TryGetPropertyValue(nameof(IsExpanded), out var isExpandedNode) + if (json.TryGetPropertyValue(nameof(IsExpanded), out JsonNode? isExpandedNode) && isExpandedNode is JsonValue isExpanded) { IsExpanded.Value = (bool)isExpanded; diff --git a/src/Beutl/ViewModels/ElementViewModel.cs b/src/Beutl/ViewModels/ElementViewModel.cs index bce39c530..8ce5ee6f2 100644 --- a/src/Beutl/ViewModels/ElementViewModel.cs +++ b/src/Beutl/ViewModels/ElementViewModel.cs @@ -210,7 +210,7 @@ public async void AnimationRequest(int layerNum, bool affectModel = true, Cancel .ToArray(); var scope = Scope.PrepareAnimation(); - var newMargin = new Thickness(0, Timeline.CalculateLayerTop(layerNum), 0, 0); + Thickness newMargin = new(0, Timeline.CalculateLayerTop(layerNum), 0, 0); Thickness oldMargin = Margin.Value; if (affectModel) Model.ZIndex = layerNum; @@ -406,12 +406,12 @@ private List CreateKeyBinding() { PlatformHotkeyConfiguration? config = Application.Current?.PlatformSettings?.HotkeyConfiguration; KeyModifiers modifier = config?.CommandModifiers ?? KeyModifiers.Control; - var list = new List - { + List list = + [ new KeyBinding { Gesture = new(Key.Delete), Command = Exclude }, new KeyBinding { Gesture = new(Key.Delete, modifier), Command = Delete }, new KeyBinding { Gesture = new(Key.K, modifier), Command = SplitByCurrentFrame } - }; + ]; if (config != null) { diff --git a/src/Beutl/ViewModels/GraphEditorViewModel.cs b/src/Beutl/ViewModels/GraphEditorViewModel.cs index 3b7191a72..36d252cbe 100644 --- a/src/Beutl/ViewModels/GraphEditorViewModel.cs +++ b/src/Beutl/ViewModels/GraphEditorViewModel.cs @@ -16,7 +16,7 @@ public sealed class GraphEditorViewModel( { public override void DropEasing(Easing easing, TimeSpan keyTime) { - var originalKeyTime = keyTime; + TimeSpan originalKeyTime = keyTime; keyTime = ConvertKeyTime(keyTime); Project? proj = Scene.FindHierarchicalParent(); int rate = proj?.GetFrameRate() ?? 30; diff --git a/src/Beutl/ViewModels/InlineAnimationLayerViewModel.cs b/src/Beutl/ViewModels/InlineAnimationLayerViewModel.cs index 48e666415..944e5617a 100644 --- a/src/Beutl/ViewModels/InlineAnimationLayerViewModel.cs +++ b/src/Beutl/ViewModels/InlineAnimationLayerViewModel.cs @@ -17,14 +17,14 @@ public override void DropEasing(Easing easing, TimeSpan keyTime) { if (Property.Animation is KeyFrameAnimation kfAnimation) { - var originalKeyTime = keyTime; + TimeSpan originalKeyTime = keyTime; keyTime = ConvertKeyTime(originalKeyTime, kfAnimation); Project? proj = Timeline.Scene.FindHierarchicalParent(); int rate = proj?.GetFrameRate() ?? 30; - var threshold = TimeSpan.FromSeconds(1d / rate) * 3; + TimeSpan threshold = TimeSpan.FromSeconds(1d / rate) * 3; - var keyFrame = kfAnimation.KeyFrames.FirstOrDefault(v => Math.Abs(v.KeyTime.Ticks - keyTime.Ticks) <= threshold.Ticks); + IKeyFrame? keyFrame = kfAnimation.KeyFrames.FirstOrDefault(v => Math.Abs(v.KeyTime.Ticks - keyTime.Ticks) <= threshold.Ticks); if (keyFrame != null) { new ChangePropertyCommand(keyFrame, KeyFrame.EasingProperty, easing, keyFrame.Easing) diff --git a/src/Beutl/ViewModels/MenuBarViewModel.Files.cs b/src/Beutl/ViewModels/MenuBarViewModel.Files.cs index c9d3d061d..cee93937e 100644 --- a/src/Beutl/ViewModels/MenuBarViewModel.Files.cs +++ b/src/Beutl/ViewModels/MenuBarViewModel.Files.cs @@ -94,7 +94,7 @@ private void InitializeFilesCommands() private async Task OnSaveAll() { - using var activity = Telemetry.StartActivity("SaveAll"); + using Activity? activity = Telemetry.StartActivity("SaveAll"); Project? project = ProjectService.Current.CurrentProject.Value; int itemsCount = 0; diff --git a/src/Beutl/ViewModels/NodeTree/NodeTreeViewModel.cs b/src/Beutl/ViewModels/NodeTree/NodeTreeViewModel.cs index 7160a6162..b4150d8c2 100644 --- a/src/Beutl/ViewModels/NodeTree/NodeTreeViewModel.cs +++ b/src/Beutl/ViewModels/NodeTree/NodeTreeViewModel.cs @@ -124,7 +124,7 @@ public void ReadFromJson(JsonObject json) } } - if (json.TryGetPropertyValue(nameof(Matrix), out var mJson)) + if (json.TryGetPropertyValue(nameof(Matrix), out JsonNode? mJson)) { string m = (string)mJson!; Matrix.Value = Avalonia.Matrix.Parse(m); diff --git a/src/Beutl/ViewModels/PlayerViewModel.cs b/src/Beutl/ViewModels/PlayerViewModel.cs index 474d4ffcf..84c00461b 100644 --- a/src/Beutl/ViewModels/PlayerViewModel.cs +++ b/src/Beutl/ViewModels/PlayerViewModel.cs @@ -242,9 +242,7 @@ private async void PlayAudio(Scene scene) private static void Swap(ref T x, ref T y) { - T temp = x; - x = y; - y = temp; + (y, x) = (x, y); } private async Task PlayWithXA2(XAudioContext audioContext, Scene scene) @@ -325,16 +323,16 @@ private async Task PlayWithOpenAL(AudioContext audioContext, Scene scene) IComposer composer = scene.Composer; TimeSpan cur = scene.CurrentFrame; - var buffers = AL.GenBuffers(2); - var source = AL.GenSource(); + int[] buffers = AL.GenBuffers(2); + int source = AL.GenSource(); - foreach (var buffer in buffers) + foreach (int buffer in buffers) { - using var pcmf = FillAudioData(cur, composer); + using Pcm? pcmf = FillAudioData(cur, composer); cur += s_second; if (pcmf != null) { - using var pcm = pcmf.Convert(); + using Pcm pcm = pcmf.Convert(); AL.BufferData(buffer, ALFormat.Stereo16, pcm.DataSpan, pcm.SampleRate); } @@ -346,7 +344,7 @@ private async Task PlayWithOpenAL(AudioContext audioContext, Scene scene) while (IsPlaying.Value) { - AL.GetSource(source, ALGetSourcei.BuffersProcessed, out var processed); + AL.GetSource(source, ALGetSourcei.BuffersProcessed, out int processed); while (processed > 0) { using Pcm? pcmf = FillAudioData(cur, composer); @@ -354,7 +352,7 @@ private async Task PlayWithOpenAL(AudioContext audioContext, Scene scene) int buffer = AL.SourceUnqueueBuffer(source); if (pcmf != null) { - using var pcm = pcmf.Convert(); + using Pcm pcm = pcmf.Convert(); AL.BufferData(buffer, ALFormat.Stereo16, pcm.DataSpan, pcm.SampleRate); } @@ -402,7 +400,7 @@ private void Render(IRenderer renderer, TimeSpan timeSpan) { if (IsPlaying.Value && renderer.Render(timeSpan)) { - using var bitmap = renderer.Snapshot(); + using Bitmap bitmap = renderer.Snapshot(); UpdateImage(bitmap); if (Scene != null) @@ -470,7 +468,7 @@ private void DrawBoundaries(Renderer renderer) foreach (Rect item in renderer.RenderScene[selected.Value].GetBoundaries()) { - var rect = item; + Rect rect = item; if (!exactBounds) { rect = item.Inflate(4 / scale); diff --git a/src/Beutl/ViewModels/SettingsPages/AnExtensionSettingsPageViewModel.cs b/src/Beutl/ViewModels/SettingsPages/AnExtensionSettingsPageViewModel.cs index f680a8acc..706b02363 100644 --- a/src/Beutl/ViewModels/SettingsPages/AnExtensionSettingsPageViewModel.cs +++ b/src/Beutl/ViewModels/SettingsPages/AnExtensionSettingsPageViewModel.cs @@ -65,7 +65,7 @@ private void InitializeCoreObject(ExtensionSettings obj, Func(abProperty.ImplementedType, out var metadata)) + && coreProperty.TryGetMetadata(abProperty.ImplementedType, out CorePropertyMetadata? metadata)) { return metadata.DisplayAttribute?.GetGroupName(); } diff --git a/src/Beutl/ViewModels/TimelineViewModel.cs b/src/Beutl/ViewModels/TimelineViewModel.cs index 7c2c68166..ca1eed4f9 100644 --- a/src/Beutl/ViewModels/TimelineViewModel.cs +++ b/src/Beutl/ViewModels/TimelineViewModel.cs @@ -110,7 +110,7 @@ public TimelineViewModel(EditViewModel editViewModel) AdjustDurationToPointer.Subscribe(OnAdjustDurationToPointer); AdjustDurationToCurrent.Subscribe(OnAdjustDurationToCurrent); - var editorConfig = GlobalConfiguration.Instance.EditorConfig; + EditorConfig editorConfig = GlobalConfiguration.Instance.EditorConfig; AutoAdjustSceneDuration = editorConfig.GetObservable(EditorConfig.AutoAdjustSceneDurationProperty).ToReactiveProperty(); AutoAdjustSceneDuration.Subscribe(b => editorConfig.AutoAdjustSceneDuration = b); @@ -228,7 +228,7 @@ public void Dispose() { // ToArrayの理由は // TrackedLayerTopObservable.DisposeでDeinitializeが呼び出され、_trackerCacheが変更されるので - foreach (var item in _trackerCache.Values.ToArray()) + foreach (TrackedLayerTopObservable? item in _trackerCache.Values.ToArray()) { item.Dispose(); } @@ -305,7 +305,7 @@ private void TryApplyLayerCount(int count) public void ReadFromJson(JsonObject json) { - if (json.TryGetPropertyValue(nameof(LayerHeaders), out var layersNode) + if (json.TryGetPropertyValue(nameof(LayerHeaders), out JsonNode? layersNode) && layersNode is JsonArray layersArray) { foreach ((LayerHeaderViewModel layer, JsonObject item) in layersArray.OfType() diff --git a/src/Beutl/ViewModels/Tools/SourceOperatorViewModel.cs b/src/Beutl/ViewModels/Tools/SourceOperatorViewModel.cs index 3c4f82699..a4a96bc3f 100644 --- a/src/Beutl/ViewModels/Tools/SourceOperatorViewModel.cs +++ b/src/Beutl/ViewModels/Tools/SourceOperatorViewModel.cs @@ -149,7 +149,7 @@ private void Init() { if (x is BaseEditorViewModel { WrappedProperty: { } abProperty } && abProperty.GetCoreProperty() is { } coreProperty - && coreProperty.TryGetMetadata(abProperty.ImplementedType, out var metadata)) + && coreProperty.TryGetMetadata(abProperty.ImplementedType, out CorePropertyMetadata? metadata)) { return metadata.DisplayAttribute?.GetGroupName(); } diff --git a/src/Beutl/Views/EditView.axaml.cs b/src/Beutl/Views/EditView.axaml.cs index 12c010e37..e13bb8afa 100644 --- a/src/Beutl/Views/EditView.axaml.cs +++ b/src/Beutl/Views/EditView.axaml.cs @@ -297,10 +297,10 @@ protected override void OnDataContextChanged(EventArgs e) t.Item3.RenderTransform = t.Item2.RenderTransform = new ImmutableTransform(t.matrix.ToAvaMatrix()); if (DataContext is EditViewModel vm) { - var width = vm.Scene.Width; + int width = vm.Scene.Width; if (width == 0) return; - var actualWidth = t.Item2.Bounds.Width * t.matrix.M11; - var pixelSize = actualWidth / width; + double actualWidth = t.Item2.Bounds.Width * t.matrix.M11; + double pixelSize = actualWidth / width; if (pixelSize >= 1) { RenderOptions.SetBitmapInterpolationMode(t.Item2, BitmapInterpolationMode.None); diff --git a/src/Beutl/Views/NodeTree/NodeTreeView.axaml.cs b/src/Beutl/Views/NodeTree/NodeTreeView.axaml.cs index 46dd61cdc..e7fddfa1b 100644 --- a/src/Beutl/Views/NodeTree/NodeTreeView.axaml.cs +++ b/src/Beutl/Views/NodeTree/NodeTreeView.axaml.cs @@ -19,7 +19,7 @@ public partial class NodeTreeView : UserControl private Point _rightClickedPosition; internal Point _leftClickedPosition; private bool _rangeSelectionPressed; - private List<(NodeView Node, bool IsSelectedOriginal)> _rangeSelection = []; + private readonly List<(NodeView Node, bool IsSelectedOriginal)> _rangeSelection = []; private bool _matrixUpdating; public NodeTreeView() @@ -77,7 +77,7 @@ private void OnZoomChanged(object sender, ZoomChangedEventArgs e) private void UpdateRangeSelection() { - foreach ((var node, bool isSelectedOriginal) in _rangeSelection) + foreach ((NodeView? node, bool isSelectedOriginal) in _rangeSelection) { if (node.DataContext is NodeViewModel nodeViewModel) { From a11a4eb2de26895dbdbac894cc04bf97ba9e9d06 Mon Sep 17 00:00:00 2001 From: indigo-san Date: Sun, 31 Dec 2023 18:39:32 +0900 Subject: [PATCH 4/4] chores --- build/generators/ResourcesGenerator/Program.cs | 7 ++++--- src/Beutl.Configuration/ViewConfig.cs | 2 +- src/Beutl.Controls/PropertyEditors/RelativePointEditor.cs | 2 +- src/Beutl.Core/Collections/CoreList.cs | 2 +- src/Beutl.Core/Collections/Pooled/PooledList.cs | 6 +++--- src/Beutl.Engine/Graphics/Shapes/TextElements.cs | 2 +- src/Beutl.Engine/Media/Source/Counter.cs | 2 ++ src/Beutl.PackageTools/Program.cs | 4 ++-- src/Beutl.PackageTools/RunCommand.cs | 6 +++--- src/Beutl/ViewModels/OutputViewModel.cs | 4 ++++ 10 files changed, 22 insertions(+), 15 deletions(-) diff --git a/build/generators/ResourcesGenerator/Program.cs b/build/generators/ResourcesGenerator/Program.cs index 8771c69a2..6e8ae0a25 100644 --- a/build/generators/ResourcesGenerator/Program.cs +++ b/build/generators/ResourcesGenerator/Program.cs @@ -128,12 +128,13 @@ void AddChild(Dictionary hierarchizedLists, string key match2.Key = $"Index{match2.Key}"; } - if (!current.Children.ContainsKey(curKey)) + if (!current.Children.TryGetValue(curKey, out HierarchizedList? v)) { - current.Children[curKey] = new HierarchizedList(); + v = new HierarchizedList(); + current.Children[curKey] = v; } - current = current.Children[curKey]; + current = v; if (i == splitted.Length - 1) { diff --git a/src/Beutl.Configuration/ViewConfig.cs b/src/Beutl.Configuration/ViewConfig.cs index 2a5d7560a..e9d176ce0 100644 --- a/src/Beutl.Configuration/ViewConfig.cs +++ b/src/Beutl.Configuration/ViewConfig.cs @@ -310,7 +310,7 @@ public void UpdateRecentProject(string filename) public void ResetPrimaryProperties() { - PrimaryProperties.Replace(new[] { "AlignmentX", "AlignmentY", "TransformOrigin", "BlendMode" }); + PrimaryProperties.Replace(["AlignmentX", "AlignmentY", "TransformOrigin", "BlendMode"]); } protected override void OnPropertyChanged(PropertyChangedEventArgs args) diff --git a/src/Beutl.Controls/PropertyEditors/RelativePointEditor.cs b/src/Beutl.Controls/PropertyEditors/RelativePointEditor.cs index 83e4a65dd..a202ed64b 100644 --- a/src/Beutl.Controls/PropertyEditors/RelativePointEditor.cs +++ b/src/Beutl.Controls/PropertyEditors/RelativePointEditor.cs @@ -162,7 +162,7 @@ private static bool TryParse(string s, out float result, out Graphics.RelativeUn float scale = 1f; ReadOnlySpan span = s; - if (s.EndsWith("%", StringComparison.Ordinal)) + if (s.EndsWith('%')) { scale = 0.01f; span = s.AsSpan()[0..^1]; diff --git a/src/Beutl.Core/Collections/CoreList.cs b/src/Beutl.Core/Collections/CoreList.cs index 8de20699d..17453a7da 100644 --- a/src/Beutl.Core/Collections/CoreList.cs +++ b/src/Beutl.Core/Collections/CoreList.cs @@ -677,7 +677,7 @@ public bool MoveNext() return _innerEnumerator.MoveNext(); } - void IEnumerator.Reset() + readonly void IEnumerator.Reset() { ((IEnumerator)_innerEnumerator).Reset(); } diff --git a/src/Beutl.Core/Collections/Pooled/PooledList.cs b/src/Beutl.Core/Collections/Pooled/PooledList.cs index bce3e0b30..b7c95142a 100644 --- a/src/Beutl.Core/Collections/Pooled/PooledList.cs +++ b/src/Beutl.Core/Collections/Pooled/PooledList.cs @@ -1441,7 +1441,7 @@ internal Enumerator(PooledList list) _current = default; } - public void Dispose() + public readonly void Dispose() { } @@ -1470,9 +1470,9 @@ private bool MoveNextRare() return false; } - public T Current => _current!; + public readonly T Current => _current!; - object? IEnumerator.Current + readonly object? IEnumerator.Current { get { diff --git a/src/Beutl.Engine/Graphics/Shapes/TextElements.cs b/src/Beutl.Engine/Graphics/Shapes/TextElements.cs index db52c53e2..89d9fa169 100644 --- a/src/Beutl.Engine/Graphics/Shapes/TextElements.cs +++ b/src/Beutl.Engine/Graphics/Shapes/TextElements.cs @@ -104,7 +104,7 @@ internal LineEnumerator(FormattedText[] array, int count) _arrayCount = count; } - public Span Current => _array.AsSpan().Slice(_index, _count); + public readonly Span Current => _array.AsSpan().Slice(_index, _count); public bool MoveNext() { diff --git a/src/Beutl.Engine/Media/Source/Counter.cs b/src/Beutl.Engine/Media/Source/Counter.cs index ea3b5b39d..1b8f86309 100644 --- a/src/Beutl.Engine/Media/Source/Counter.cs +++ b/src/Beutl.Engine/Media/Source/Counter.cs @@ -11,7 +11,9 @@ internal sealed class Counter // なのでどこで作成されたかの情報が欲しい。 // 可能性として考えられるのは、ImmediateCanvasにそのままのSKSurfaceを渡している点 #if DEBUG +#pragma warning disable IDE0052 // 読み取られていないプライベート メンバーを削除 private readonly string _stackTrace; +#pragma warning restore IDE0052 // 読み取られていないプライベート メンバーを削除 #endif public Counter(T value, Action? onRelease) diff --git a/src/Beutl.PackageTools/Program.cs b/src/Beutl.PackageTools/Program.cs index bde992a38..74ea74cb9 100644 --- a/src/Beutl.PackageTools/Program.cs +++ b/src/Beutl.PackageTools/Program.cs @@ -12,11 +12,11 @@ var apiApp = new BeutlApiApplication(new HttpClient()); -var verbose = new Option(new[] { "--verbose", "-v" }, () => false) +var verbose = new Option(["--verbose", "-v"], () => false) { Description = Resources.VerboseDescription, }; -var clean = new Option(new[] { "--clean", "-c" }, () => true) +var clean = new Option(["--clean", "-c"], () => true) { Description = Resources.CleanDescription, }; diff --git a/src/Beutl.PackageTools/RunCommand.cs b/src/Beutl.PackageTools/RunCommand.cs index 9f192a1d9..4583ee8be 100644 --- a/src/Beutl.PackageTools/RunCommand.cs +++ b/src/Beutl.PackageTools/RunCommand.cs @@ -17,17 +17,17 @@ public sealed class RunCommand : RootCommand public RunCommand(BeutlApiApplication apiApp, Option verbose, Option clean) : base(Resources.RunCommandDescription) { - AddOption(_installs = new Option(new[] { "--installs", "-i" }, () => Array.Empty()) + AddOption(_installs = new Option(["--installs", "-i"], () => []) { Description = Resources.InstallsDescription, AllowMultipleArgumentsPerToken = true, }); - AddOption(_uninstalls = new Option(new[] { "--uninstalls", "-r" }, () => Array.Empty()) + AddOption(_uninstalls = new Option(["--uninstalls", "-r"], () => []) { Description = Resources.UninstallsDescription, AllowMultipleArgumentsPerToken = true, }); - AddOption(_updates = new Option(new[] { "--updates", "-u" }, () => Array.Empty()) + AddOption(_updates = new Option(["--updates", "-u"], () => []) { Description = Resources.UpdatesDescription, AllowMultipleArgumentsPerToken = true, diff --git a/src/Beutl/ViewModels/OutputViewModel.cs b/src/Beutl/ViewModels/OutputViewModel.cs index 4e988b607..a33e8006f 100644 --- a/src/Beutl/ViewModels/OutputViewModel.cs +++ b/src/Beutl/ViewModels/OutputViewModel.cs @@ -619,10 +619,14 @@ public void ReadFromJson(JsonObject json) if (json.TryGetPropertyValue(nameof(VideoSettings), out JsonNode? videoNode) && videoNode is JsonObject videoObj) + { VideoSettings.ReadFromJson(videoObj); + } if (json.TryGetPropertyValue(nameof(AudioSettings), out JsonNode? audioNode) && audioNode is JsonObject audioObj) + { AudioSettings.ReadFromJson(audioObj); + } } }