Skip to content

Commit

Permalink
ImmutableCollectionsNameValue
Browse files Browse the repository at this point in the history
  • Loading branch information
Lightczx committed Dec 13, 2024
1 parent ca5507f commit 8a7315f
Show file tree
Hide file tree
Showing 13 changed files with 94 additions and 93 deletions.
11 changes: 0 additions & 11 deletions src/Snap.Hutao/Snap.Hutao.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,11 @@
<File Path=".editorconfig" />
<File Path=".vsconfig" />
</Folder>
<Project Path="Snap.Hutao.Test\Snap.Hutao.Test.csproj" />
<Project Path="Snap.Hutao\Snap.Hutao.csproj">
<Platform Solution="*|Any CPU" Project="x64" />
<Platform Solution="*|arm64" Project="arm64" />
<Platform Solution="*|x64" Project="x64" />
<Platform Solution="*|x86" Project="x86" />
<Deploy />
</Project>
<Properties Name="ExtensibilityGlobals">
<Property Name="RESX_AutoApplyExistingTranslations" Value="False" />
<Property Name="RESX_NeutralResourcesLanguage" Value="zh-CN" />
<Property Name="RESX_Rules" Value="{&quot;EnabledRules&quot;:[&quot;StringFormat&quot;,&quot;WhiteSpaceLead&quot;,&quot;WhiteSpaceTail&quot;,&quot;PunctuationLead&quot;]}" />
<Property Name="RESX_ShowErrorsInErrorList" Value="False" />
<Property Name="RESX_SortFileContentOnSave" Value="True" />
</Properties>
<Properties Name="Visual Studio">
<Property Name="OpenWith" Value="17" />
</Properties>
</Solution>
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.

using Microsoft.UI.Xaml.Documents;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
Expand All @@ -23,8 +24,14 @@ public static ImmutableArray<TResult> SelectAsArray<TSource, TResult>(this Immut
[Pure]
public static ImmutableArray<TResult> SelectAsArray<TSource, TResult>(this ImmutableArray<TSource> array, Func<TSource, int, TResult> selector)
{
int length = array.Length;
if (length == 0)
{
return [];
}

ReadOnlySpan<TSource> sourceSpan = array.AsSpan();
TResult[] results = GC.AllocateUninitializedArray<TResult>(sourceSpan.Length);
TResult[] results = GC.AllocateUninitializedArray<TResult>(length);

Span<TResult> resultSpan = results.AsSpan();
for (int index = 0; index < sourceSpan.Length; index++)
Expand Down
30 changes: 0 additions & 30 deletions src/Snap.Hutao/Snap.Hutao/Model/CollectionsNameValue.cs

This file was deleted.

50 changes: 50 additions & 0 deletions src/Snap.Hutao/Snap.Hutao/Model/ImmutableCollectionsNameValue.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.

using System.Collections.Immutable;
using System.Runtime.InteropServices;

namespace Snap.Hutao.Model;

internal static class ImmutableCollectionsNameValue
{
public static ImmutableArray<NameValue<TEnum>> FromEnum<TEnum>()
where TEnum : struct, Enum
{
return ImmutableCollectionsMarshal.AsImmutableArray(Enum.GetValues<TEnum>()).SelectAsArray(DefaultCreateNameValue);
}

public static ImmutableArray<NameValue<TEnum>> FromEnum<TEnum>(Func<TEnum, bool> predicate)
where TEnum : struct, Enum
{
return From(Enum.GetValues<TEnum>(), predicate);
}

public static ImmutableArray<NameValue<TEnum>> FromEnum<TEnum>(Func<TEnum, string> nameSelector)
where TEnum : struct, Enum
{
return From(Enum.GetValues<TEnum>(), nameSelector);
}

public static ImmutableArray<NameValue<TSource>> From<TSource>(IEnumerable<TSource> sources)
{
return [.. sources.Select(DefaultCreateNameValue)];
}

public static ImmutableArray<NameValue<TSource>> From<TSource>(IEnumerable<TSource> sources, Func<TSource, bool> predicate)
{
return [.. sources.Where(predicate).Select(DefaultCreateNameValue)];
}

public static ImmutableArray<NameValue<TSource>> From<TSource>(IEnumerable<TSource> sources, Func<TSource, string> nameSelector)
{
return [.. sources.Select(x => new NameValue<TSource>(nameSelector(x), x))];
}

private static NameValue<TEnum> DefaultCreateNameValue<TEnum>(TEnum value)
{
string? name = value?.ToString();
ArgumentNullException.ThrowIfNull(name);
return new(name, value);
}
}
9 changes: 5 additions & 4 deletions src/Snap.Hutao/Snap.Hutao/Service/AppOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Snap.Hutao.UI.Xaml.Media.Backdrop;
using Snap.Hutao.Web.Bridge;
using Snap.Hutao.Web.Hoyolab;
using System.Collections.Immutable;

namespace Snap.Hutao.Service;

Expand Down Expand Up @@ -46,7 +47,7 @@ public bool IsUnobtainedWishItemVisible
set => SetOption(ref isUnobtainedWishItemVisible, SettingEntry.IsUnobtainedWishItemVisible, value);
}

public List<NameValue<BackdropType>> BackdropTypes { get; } = CollectionsNameValue.FromEnum<BackdropType>(type => type >= 0);
public ImmutableArray<NameValue<BackdropType>> BackdropTypes { get; } = ImmutableCollectionsNameValue.FromEnum<BackdropType>(type => type >= 0);

public BackdropType BackdropType
{
Expand All @@ -67,7 +68,7 @@ public ElementTheme ElementTheme
set => SetOption(ref elementTheme, SettingEntry.ElementTheme, value, EnumToStringOrEmpty);
}

public List<NameValue<BackgroundImageType>> BackgroundImageTypes { get; } = CollectionsNameValue.FromEnum<BackgroundImageType>(type => type.GetLocalizedDescription());
public ImmutableArray<NameValue<BackgroundImageType>> BackgroundImageTypes { get; } = ImmutableCollectionsNameValue.FromEnum<BackgroundImageType>(type => type.GetLocalizedDescription());

public BackgroundImageType BackgroundImageType
{
Expand Down Expand Up @@ -96,15 +97,15 @@ public int DownloadSpeedLimitPerSecondInKiloByte
set => SetOption(ref downloadSpeedLimitPerSecondInKiloByte, SettingEntry.DownloadSpeedLimitPerSecondInKiloByte, value);
}

public List<NameValue<PackageConverterType>> PackageConverterTypes { get; } = CollectionsNameValue.FromEnum<PackageConverterType>();
public ImmutableArray<NameValue<PackageConverterType>> PackageConverterTypes { get; } = ImmutableCollectionsNameValue.FromEnum<PackageConverterType>();

public PackageConverterType PackageConverterType
{
get => GetOption(ref packageConverterType, SettingEntry.PackageConverterType, Enum.Parse<PackageConverterType>, PackageConverterType.ScatteredFiles);
set => SetOption(ref packageConverterType, SettingEntry.PackageConverterType, value, EnumToStringOrEmpty);
}

public List<NameValue<BridgeShareSaveType>> BridgeShareSaveTypes { get; } = CollectionsNameValue.FromEnum<BridgeShareSaveType>(type => type.GetLocalizedDescription());
public ImmutableArray<NameValue<BridgeShareSaveType>> BridgeShareSaveTypes { get; } = ImmutableCollectionsNameValue.FromEnum<BridgeShareSaveType>(type => type.GetLocalizedDescription());

public BridgeShareSaveType BridgeShareSaveType
{
Expand Down

This file was deleted.

2 changes: 1 addition & 1 deletion src/Snap.Hutao/Snap.Hutao/Snap.Hutao.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@
<PackageReference Include="CommunityToolkit.Labs.WinUI.Shimmer" Version="0.1.230830" />
<PackageReference Include="CommunityToolkit.Labs.WinUI.TokenView" Version="0.1.230830" />
<PackageReference Include="CommunityToolkit.Labs.WinUI.TransitionHelper" Version="0.1.230830" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.3.2" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<PackageReference Include="CommunityToolkit.WinUI.Behaviors" Version="8.1.240916" />
<PackageReference Include="CommunityToolkit.WinUI.Collections" Version="8.1.240916" />
<PackageReference Include="CommunityToolkit.WinUI.Controls.HeaderedControls" Version="8.1.240916" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public unsafe HotKeyCombination(IServiceProvider serviceProvider, HWND hwnd, str

key = Enum.IsDefined(actual.Key) ? actual.Key : defaultKey;

keyNameValue = VirtualKeys.GetList().Single(v => v.Value == key);
keyNameValue = VirtualKeys.Values.Single(v => v.Value == key);
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/Snap.Hutao/Snap.Hutao/UI/Input/HotKey/HotKeyOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Snap.Hutao.Core.Setting;
using Snap.Hutao.Model;
using Snap.Hutao.Win32.UI.Input.KeyboardAndMouse;
using System.Collections.Immutable;
using System.Runtime.InteropServices;
using static Snap.Hutao.Win32.User32;

Expand Down Expand Up @@ -32,7 +33,7 @@ public HotKeyOptions(IServiceProvider serviceProvider)
MouseClickRepeatForeverKeyCombination = new(serviceProvider, hotKeyMessageWindow.HWND, SettingKeys.HotKeyMouseClickRepeatForever, 100000, default, VIRTUAL_KEY.VK_F8);
}

public List<NameValue<VIRTUAL_KEY>> VirtualKeys { get; } = Input.VirtualKeys.GetList();
public ImmutableArray<NameValue<VIRTUAL_KEY>> VirtualKeys { get; } = Input.VirtualKeys.Values;

public HotKeyCombination MouseClickRepeatForeverKeyCombination { get; set => SetProperty(ref field, value); }

Expand Down
42 changes: 16 additions & 26 deletions src/Snap.Hutao/Snap.Hutao/UI/Input/LowLevel/LowLevelKeyOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,65 +2,55 @@
// Licensed under the MIT license.

using CommunityToolkit.Mvvm.ComponentModel;
using JetBrains.Annotations;
using Snap.Hutao.Core.Setting;
using Snap.Hutao.Model;
using Snap.Hutao.Win32.UI.Input.KeyboardAndMouse;
// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract

namespace Snap.Hutao.UI.Input.LowLevel;

[SuppressMessage("", "SA1500")]
[SuppressMessage("", "SA1513")]
[Injection(InjectAs.Singleton)]
internal sealed partial class LowLevelKeyOptions : ObservableObject
{
private NameValue<VIRTUAL_KEY> webView2VideoPlayPauseKey;
private NameValue<VIRTUAL_KEY> webView2VideoFastForwardKey;
private NameValue<VIRTUAL_KEY> webView2VideoRewindKey;

public LowLevelKeyOptions()
{
// TODO: once the VirtualKeys no longer duplicate, use Single instead of First
VIRTUAL_KEY key = UnsafeLocalSetting.Get(SettingKeys.LowLevelKeyboardWebView2VideoPlayPause, VIRTUAL_KEY.VK__none_);
webView2VideoPlayPauseKey = VirtualKeys.GetList().First(n => n.Value == key);

key = UnsafeLocalSetting.Get(SettingKeys.LowLevelKeyboardWebView2VideoFastForward, VIRTUAL_KEY.VK__none_);
webView2VideoFastForwardKey = VirtualKeys.GetList().First(n => n.Value == key);

key = UnsafeLocalSetting.Get(SettingKeys.LowLevelKeyboardWebView2VideoRewind, VIRTUAL_KEY.VK__none_);
webView2VideoRewindKey = VirtualKeys.GetList().First(n => n.Value == key);
}

[UsedImplicitly]
public NameValue<VIRTUAL_KEY> WebView2VideoPlayPauseKey
{
get => webView2VideoPlayPauseKey;
get;
set
{
if (SetProperty(ref webView2VideoPlayPauseKey, value) && value is not null)
if (SetProperty(ref field, value) && value is not null)
{
UnsafeLocalSetting.Set(SettingKeys.LowLevelKeyboardWebView2VideoPlayPause, value.Value);
}
}
}
} = VirtualKeys.First(UnsafeLocalSetting.Get(SettingKeys.LowLevelKeyboardWebView2VideoPlayPause, VIRTUAL_KEY.VK__none_));

[UsedImplicitly]
public NameValue<VIRTUAL_KEY> WebView2VideoFastForwardKey
{
get => webView2VideoFastForwardKey;
get;
set
{
if (SetProperty(ref webView2VideoFastForwardKey, value) && value is not null)
if (SetProperty(ref field, value) && value is not null)
{
UnsafeLocalSetting.Set(SettingKeys.LowLevelKeyboardWebView2VideoFastForward, value.Value);
}
}
}
} = VirtualKeys.First(UnsafeLocalSetting.Get(SettingKeys.LowLevelKeyboardWebView2VideoFastForward, VIRTUAL_KEY.VK__none_));

[UsedImplicitly]
public NameValue<VIRTUAL_KEY> WebView2VideoRewindKey
{
get => webView2VideoRewindKey;
get;
set
{
if (SetProperty(ref webView2VideoRewindKey, value) && value is not null)
if (SetProperty(ref field, value) && value is not null)
{
UnsafeLocalSetting.Set(SettingKeys.LowLevelKeyboardWebView2VideoRewind, value.Value);
}
}
}
} = VirtualKeys.First(UnsafeLocalSetting.Get(SettingKeys.LowLevelKeyboardWebView2VideoRewind, VIRTUAL_KEY.VK__none_));
}
9 changes: 6 additions & 3 deletions src/Snap.Hutao/Snap.Hutao/UI/Input/VirtualKeys.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@

using Snap.Hutao.Model;
using Snap.Hutao.Win32.UI.Input.KeyboardAndMouse;
using System.Collections.Immutable;

namespace Snap.Hutao.UI.Input;

internal static class VirtualKeys
{
private static readonly List<NameValue<VIRTUAL_KEY>> Values = CollectionsNameValue.FromEnum<VIRTUAL_KEY>();
public static ImmutableArray<NameValue<VIRTUAL_KEY>> Values { get; } = ImmutableCollectionsNameValue.FromEnum<VIRTUAL_KEY>();

public static List<NameValue<VIRTUAL_KEY>> GetList()
public static NameValue<VIRTUAL_KEY> First(VIRTUAL_KEY value)
{
return Values;
// The value may come from the result of a method call, so this method
// is intentionally made to avoid multiple calls to compute input value
return Values.First(n => n.Value == value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
using Snap.Hutao.Core.Setting;
using Snap.Hutao.Model;
using Snap.Hutao.Web.Hutao;
using System.Collections.Immutable;

namespace Snap.Hutao.ViewModel.Guide;

[Injection(InjectAs.Singleton)]
internal sealed partial class StaticResourceOptions : ObservableObject
{
public List<NameValue<StaticResourceQuality>> ImageQualities { get; } = CollectionsNameValue.FromEnum<StaticResourceQuality>(q => q.GetLocalizedDescription());
public ImmutableArray<NameValue<StaticResourceQuality>> ImageQualities { get; } = ImmutableCollectionsNameValue.FromEnum<StaticResourceQuality>(q => q.GetLocalizedDescription());

public NameValue<StaticResourceQuality>? ImageQuality
{
Expand All @@ -27,7 +28,7 @@ public NameValue<StaticResourceQuality>? ImageQuality
}
}

public List<NameValue<StaticResourceArchive>> ImageArchives { get; } = CollectionsNameValue.FromEnum<StaticResourceArchive>(a => a.GetLocalizedDescription());
public ImmutableArray<NameValue<StaticResourceArchive>> ImageArchives { get; } = ImmutableCollectionsNameValue.FromEnum<StaticResourceArchive>(a => a.GetLocalizedDescription());

public NameValue<StaticResourceArchive>? ImageArchive
{
Expand Down
3 changes: 2 additions & 1 deletion src/Snap.Hutao/Snap.Hutao/ViewModel/User/UserViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
using Snap.Hutao.Web.Hoyolab;
using Snap.Hutao.Web.Hoyolab.Passport;
using Snap.Hutao.Web.Response;
using System.Collections.Immutable;
using System.Text;
using EntityUser = Snap.Hutao.Model.Entity.User;

Expand All @@ -45,7 +46,7 @@ internal sealed partial class UserViewModel : ObservableObject

public AdvancedDbCollectionView<User, EntityUser>? Users { get => users; set => SetProperty(ref users, value); }

public List<NameValue<OverseaThirdPartyKind>> OverseaThirdPartyKinds { get; } = CollectionsNameValue.FromEnum<OverseaThirdPartyKind>(static kind => kind is OverseaThirdPartyKind.Twitter ? ThirdPartyIconConverter.TwitterName : kind.ToString());
public ImmutableArray<NameValue<OverseaThirdPartyKind>> OverseaThirdPartyKinds { get; } = ImmutableCollectionsNameValue.FromEnum<OverseaThirdPartyKind>(static kind => kind is OverseaThirdPartyKind.Twitter ? ThirdPartyIconConverter.TwitterName : kind.ToString());

internal void HandleUserOptionResult(UserOptionResult optionResult, string uid)
{
Expand Down

0 comments on commit 8a7315f

Please sign in to comment.