Compare commits

..

39 Commits

Author SHA1 Message Date
dependabot[bot]
47dda1bebc Bump the packages group in /src/Snap.Hutao with 1 update
Bumps the packages group in /src/Snap.Hutao with 1 update: [MSTest.TestAdapter](https://github.com/microsoft/testfx).


Updates `MSTest.TestAdapter` from 3.2.1 to 3.2.2
- [Release notes](https://github.com/microsoft/testfx/releases)
- [Changelog](https://github.com/microsoft/testfx/blob/main/docs/Changelog.md)
- [Commits](https://github.com/microsoft/testfx/compare/v3.2.1...v3.2.2)

---
updated-dependencies:
- dependency-name: MSTest.TestAdapter
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: packages
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-11 07:12:02 +00:00
Lightczx
1a300e8b9c fix predownload latest path and name 2024-03-11 11:47:43 +08:00
Lightczx
16e8a17614 disable launchoptions by default 2024-03-11 11:24:41 +08:00
Lightczx
a5c75f9465 revert BGI process waitforinputidle 2024-03-11 11:16:23 +08:00
Lightczx
0cb59808a1 refactor unlocking fps 2024-03-11 11:01:57 +08:00
Lightczx
d632002e4b Sync Scighost/Starward#692 2024-03-11 09:33:21 +08:00
DismissedLight
cf6a972d55 Update FeedbackPage.xaml 2024-03-10 22:39:11 +08:00
DismissedLight
e1a976f02d fix theme switch dropping shadow 2024-03-10 22:28:03 +08:00
DismissedLight
dbedc2a00d fix equal panel spacing 2024-03-10 22:23:10 +08:00
DismissedLight
03312f1d52 Merge pull request #1464 from DGP-Studio/fix/horizontal_equal_panel 2024-03-10 21:37:03 +08:00
qhy040404
47f29de9c6 fix measure 2024-03-10 21:30:15 +08:00
Lightczx
2a5e7e0136 temp progress 2024-03-10 17:30:57 +08:00
Lightczx
177e7a6233 fix #1459 2024-03-10 14:29:57 +08:00
DismissedLight
bd09b303ab Merge pull request #1456 from DGP-Studio/fix/darkmode
fix #1434
2024-03-10 14:13:10 +08:00
qhy040404
5538b74939 remove WindowOptions.UseSystemBackdrop 2024-03-10 12:16:30 +08:00
qhy040404
fda289421b code style 2024-03-10 12:16:30 +08:00
qhy040404
c0abe7f7c5 fix #1434 2024-03-10 12:16:30 +08:00
DismissedLight
e95732d448 Merge pull request #1454 from DGP-Studio/fix/navigate_crash 2024-03-10 12:10:13 +08:00
DismissedLight
9e52a87d11 Merge pull request #1457 from DGP-Studio/fix/composition_image_delay 2024-03-10 12:03:29 +08:00
qhy040404
66bce570cc Update build.cake 2024-03-10 10:46:46 +08:00
qhy040404
a5091134b0 fix typo 2024-03-10 10:46:46 +08:00
qhy040404
59c9845ad0 fix navigation crash 2024-03-10 10:46:46 +08:00
qhy040404
2db829e1e2 add delay to fix blink again 2024-03-10 10:46:37 +08:00
DismissedLight
1a64328270 Update GachaTypeComparer.cs 2024-03-09 16:48:37 +08:00
DismissedLight
1c847626c7 Merge pull request #1453 from Mikachu2333/develop 2024-03-08 16:12:08 +08:00
LinkChou
062a09c632 correct 2024-03-08 12:16:55 +08:00
LinkChou
7433c1832a add tips about 'test binary package' 2024-03-07 19:41:42 +08:00
Lightczx
252649f28c fix #1429 2024-03-07 16:56:18 +08:00
Lightczx
75dda65c55 impl #1432 2024-03-07 16:53:25 +08:00
Lightczx
a9b165882f fix #1433 2024-03-07 16:49:15 +08:00
Lightczx
e41e913558 code style 2024-03-07 16:44:06 +08:00
Lightczx
2d9125d369 fix #1443 2024-03-07 16:37:26 +08:00
DismissedLight
2c7a6d152c Merge pull request #1445 from DGP-Studio/feat/1434 2024-03-07 16:27:54 +08:00
Lightczx
0c4c509fd6 code style 2024-03-07 16:27:01 +08:00
DismissedLight
7dba08451c Merge branch 'develop' into feat/1434 2024-03-07 16:20:48 +08:00
DismissedLight
a55cb89fe8 Merge pull request #1452 from DGP-Studio/fix/layoutcycle_2 2024-03-07 16:20:17 +08:00
qhy040404
38577f9813 apply suggestion 2024-03-07 13:37:22 +08:00
qhy040404
91361ddab5 resolve review 2024-03-07 13:26:35 +08:00
qhy040404
5ced8f6c71 impl #1434 2024-03-07 13:26:35 +08:00
67 changed files with 1005 additions and 713 deletions

View File

@@ -35,7 +35,8 @@ Install with Snap Hutao MSIX package, can be installed with Windows built-in App
* [向我们提交 PR / Make Pull Requests](https://github.com/DGP-Studio/Snap.Hutao/pulls)
* [在 Crowdin 上进行本地化 / Translate Project on Crowdin](https://translate.hut.ao/)
* [为我们更新文档 / Enhance our Document ](https://github.com/DGP-Studio/Snap.Hutao.Docs)
* [为我们更新文档 / Enhance our Document](https://github.com/DGP-Studio/Snap.Hutao.Docs)
* [帮助我们测试程序 / Test Binary Package](https://hut.ao/development/contribute.html)
## 特别感谢 / Special Thanks

View File

@@ -69,6 +69,15 @@ else if (AppVeyor.IsRunningOnAppVeyor)
})[..^2];
Information($"Version: {version}");
}
else // Local
{
repoDir = System.Environment.CurrentDirectory;
outputPath = System.IO.Path.Combine(repoDir, "src", "output");
version = System.DateTime.Now.ToString("yyyy.M.d.") + ((int)((System.DateTime.Now - System.DateTime.Today).TotalSeconds / 86400 * 65535)).ToString();
Information($"Version: {version}");
}
Task("Build")
.IsDependentOn("Build binary package")
@@ -112,6 +121,17 @@ Task("Generate AppxManifest")
Information("Using Release configuration");
content = System.Text.RegularExpressions.Regex.Replace(content, " Publisher=\"([^\"]*)\"", " Publisher=\"CN=SignPath Foundation, O=SignPath Foundation, L=Lewes, S=Delaware, C=US\"");
}
else
{
Information("Using Local configuration.");
content = content
.Replace("Snap Hutao", "Snap Hutao Local")
.Replace("胡桃", "胡桃 Local")
.Replace("DGP Studio", "DGP Studio CI");
content = System.Text.RegularExpressions.Regex.Replace(content, " Name=\"([^\"]*)\"", " Name=\"E8B6E2B3-D2A0-4435-A81D-2A16AAF405C7\"");
content = System.Text.RegularExpressions.Regex.Replace(content, " Publisher=\"([^\"]*)\"", " Publisher=\"E=admin@dgp-studio.cn, CN=DGP Studio CI, OU=CI, O=DGP-Studio, L=San Jose, S=CA, C=US\"");
content = System.Text.RegularExpressions.Regex.Replace(content, " Version=\"([0-9\\.]+)\"", $" Version=\"{version}\"");
}
System.IO.File.WriteAllText(manifest, content);
@@ -173,6 +193,10 @@ Task("Build MSIX")
{
arguments = "pack /d " + binPath + " /p " + System.IO.Path.Combine(outputPath, $"Snap.Hutao-{version}.msix");
}
else
{
arguments = "pack /d " + binPath + " /p " + System.IO.Path.Combine(outputPath, $"Snap.Hutao.Local-{version}.msix");
}
var p = StartProcess(
"makeappx.exe",
new ProcessSettings

View File

@@ -13,7 +13,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.2.1" />
<PackageReference Include="MSTest.TestAdapter" Version="3.2.2" />
<PackageReference Include="MSTest.TestFramework" Version="3.2.2" />
<PackageReference Include="coverlet.collector" Version="6.0.1">
<PrivateAssets>all</PrivateAssets>

View File

@@ -1,10 +1,8 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using CommunityToolkit.WinUI;
using CommunityToolkit.WinUI.Controls;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Snap.Hutao.Control.Extension;
namespace Snap.Hutao.Control.AutoSuggestBox;

View File

@@ -168,6 +168,7 @@ internal abstract partial class CompositionImage : Microsoft.UI.Xaml.Controls.Co
if (surface.DecodedPhysicalSize.Size() <= 0D)
{
await Task.WhenAny(surfaceLoadTaskCompletionSource.Task, Task.Delay(5000, token)).ConfigureAwait(true);
await Task.Delay(50, token).ConfigureAwait(true);
}
LoadImageSurfaceCompleted(surface);

View File

@@ -0,0 +1,58 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Xaml;
using Windows.Foundation;
namespace Snap.Hutao.Control.Panel;
[DependencyProperty("MinItemWidth", typeof(double))]
[DependencyProperty("Spacing", typeof(double))]
internal partial class HorizontalEqualPanel : Microsoft.UI.Xaml.Controls.Panel
{
public HorizontalEqualPanel()
{
Loaded += OnLoaded;
SizeChanged += OnSizeChanged;
}
protected override Size MeasureOverride(Size availableSize)
{
foreach (UIElement child in Children)
{
// ScrollViewer will always return an Infinity Size, we should use ActualWidth for this situation.
double availableWidth = double.IsInfinity(availableSize.Width) ? ActualWidth : availableSize.Width;
double childAvailableWidth = (availableWidth + Spacing) / Children.Count;
double childMaxAvailableWidth = Math.Max(MinItemWidth, childAvailableWidth);
child.Measure(new(childMaxAvailableWidth - Spacing, ActualHeight));
}
return base.MeasureOverride(availableSize);
}
protected override Size ArrangeOverride(Size finalSize)
{
int itemCount = Children.Count;
double availableWidthPerItem = (finalSize.Width - (Spacing * (itemCount - 1))) / itemCount;
double actualItemWidth = Math.Max(MinItemWidth, availableWidthPerItem);
double offset = 0;
foreach (UIElement child in Children)
{
child.Arrange(new Rect(offset, 0, actualItemWidth, finalSize.Height));
offset += actualItemWidth + Spacing;
}
return finalSize;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
MinWidth = (MinItemWidth * Children.Count) + (Spacing * (Children.Count - 1));
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
InvalidateMeasure();
}
}

View File

@@ -4,21 +4,19 @@
xmlns:cwm="using:CommunityToolkit.WinUI.Media">
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Light">
<cwm:AttachedCardShadow
x:Key="CompatCardShadow"
BlurRadius="8"
Opacity="0.14"
Offset="0,4,0"/>
<x:Double x:Key="CompatShadowThemeOpacity">0.14</x:Double>
</ResourceDictionary>
<ResourceDictionary x:Key="Dark">
<cwm:AttachedCardShadow
x:Key="CompatCardShadow"
BlurRadius="8"
Opacity="0.28"
Offset="0,4,0"/>
<x:Double x:Key="CompatShadowThemeOpacity">0.28</x:Double>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
<cwm:AttachedCardShadow
x:Key="CompatCardShadow"
BlurRadius="8"
Opacity="{ThemeResource CompatShadowThemeOpacity}"
Offset="0,4,0"/>
<Style x:Key="BorderCardStyle" TargetType="Border">
<Setter Property="Background" Value="{ThemeResource CardBackgroundFillColorDefaultBrush}"/>
<Setter Property="BorderBrush" Value="{ThemeResource CardStrokeColorDefaultBrush}"/>

View File

@@ -1,8 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using System.Numerics;
namespace Snap.Hutao.Core.ExceptionService;
internal sealed class HutaoException : Exception
@@ -34,6 +32,14 @@ internal sealed class HutaoException : Exception
}
}
public static void ThrowIfNot(bool condition, HutaoExceptionKind kind, string message, Exception? innerException = default)
{
if (!condition)
{
throw new HutaoException(kind, message, innerException);
}
}
public static HutaoException ServiceTypeCastFailed<TFrom, TTo>(string name, Exception? innerException = default)
{
string message = $"This instance of '{typeof(TFrom).FullName}' '{name}' doesn't implement '{typeof(TTo).FullName}'";

View File

@@ -6,8 +6,15 @@ namespace Snap.Hutao.Core.ExceptionService;
internal enum HutaoExceptionKind
{
None,
// Foundation
ServiceTypeCastFailed,
// IO
FileSystemCreateFileInsufficientPermissions,
PrivateNamedPipeContentHashIncorrect,
// Service
GachaStatisticsInvalidItemId,
GameFpsUnlockingFailed,
}

View File

@@ -9,6 +9,7 @@ namespace Snap.Hutao.Core.Validation;
/// 封装验证方法,简化微软验证
/// </summary>
[HighQuality]
[Obsolete("Use HutaoException instead")]
internal static class Must
{
/// <summary>

View File

@@ -69,12 +69,10 @@ internal sealed class WindowController
window.Activate();
options.BringToForeground();
if (options.UseSystemBackdrop)
{
AppOptions appOptions = serviceProvider.GetRequiredService<AppOptions>();
UpdateSystemBackdrop(appOptions.BackdropType);
appOptions.PropertyChanged += OnOptionsPropertyChanged;
}
AppOptions appOptions = serviceProvider.GetRequiredService<AppOptions>();
UpdateElementTheme(appOptions.ElementTheme);
UpdateSystemBackdrop(appOptions.BackdropType);
appOptions.PropertyChanged += OnOptionsPropertyChanged;
subclass.Initialize();
@@ -122,13 +120,17 @@ internal sealed class WindowController
private void OnOptionsPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName is nameof(AppOptions.BackdropType))
if (sender is not AppOptions options)
{
if (sender is AppOptions options)
{
UpdateSystemBackdrop(options.BackdropType);
}
return;
}
_ = e.PropertyName switch
{
nameof(AppOptions.BackdropType) => UpdateSystemBackdrop(options.BackdropType),
nameof(AppOptions.ElementTheme) => UpdateElementTheme(options.ElementTheme),
_ => false,
};
}
private void OnWindowClosed(object sender, WindowEventArgs args)
@@ -158,7 +160,7 @@ internal sealed class WindowController
}
}
private void UpdateSystemBackdrop(BackdropType backdropType)
private bool UpdateSystemBackdrop(BackdropType backdropType)
{
window.SystemBackdrop = backdropType switch
{
@@ -168,6 +170,15 @@ internal sealed class WindowController
BackdropType.Acrylic => new DesktopAcrylicBackdrop(),
_ => null,
};
return true;
}
private bool UpdateElementTheme(ElementTheme theme)
{
((FrameworkElement)window.Content).RequestedTheme = theme;
return true;
}
private void UpdateTitleButtonColor()

View File

@@ -41,21 +41,18 @@ internal readonly struct WindowOptions
/// </summary>
public readonly bool PersistSize;
public readonly bool UseSystemBackdrop;
/// <summary>
/// 是否使用 Win UI 3 自带的拓展标题栏实现
/// </summary>
public readonly bool UseLegacyDragBarImplementation = !AppWindowTitleBar.IsCustomizationSupported();
public WindowOptions(Window window, FrameworkElement titleBar, SizeInt32 initSize, bool persistSize = false, bool useSystemBackdrop = true)
public WindowOptions(Window window, FrameworkElement titleBar, SizeInt32 initSize, bool persistSize = false)
{
Hwnd = WindowNative.GetWindowHandle(window);
InputNonClientPointerSource = InputNonClientPointerSource.GetForWindowId(window.AppWindow.Id);
TitleBar = titleBar;
InitSize = initSize;
PersistSize = persistSize;
UseSystemBackdrop = useSystemBackdrop;
}
/// <summary>

View File

@@ -13,6 +13,7 @@ internal sealed partial class SettingEntry
public const string Culture = "Culture";
public const string SystemBackdropType = "SystemBackdropType";
public const string ElementTheme = "ElementTheme";
public const string BackgroundImageType = "BackgroundImageType";
public const string AnnouncementRegion = "AnnouncementRegion";

View File

@@ -1,8 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Model.Primitive;
namespace Snap.Hutao.Model.Metadata.Achievement;
/// <summary>

View File

@@ -1,7 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Model.Intrinsic;
using Snap.Hutao.Model.Primitive;
namespace Snap.Hutao.Model.Metadata.Furniture;

View File

@@ -1,7 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Model.Intrinsic;
using Snap.Hutao.Model.Primitive;
namespace Snap.Hutao.Model.Metadata.Furniture;

View File

@@ -1,7 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Model.Intrinsic;
using Snap.Hutao.Model.Primitive;
namespace Snap.Hutao.Model.Metadata;

View File

@@ -60,45 +60,45 @@
: and then encoded with base64 encoding.
-->
<xsd:schema xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="root">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0"/>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string"/>
<xsd:attribute name="type" type="xsd:string"/>
<xsd:attribute name="mimetype" type="xsd:string"/>
<xsd:attribute ref="xml:space"/>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string"/>
<xsd:attribute name="name" type="xsd:string"/>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1"/>
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2"/>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1"/>
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3"/>
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4"/>
<xsd:attribute ref="xml:space"/>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1"/>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required"/>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
@@ -186,6 +186,15 @@
<data name="CoreWebView2HelperVersionUndetected" xml:space="preserve">
<value>No WebView2 Runtime detected</value>
</data>
<data name="CoreWindowThemeDark" xml:space="preserve">
<value>Dark</value>
</data>
<data name="CoreWindowThemeLight" xml:space="preserve">
<value>Light</value>
</data>
<data name="CoreWindowThemeSystem" xml:space="preserve">
<value>System</value>
</data>
<data name="FilePickerExportCommit" xml:space="preserve">
<value>Export</value>
</data>

View File

@@ -189,6 +189,15 @@
<data name="CoreWindowHotkeyCombinationRegisterFailed" xml:space="preserve">
<value>[{0}] 热键 [{1}] 注册失败</value>
</data>
<data name="CoreWindowThemeDark" xml:space="preserve">
<value>深色</value>
</data>
<data name="CoreWindowThemeLight" xml:space="preserve">
<value>浅色</value>
</data>
<data name="CoreWindowThemeSystem" xml:space="preserve">
<value>跟随系统</value>
</data>
<data name="FilePickerExportCommit" xml:space="preserve">
<value>导出</value>
</data>
@@ -2220,7 +2229,7 @@
<value>在游戏启动后尝试启动并使用 Better GI 进行自动化任务</value>
</data>
<data name="ViewPageLaunchGameBetterGIHeader" xml:space="preserve">
<value>Better GI</value>
<value>自动化任务</value>
</data>
<data name="ViewPageLaunchGameCommonHeader" xml:space="preserve">
<value>常规</value>
@@ -2238,7 +2247,7 @@
<value>文件</value>
</data>
<data name="ViewPageLaunchGameInterProcessHeader" xml:space="preserve">
<value>进程</value>
<value>进程联动</value>
</data>
<data name="ViewPageLaunchGameMonitorsDescription" xml:space="preserve">
<value>在指定的显示器上运行</value>
@@ -2372,6 +2381,9 @@
<data name="ViewPageSettingBackgroundImageHeader" xml:space="preserve">
<value>背景图片</value>
</data>
<data name="ViewPageSettingBackgroundImageLocalFolderCopyrightHeader" xml:space="preserve">
<value>当前背景为本地图片,如遇版权问题由用户个人负责</value>
</data>
<data name="ViewPageSettingCacheFolderDescription" xml:space="preserve">
<value>图片缓存 在此处存放</value>
</data>
@@ -2627,6 +2639,12 @@
<data name="ViewPageSettingStoreReviewNavigate" xml:space="preserve">
<value>评价软件</value>
</data>
<data name="ViewPageSettingThemeDescription" xml:space="preserve">
<value>更改窗体的颜色主题</value>
</data>
<data name="ViewPageSettingThemeHeader" xml:space="preserve">
<value>颜色主题</value>
</data>
<data name="ViewPageSettingTranslateNavigate" xml:space="preserve">
<value>贡献翻译</value>
</data>

View File

@@ -1,6 +1,7 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Xaml;
using Snap.Hutao.Core.Windowing;
using Snap.Hutao.Model;
using Snap.Hutao.Model.Entity;
@@ -16,6 +17,7 @@ internal sealed partial class AppOptions : DbStoreOptions
{
private bool? isEmptyHistoryWishVisible;
private BackdropType? backdropType;
private ElementTheme? elementTheme;
private BackgroundImageType? backgroundImageType;
private Region? region;
private string? geetestCustomCompositeUrl;
@@ -34,6 +36,19 @@ internal sealed partial class AppOptions : DbStoreOptions
set => SetOption(ref backdropType, SettingEntry.SystemBackdropType, value, EnumToStringOrEmpty);
}
public Lazy<List<NameValue<ElementTheme>>> LazyElementThemes { get; } = new(() =>
[
new(SH.CoreWindowThemeLight, ElementTheme.Light),
new(SH.CoreWindowThemeDark, ElementTheme.Dark),
new(SH.CoreWindowThemeSystem, ElementTheme.Default),
]);
public ElementTheme ElementTheme
{
get => GetOption(ref elementTheme, SettingEntry.ElementTheme, EnumParse<ElementTheme>, ElementTheme.Default).Value;
set => SetOption(ref elementTheme, SettingEntry.ElementTheme, value, EnumToStringOrEmpty);
}
public List<NameValue<BackgroundImageType>> BackgroundImageTypes { get; } = CollectionsNameValue.FromEnum<BackgroundImageType>(type => type.GetLocalizedDescription());
public BackgroundImageType BackgroundImageType

View File

@@ -37,7 +37,7 @@ internal sealed partial class BackgroundImageService : IBackgroundImageService
return new(true, default!);
}
string path = System.Random.Shared.GetItems([..backgroundSet], 1)[0];
string path = System.Random.Shared.GetItems([.. backgroundSet], 1)[0];
backgroundSet.Remove(path);
if (string.Equals(path, previous?.Path, StringComparison.OrdinalIgnoreCase))

View File

@@ -3,7 +3,6 @@
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Model.Intrinsic;
using Snap.Hutao.Model.Metadata;
using Snap.Hutao.Model.Metadata.Avatar;
using Snap.Hutao.Model.Metadata.Weapon;
using Snap.Hutao.Service.Metadata;

View File

@@ -18,9 +18,9 @@ internal sealed class GachaTypeComparer : IComparer<GachaType>
KeyValuePair.Create(GachaType.ActivityAvatar, 0),
KeyValuePair.Create(GachaType.SpecialActivityAvatar, 1),
KeyValuePair.Create(GachaType.ActivityWeapon, 2),
KeyValuePair.Create(GachaType.Standard, 3),
KeyValuePair.Create(GachaType.NewBie, 4),
KeyValuePair.Create(GachaType.ActivityCity, 5),
KeyValuePair.Create(GachaType.ActivityCity, 3),
KeyValuePair.Create(GachaType.Standard, 4),
KeyValuePair.Create(GachaType.NewBie, 5),
]);
/// <summary>

View File

@@ -38,6 +38,10 @@ internal sealed class PullPrediction
typedWishSummary.PredictedPullLeftToOrange = result.PredictedPullLeftToOrange;
typedWishSummary.IsPredictPullAvailable = true;
}
else
{
await barrier.SignalAndWaitAsync().ConfigureAwait(false);
}
}
private static PredictResult PredictCore(List<PullCount> distribution, TypedWishSummary typedWishSummary)

View File

@@ -5,7 +5,6 @@ using Snap.Hutao.Model.Entity;
using Snap.Hutao.Model.Intrinsic;
using Snap.Hutao.Model.Metadata.Abstraction;
using Snap.Hutao.ViewModel.GachaLog;
using Snap.Hutao.Web.Hoyolab.Hk4e.Event.GachaInfo;
namespace Snap.Hutao.Service.GachaLog.Factory;

View File

@@ -2,10 +2,6 @@
// Licensed under the MIT license.
using Snap.Hutao.Model.Entity;
using Snap.Hutao.Model.Metadata;
using Snap.Hutao.Model.Metadata.Avatar;
using Snap.Hutao.Model.Metadata.Weapon;
using Snap.Hutao.Model.Primitive;
using Snap.Hutao.Service.GachaLog.Factory;
using Snap.Hutao.Service.Metadata;
using Snap.Hutao.Service.Metadata.ContextAbstraction;

View File

@@ -5,7 +5,6 @@ using Snap.Hutao.Core.Database;
using Snap.Hutao.Core.Diagnostics;
using Snap.Hutao.Model.Entity;
using Snap.Hutao.Model.InterChange.GachaLog;
using Snap.Hutao.Model.Primitive;
using Snap.Hutao.Service.GachaLog.Factory;
using Snap.Hutao.Service.GachaLog.QueryProvider;
using Snap.Hutao.Service.Metadata;

View File

@@ -109,7 +109,7 @@ internal sealed class LaunchOptions : DbStoreOptions
public bool IsEnabled
{
get => GetOption(ref isEnabled, SettingEntry.LaunchIsLaunchOptionsEnabled, true);
get => GetOption(ref isEnabled, SettingEntry.LaunchIsLaunchOptionsEnabled, false);
set => SetOption(ref isEnabled, SettingEntry.LaunchIsLaunchOptionsEnabled, value);
}

View File

@@ -17,9 +17,9 @@ internal sealed class LaunchStatus
public string Description { get; set; }
public static LaunchStatus FromUnlockStatus(UnlockerStatus unlockerStatus)
public static LaunchStatus FromUnlockState(GameFpsUnlockerState unlockerState)
{
if (unlockerStatus.FindModuleState == FindModuleResult.Ok)
if (unlockerState.FindModuleResult == FindModuleResult.Ok)
{
return new(LaunchPhase.UnlockFpsSucceed, SH.ServiceGameLaunchPhaseUnlockFpsSucceed);
}

View File

@@ -30,6 +30,7 @@ internal sealed class LaunchExecutionBetterGenshinImpactAutomationHandlder : ILa
}
catch (InvalidOperationException)
{
context.Logger.LogInformation("Failed to wait Input idle waiting");
return;
}

View File

@@ -1,18 +1,27 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using System.Diagnostics;
namespace Snap.Hutao.Service.Game.Launching.Handler;
internal sealed class LaunchExecutionEnsureGameNotRunningHandler : ILaunchExecutionDelegateHandler
{
public static bool IsGameRunning([NotNullWhen(true)] out System.Diagnostics.Process? runningProcess)
public static bool IsGameRunning([NotNullWhen(true)] out Process? runningProcess)
{
int currentSessionId = Process.GetCurrentProcess().SessionId;
// GetProcesses once and manually loop is O(n)
foreach (ref readonly System.Diagnostics.Process process in System.Diagnostics.Process.GetProcesses().AsSpan())
foreach (ref readonly Process process in Process.GetProcesses().AsSpan())
{
if (string.Equals(process.ProcessName, GameConstants.YuanShenProcessName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(process.ProcessName, GameConstants.GenshinImpactProcessName, StringComparison.OrdinalIgnoreCase))
{
if (process.SessionId != currentSessionId)
{
continue;
}
runningProcess = process;
return true;
}
@@ -24,7 +33,7 @@ internal sealed class LaunchExecutionEnsureGameNotRunningHandler : ILaunchExecut
public async ValueTask OnExecutionAsync(LaunchExecutionContext context, LaunchExecutionDelegate next)
{
if (IsGameRunning(out System.Diagnostics.Process? process))
if (IsGameRunning(out Process? process))
{
context.Logger.LogInformation("Game process detected, id: {Id}", process.Id);

View File

@@ -18,12 +18,13 @@ internal sealed class LaunchExecutionUnlockFpsHandler : ILaunchExecutionDelegate
context.Progress.Report(new(LaunchPhase.UnlockingFps, SH.ServiceGameLaunchPhaseUnlockingFps));
IProgressFactory progressFactory = context.ServiceProvider.GetRequiredService<IProgressFactory>();
IProgress<UnlockerStatus> progress = progressFactory.CreateForMainThread<UnlockerStatus>(status => context.Progress.Report(LaunchStatus.FromUnlockStatus(status)));
GameFpsUnlocker unlocker = context.ServiceProvider.CreateInstance<GameFpsUnlocker>(context.Process);
IProgress<GameFpsUnlockerState> progress = progressFactory.CreateForMainThread<GameFpsUnlockerState>(status => context.Progress.Report(LaunchStatus.FromUnlockState(status)));
GameFpsUnlocker unlocker = new(context.ServiceProvider, context.Process, new(100, 20000, 3000), progress);
try
{
await unlocker.UnlockAsync(new(100, 20000, 3000), progress, context.CancellationToken).ConfigureAwait(false);
await unlocker.UnlockAsync(context.CancellationToken).ConfigureAwait(false);
unlocker.PostUnlockAsync(context.CancellationToken).SafeForget();
}
catch (InvalidOperationException ex)
{

View File

@@ -24,25 +24,25 @@ internal sealed class LaunchExecutionInvoker
handlers.Enqueue(new LaunchExecutionGameProcessInitializationHandler());
handlers.Enqueue(new LaunchExecutionSetDiscordActivityHandler());
handlers.Enqueue(new LaunchExecutionGameProcessStartHandler());
handlers.Enqueue(new LaunchExecutionUnlockFpsHandler());
handlers.Enqueue(new LaunchExecutionStarwardPlayTimeStatisticsHandler());
handlers.Enqueue(new LaunchExecutionBetterGenshinImpactAutomationHandlder());
handlers.Enqueue(new LaunchExecutionUnlockFpsHandler());
handlers.Enqueue(new LaunchExecutionGameProcessExitHandler());
}
public async ValueTask<LaunchExecutionResult> InvokeAsync(LaunchExecutionContext context)
{
await InvokeHandlerAsync(context).ConfigureAwait(false);
await RecursiveInvokeHandlerAsync(context).ConfigureAwait(false);
return context.Result;
}
private async ValueTask<LaunchExecutionContext> InvokeHandlerAsync(LaunchExecutionContext context)
private async ValueTask<LaunchExecutionContext> RecursiveInvokeHandlerAsync(LaunchExecutionContext context)
{
if (handlers.TryDequeue(out ILaunchExecutionDelegateHandler? handler))
{
string typeName = TypeNameHelper.GetTypeDisplayName(handler, false);
context.Logger.LogInformation("Handler [{Handler}] begin execution", typeName);
await handler.OnExecutionAsync(context, () => InvokeHandlerAsync(context)).ConfigureAwait(false);
await handler.OnExecutionAsync(context, () => RecursiveInvokeHandlerAsync(context)).ConfigureAwait(false);
context.Logger.LogInformation("Handler [{Handler}] end execution", typeName);
}

View File

@@ -168,9 +168,14 @@ internal sealed partial class PackageConverter
{
try
{
using (Stream remoteSteam = await httpClient.GetStreamAsync(pkgVersionUrl).ConfigureAwait(false))
// Server might close the connection shortly,
// we have to cache the content immediately.
using (HttpResponseMessage responseMessage = await httpClient.GetAsync(pkgVersionUrl, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false))
{
return await GetVersionItemsAsync(remoteSteam).ConfigureAwait(false);
using (Stream remoteSteam = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
return await GetVersionItemsAsync(remoteSteam).ConfigureAwait(false);
}
}
}
catch (IOException ex)

View File

@@ -0,0 +1,82 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Win32.Foundation;
using Snap.Hutao.Win32.Memory;
using System.Diagnostics;
using static Snap.Hutao.Win32.Kernel32;
namespace Snap.Hutao.Service.Game.Unlocker;
internal static class GameFpsAddress
{
#pragma warning disable SA1310
private const byte ASM_CALL = 0xE8;
private const byte ASM_JMP = 0xE9;
#pragma warning restore SA1310
public static unsafe void UnsafeFindFpsAddress(GameFpsUnlockerState state, in RequiredGameModule requiredGameModule)
{
bool readOk = UnsafeReadModulesMemory(state.GameProcess, requiredGameModule, out VirtualMemory localMemory);
HutaoException.ThrowIfNot(readOk, HutaoExceptionKind.GameFpsUnlockingFailed, SH.ServiceGameUnlockerReadModuleMemoryCopyVirtualMemoryFailed);
using (localMemory)
{
int offset = IndexOfPattern(localMemory.AsSpan()[(int)requiredGameModule.UnityPlayer.Size..]);
HutaoException.ThrowIfNot(offset >= 0, HutaoExceptionKind.GameFpsUnlockingFailed, SH.ServiceGameUnlockerInterestedPatternNotFound);
byte* pLocalMemory = (byte*)localMemory.Pointer;
ref readonly Module unityPlayer = ref requiredGameModule.UnityPlayer;
ref readonly Module userAssembly = ref requiredGameModule.UserAssembly;
nuint localMemoryUnityPlayerAddress = (nuint)pLocalMemory;
nuint localMemoryUserAssemblyAddress = localMemoryUnityPlayerAddress + unityPlayer.Size;
nuint rip = localMemoryUserAssemblyAddress + (uint)offset;
rip += 5U;
rip += (nuint)(*(int*)(rip + 2U) + 6);
nuint address = userAssembly.Address + (rip - localMemoryUserAssemblyAddress);
nuint ptr = 0;
SpinWait.SpinUntil(() => UnsafeReadProcessMemory(state.GameProcess, address, out ptr) && ptr != 0);
rip = ptr - unityPlayer.Address + localMemoryUnityPlayerAddress;
while (*(byte*)rip is ASM_CALL or ASM_JMP)
{
rip += (nuint)(*(int*)(rip + 1) + 5);
}
nuint localMemoryActualAddress = rip + *(uint*)(rip + 2) + 6;
nuint actualOffset = localMemoryActualAddress - localMemoryUnityPlayerAddress;
state.FpsAddress = unityPlayer.Address + actualOffset;
}
}
private static int IndexOfPattern(in ReadOnlySpan<byte> memory)
{
// B9 3C 00 00 00 FF 15
ReadOnlySpan<byte> part = [0xB9, 0x3C, 0x00, 0x00, 0x00, 0xFF, 0x15];
return memory.IndexOf(part);
}
private static unsafe bool UnsafeReadModulesMemory(Process process, in RequiredGameModule moduleEntryInfo, out VirtualMemory memory)
{
ref readonly Module unityPlayer = ref moduleEntryInfo.UnityPlayer;
ref readonly Module userAssembly = ref moduleEntryInfo.UserAssembly;
memory = new VirtualMemory(unityPlayer.Size + userAssembly.Size);
return ReadProcessMemory(process.Handle, (void*)unityPlayer.Address, memory.AsSpan()[..(int)unityPlayer.Size], out _)
&& ReadProcessMemory(process.Handle, (void*)userAssembly.Address, memory.AsSpan()[(int)unityPlayer.Size..], out _);
}
private static unsafe bool UnsafeReadProcessMemory(Process process, nuint baseAddress, out nuint value)
{
value = 0;
bool result = ReadProcessMemory((HANDLE)process.Handle, (void*)baseAddress, ref value, out _);
HutaoException.ThrowIfNot(result, HutaoExceptionKind.GameFpsUnlockingFailed, SH.ServiceGameUnlockerReadProcessMemoryPointerAddressFailed);
return result;
}
}

View File

@@ -1,11 +1,9 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Core.Diagnostics;
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Win32.Foundation;
using Snap.Hutao.Win32.Memory;
using Snap.Hutao.Win32.System.ProcessStatus;
using System.Runtime.InteropServices;
using System.Diagnostics;
using static Snap.Hutao.Win32.Kernel32;
namespace Snap.Hutao.Service.Game.Unlocker;
@@ -17,255 +15,54 @@ namespace Snap.Hutao.Service.Game.Unlocker;
[HighQuality]
internal sealed class GameFpsUnlocker : IGameFpsUnlocker
{
private readonly System.Diagnostics.Process gameProcess;
private readonly LaunchOptions launchOptions;
private readonly UnlockerStatus status = new();
private readonly GameFpsUnlockerState state = new();
/// <summary>
/// 构造一个新的 <see cref="GameFpsUnlocker"/> 对象,
/// 每个解锁器只能解锁一次原神的进程,
/// 再次解锁需要重新创建对象
/// <para/>
/// 解锁器需要在管理员模式下才能正确的完成解锁操作,
/// 非管理员模式不能解锁
/// </summary>
/// <param name="serviceProvider">服务提供器</param>
/// <param name="gameProcess">游戏进程</param>
public GameFpsUnlocker(IServiceProvider serviceProvider, System.Diagnostics.Process gameProcess)
public GameFpsUnlocker(IServiceProvider serviceProvider, Process gameProcess, in UnlockTimingOptions options, IProgress<GameFpsUnlockerState> progress)
{
launchOptions = serviceProvider.GetRequiredService<LaunchOptions>();
this.gameProcess = gameProcess;
state.GameProcess = gameProcess;
state.TimingOptions = options;
state.Progress = progress;
}
/// <inheritdoc/>
public async ValueTask UnlockAsync(UnlockTimingOptions options, IProgress<UnlockerStatus> progress, CancellationToken token = default)
public async ValueTask UnlockAsync(CancellationToken token = default)
{
Verify.Operation(status.IsUnlockerValid, "This Unlocker is invalid");
HutaoException.ThrowIfNot(state.IsUnlockerValid, HutaoExceptionKind.GameFpsUnlockingFailed, "This Unlocker is invalid");
(FindModuleResult result, RequiredGameModule gameModule) = await GameProcessModule.FindModuleAsync(state).ConfigureAwait(false);
HutaoException.ThrowIfNot(result != FindModuleResult.TimeLimitExeeded, HutaoExceptionKind.GameFpsUnlockingFailed, SH.ServiceGameUnlockerFindModuleTimeLimitExeeded);
HutaoException.ThrowIfNot(result != FindModuleResult.NoModuleFound, HutaoExceptionKind.GameFpsUnlockingFailed, SH.ServiceGameUnlockerFindModuleNoModuleFound);
(FindModuleResult result, GameModule moduleEntryInfo) = await FindModuleAsync(options.FindModuleDelay, options.FindModuleLimit).ConfigureAwait(false);
Verify.Operation(result != FindModuleResult.TimeLimitExeeded, SH.ServiceGameUnlockerFindModuleTimeLimitExeeded);
Verify.Operation(result != FindModuleResult.NoModuleFound, SH.ServiceGameUnlockerFindModuleNoModuleFound);
// Read UnityPlayer.dll
UnsafeFindFpsAddress(moduleEntryInfo);
progress.Report(status);
// When player switch between scenes, we have to re adjust the fps
// So we keep a loop here
await LoopAdjustFpsAsync(options.AdjustFpsDelay, progress, token).ConfigureAwait(false);
GameFpsAddress.UnsafeFindFpsAddress(state, gameModule);
state.Report();
}
private static unsafe bool UnsafeReadModulesMemory(System.Diagnostics.Process process, in GameModule moduleEntryInfo, out VirtualMemory memory)
public async ValueTask PostUnlockAsync(CancellationToken token = default)
{
ref readonly Module unityPlayer = ref moduleEntryInfo.UnityPlayer;
ref readonly Module userAssembly = ref moduleEntryInfo.UserAssembly;
memory = new VirtualMemory(unityPlayer.Size + userAssembly.Size);
return ReadProcessMemory(process.Handle, (void*)unityPlayer.Address, memory.AsSpan()[..(int)unityPlayer.Size], out _)
&& ReadProcessMemory(process.Handle, (void*)userAssembly.Address, memory.AsSpan()[(int)unityPlayer.Size..], out _);
}
private static unsafe bool UnsafeReadProcessMemory(System.Diagnostics.Process process, nuint baseAddress, out nuint value)
{
value = 0;
bool result = ReadProcessMemory((HANDLE)process.Handle, (void*)baseAddress, ref value, out _);
Verify.Operation(result, SH.ServiceGameUnlockerReadProcessMemoryPointerAddressFailed);
return result;
}
private static unsafe bool UnsafeWriteProcessMemory(System.Diagnostics.Process process, nuint baseAddress, int value)
{
return WriteProcessMemory((HANDLE)process.Handle, (void*)baseAddress, ref value, out _);
}
private static unsafe FindModuleResult UnsafeTryFindModule(in HANDLE hProcess, in ReadOnlySpan<char> moduleName, out Module module)
{
HMODULE[] buffer = new HMODULE[128];
if (!K32EnumProcessModules(hProcess, buffer, out uint actualSize))
{
Marshal.ThrowExceptionForHR(Marshal.GetLastPInvokeError());
}
if (actualSize == 0)
{
module = default!;
return FindModuleResult.NoModuleFound;
}
foreach (ref readonly HMODULE hModule in buffer.AsSpan()[..(int)(actualSize / sizeof(HMODULE))])
{
char[] baseName = new char[256];
if (K32GetModuleBaseNameW(hProcess, hModule, baseName) == 0)
{
continue;
}
fixed (char* lpBaseName = baseName)
{
ReadOnlySpan<char> szModuleName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(lpBaseName);
if (!szModuleName.SequenceEqual(moduleName))
{
continue;
}
}
if (!K32GetModuleInformation(hProcess, hModule, out MODULEINFO moduleInfo))
{
continue;
}
module = new((nuint)moduleInfo.lpBaseOfDll, moduleInfo.SizeOfImage);
return FindModuleResult.Ok;
}
module = default;
return FindModuleResult.ModuleNotLoaded;
}
private static int IndexOfPattern(in ReadOnlySpan<byte> memory)
{
// B9 3C 00 00 00 FF 15
ReadOnlySpan<byte> part = [0xB9, 0x3C, 0x00, 0x00, 0x00, 0xFF, 0x15];
return memory.IndexOf(part);
}
private static FindModuleResult UnsafeGetGameModuleInfo(in HANDLE hProcess, out GameModule info)
{
FindModuleResult unityPlayerResult = UnsafeTryFindModule(hProcess, "UnityPlayer.dll", out Module unityPlayer);
FindModuleResult userAssemblyResult = UnsafeTryFindModule(hProcess, "UserAssembly.dll", out Module userAssembly);
if (unityPlayerResult == FindModuleResult.Ok && userAssemblyResult == FindModuleResult.Ok)
{
info = new(unityPlayer, userAssembly);
return FindModuleResult.Ok;
}
if (unityPlayerResult == FindModuleResult.NoModuleFound && userAssemblyResult == FindModuleResult.NoModuleFound)
{
info = default;
return FindModuleResult.NoModuleFound;
}
info = default;
return FindModuleResult.ModuleNotLoaded;
}
private async ValueTask<ValueResult<FindModuleResult, GameModule>> FindModuleAsync(TimeSpan findModuleDelay, TimeSpan findModuleLimit)
{
ValueStopwatch watch = ValueStopwatch.StartNew();
using (PeriodicTimer timer = new(findModuleDelay))
{
while (await timer.WaitForNextTickAsync().ConfigureAwait(false))
{
FindModuleResult result = UnsafeGetGameModuleInfo((HANDLE)gameProcess.Handle, out GameModule gameModule);
if (result == FindModuleResult.Ok)
{
return new(FindModuleResult.Ok, gameModule);
}
if (result == FindModuleResult.NoModuleFound)
{
return new(FindModuleResult.NoModuleFound, default);
}
if (watch.GetElapsedTime() > findModuleLimit)
{
break;
}
}
}
return new(FindModuleResult.TimeLimitExeeded, default);
}
private async ValueTask LoopAdjustFpsAsync(TimeSpan adjustFpsDelay, IProgress<UnlockerStatus> progress, CancellationToken token)
{
using (PeriodicTimer timer = new(adjustFpsDelay))
using (PeriodicTimer timer = new(state.TimingOptions.AdjustFpsDelay))
{
while (await timer.WaitForNextTickAsync(token).ConfigureAwait(false))
{
if (!gameProcess.HasExited && status.FpsAddress != 0U)
if (!state.GameProcess.HasExited && state.FpsAddress != 0U)
{
UnsafeWriteProcessMemory(gameProcess, status.FpsAddress, launchOptions.TargetFps);
progress.Report(status);
UnsafeWriteProcessMemory(state.GameProcess, state.FpsAddress, launchOptions.TargetFps);
state.Report();
}
else
{
status.IsUnlockerValid = false;
status.FpsAddress = 0;
progress.Report(status);
state.IsUnlockerValid = false;
state.FpsAddress = 0;
state.Report();
return;
}
}
}
}
private unsafe void UnsafeFindFpsAddress(in GameModule moduleEntryInfo)
private static unsafe bool UnsafeWriteProcessMemory(Process process, nuint baseAddress, int value)
{
bool readOk = UnsafeReadModulesMemory(gameProcess, moduleEntryInfo, out VirtualMemory localMemory);
Verify.Operation(readOk, SH.ServiceGameUnlockerReadModuleMemoryCopyVirtualMemoryFailed);
using (localMemory)
{
int offset = IndexOfPattern(localMemory.AsSpan()[(int)moduleEntryInfo.UnityPlayer.Size..]);
Must.Range(offset >= 0, SH.ServiceGameUnlockerInterestedPatternNotFound);
byte* pLocalMemory = (byte*)localMemory.Pointer;
ref readonly Module unityPlayer = ref moduleEntryInfo.UnityPlayer;
ref readonly Module userAssembly = ref moduleEntryInfo.UserAssembly;
nuint localMemoryUnityPlayerAddress = (nuint)pLocalMemory;
nuint localMemoryUserAssemblyAddress = localMemoryUnityPlayerAddress + unityPlayer.Size;
nuint rip = localMemoryUserAssemblyAddress + (uint)offset;
rip += 5U;
rip += (nuint)(*(int*)(rip + 2U) + 6);
nuint address = userAssembly.Address + (rip - localMemoryUserAssemblyAddress);
nuint ptr = 0;
SpinWait.SpinUntil(() => UnsafeReadProcessMemory(gameProcess, address, out ptr) && ptr != 0);
rip = ptr - unityPlayer.Address + localMemoryUnityPlayerAddress;
// CALL or JMP
while (*(byte*)rip == 0xE8 || *(byte*)rip == 0xE9)
{
rip += (nuint)(*(int*)(rip + 1) + 5);
}
nuint localMemoryActualAddress = rip + *(uint*)(rip + 2) + 6;
nuint actualOffset = localMemoryActualAddress - localMemoryUnityPlayerAddress;
status.FpsAddress = unityPlayer.Address + actualOffset;
}
}
private readonly struct GameModule
{
public readonly bool HasValue = false;
public readonly Module UnityPlayer;
public readonly Module UserAssembly;
public GameModule(in Module unityPlayer, in Module userAssembly)
{
HasValue = true;
UnityPlayer = unityPlayer;
UserAssembly = userAssembly;
}
}
private readonly struct Module
{
public readonly bool HasValue = false;
public readonly nuint Address;
public readonly uint Size;
public Module(nuint address, uint size)
{
HasValue = true;
Address = address;
Size = size;
}
return WriteProcessMemory((HANDLE)process.Handle, (void*)baseAddress, ref value, out _);
}
}

View File

@@ -0,0 +1,31 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using System.Diagnostics;
namespace Snap.Hutao.Service.Game.Unlocker;
/// <summary>
/// 解锁状态
/// </summary>
internal sealed class GameFpsUnlockerState
{
public string Description { get; set; } = default!;
public FindModuleResult FindModuleResult { get; set; }
public bool IsUnlockerValid { get; set; } = true;
public nuint FpsAddress { get; set; }
public UnlockTimingOptions TimingOptions { get; set; }
public Process GameProcess { get; set; } = default!;
public IProgress<GameFpsUnlockerState> Progress { get; set; } = default!;
public void Report()
{
Progress.Report(this);
}
}

View File

@@ -0,0 +1,108 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Core.Diagnostics;
using Snap.Hutao.Win32.Foundation;
using Snap.Hutao.Win32.Memory;
using Snap.Hutao.Win32.System.ProcessStatus;
using System.Diagnostics;
using System.Runtime.InteropServices;
using static Snap.Hutao.Win32.Kernel32;
namespace Snap.Hutao.Service.Game.Unlocker;
internal static class GameProcessModule
{
public static async ValueTask<ValueResult<FindModuleResult, RequiredGameModule>> FindModuleAsync(GameFpsUnlockerState state)
{
ValueStopwatch watch = ValueStopwatch.StartNew();
using (PeriodicTimer timer = new(state.TimingOptions.FindModuleDelay))
{
while (await timer.WaitForNextTickAsync().ConfigureAwait(false))
{
FindModuleResult result = UnsafeGetGameModuleInfo((HANDLE)state.GameProcess.Handle, out RequiredGameModule gameModule);
if (result == FindModuleResult.Ok)
{
return new(FindModuleResult.Ok, gameModule);
}
if (result == FindModuleResult.NoModuleFound)
{
return new(FindModuleResult.NoModuleFound, default);
}
if (watch.GetElapsedTime() > state.TimingOptions.FindModuleLimit)
{
break;
}
}
}
return new(FindModuleResult.TimeLimitExeeded, default);
}
private static FindModuleResult UnsafeGetGameModuleInfo(in HANDLE hProcess, out RequiredGameModule info)
{
FindModuleResult unityPlayerResult = UnsafeFindModule(hProcess, "UnityPlayer.dll", out Module unityPlayer);
FindModuleResult userAssemblyResult = UnsafeFindModule(hProcess, "UserAssembly.dll", out Module userAssembly);
if (unityPlayerResult is FindModuleResult.Ok && userAssemblyResult is FindModuleResult.Ok)
{
info = new(unityPlayer, userAssembly);
return FindModuleResult.Ok;
}
if (unityPlayerResult is FindModuleResult.NoModuleFound && userAssemblyResult is FindModuleResult.NoModuleFound)
{
info = default;
return FindModuleResult.NoModuleFound;
}
info = default;
return FindModuleResult.ModuleNotLoaded;
}
private static unsafe FindModuleResult UnsafeFindModule(in HANDLE hProcess, in ReadOnlySpan<char> moduleName, out Module module)
{
HMODULE[] buffer = new HMODULE[128];
if (!K32EnumProcessModules(hProcess, buffer, out uint actualSize))
{
Marshal.ThrowExceptionForHR(Marshal.GetLastPInvokeError());
}
if (actualSize == 0)
{
module = default!;
return FindModuleResult.NoModuleFound;
}
foreach (ref readonly HMODULE hModule in buffer.AsSpan()[..(int)(actualSize / sizeof(HMODULE))])
{
char[] baseName = new char[256];
if (K32GetModuleBaseNameW(hProcess, hModule, baseName) == 0)
{
continue;
}
fixed (char* lpBaseName = baseName)
{
if (!moduleName.SequenceEqual(MemoryMarshal.CreateReadOnlySpanFromNullTerminated(lpBaseName)))
{
continue;
}
}
if (!K32GetModuleInformation(hProcess, hModule, out MODULEINFO moduleInfo))
{
continue;
}
module = new((nuint)moduleInfo.lpBaseOfDll, moduleInfo.SizeOfImage);
return FindModuleResult.Ok;
}
module = default;
return FindModuleResult.ModuleNotLoaded;
}
}

View File

@@ -9,12 +9,7 @@ namespace Snap.Hutao.Service.Game.Unlocker;
[HighQuality]
internal interface IGameFpsUnlocker
{
/// <summary>
/// 异步的解锁帧数限制
/// </summary>
/// <param name="options">选项</param>
/// <param name="progress">进度</param>
/// <param name="token">取消令牌</param>
/// <returns>解锁的结果</returns>
ValueTask UnlockAsync(UnlockTimingOptions options, IProgress<UnlockerStatus> progress, CancellationToken token = default);
ValueTask PostUnlockAsync(CancellationToken token = default);
ValueTask UnlockAsync(CancellationToken token = default);
}

View File

@@ -0,0 +1,18 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Service.Game.Unlocker;
internal readonly struct Module
{
public readonly bool HasValue = false;
public readonly nuint Address;
public readonly uint Size;
public Module(nuint address, uint size)
{
HasValue = true;
Address = address;
Size = size;
}
}

View File

@@ -0,0 +1,18 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Service.Game.Unlocker;
internal readonly struct RequiredGameModule
{
public readonly bool HasValue = false;
public readonly Module UnityPlayer;
public readonly Module UserAssembly;
public RequiredGameModule(in Module unityPlayer, in Module userAssembly)
{
HasValue = true;
UnityPlayer = unityPlayer;
UserAssembly = userAssembly;
}
}

View File

@@ -1,30 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Service.Game.Unlocker;
/// <summary>
/// 解锁状态
/// </summary>
internal sealed class UnlockerStatus
{
/// <summary>
/// 状态描述
/// </summary>
public string Description { get; set; } = default!;
/// <summary>
/// 查找模块状态
/// </summary>
public FindModuleResult FindModuleState { get; set; }
/// <summary>
/// 当前解锁器是否有效
/// </summary>
public bool IsUnlockerValid { get; set; } = true;
/// <summary>
/// FPS 字节地址
/// </summary>
public nuint FpsAddress { get; set; }
}

View File

@@ -2,7 +2,6 @@
// Licensed under the MIT license.
using Microsoft.Extensions.Caching.Memory;
using Snap.Hutao.Core.DependencyInjection.Abstraction;
namespace Snap.Hutao.Service.Metadata;

View File

@@ -2,7 +2,6 @@
// Licensed under the MIT license.
using Microsoft.UI.Xaml.Controls;
using Snap.Hutao.Core.DependencyInjection.Abstraction;
namespace Snap.Hutao.Service.Navigation;

View File

@@ -3,7 +3,6 @@
using CommunityToolkit.Mvvm.Messaging;
using Snap.Hutao.Core.Database;
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Message;
using Snap.Hutao.ViewModel.User;
using Snap.Hutao.Web.Hoyolab.Takumi.Binding;

View File

@@ -15,6 +15,7 @@
HorizontalContentAlignment="Stretch"
d:DataContext="{d:DesignInstance shva:AchievementViewModelSlim}"
Background="Transparent"
BorderBrush="{x:Null}"
Command="{Binding NavigateCommand}"
Style="{ThemeResource DefaultButtonStyle}"
mc:Ignorable="d">
@@ -51,11 +52,12 @@
Grid.Row="0"
HorizontalAlignment="Right"
Text="{Binding DisplayName}"/>
<TextBlock
Grid.Row="1"
Margin="0,4,0,0"
Style="{StaticResource TitleTextBlockStyle}"
Text="{Binding FinishDescription}"/>
<Viewbox Grid.Row="1" StretchDirection="DownOnly">
<TextBlock
Margin="0,4,0,0"
Style="{StaticResource TitleTextBlockStyle}"
Text="{Binding FinishDescription}"/>
</Viewbox>
<ItemsControl
Grid.Row="2"
ItemTemplate="{StaticResource AchievementTempate}"

View File

@@ -17,6 +17,7 @@
HorizontalContentAlignment="Stretch"
d:DataContext="{d:DesignInstance shvd:DailyNoteViewModelSlim}"
Background="Transparent"
BorderBrush="{x:Null}"
Command="{Binding NavigateCommand}"
Style="{ThemeResource DefaultButtonStyle}"
mc:Ignorable="d">

View File

@@ -16,6 +16,7 @@
HorizontalContentAlignment="Stretch"
d:DataContext="{d:DesignInstance shvg:GachaLogViewModelSlim}"
Background="Transparent"
BorderBrush="{x:Null}"
Command="{Binding NavigateCommand}"
Style="{ThemeResource DefaultButtonStyle}"
mc:Ignorable="d">

View File

@@ -17,6 +17,7 @@
VerticalContentAlignment="Stretch"
d:DataContext="{d:DesignInstance shvg:LaunchGameViewModelSlim}"
Background="Transparent"
BorderBrush="{x:Null}"
Command="{Binding LaunchCommand}"
Style="{ThemeResource DefaultButtonStyle}"
mc:Ignorable="d">

View File

@@ -21,6 +21,12 @@
mc:Ignorable="d">
<UserControl.Resources>
<shvconv:BoolToGridLengthConverter x:Key="BoolToGridLengthConverter"/>
<shvconv:BoolToGridLengthConverter
x:Key="BoolToGridLengthSpacingConverter"
FalseValue="0"
TrueValue="4"/>
<shvconv:Int32ToGradientColorConverter x:Key="Int32ToGradientColorConverter" MaximumValue="{Binding GuaranteeOrangeThreshold}"/>
<DataTemplate x:Key="OrangeListTemplate" d:DataType="shvg:SummaryItem">
@@ -226,10 +232,12 @@
Padding="0,12"
Value="{x:Bind StatisticsSegmented.SelectedIndex, Mode=OneWay}">
<cwcont:Case Value="{shcm:Int32 Value=0}">
<Grid ColumnSpacing="2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition Width="{x:Bind ShowUpPull, Converter={StaticResource BoolToGridLengthSpacingConverter}}"/>
<ColumnDefinition Width="{x:Bind ShowUpPull, Converter={StaticResource BoolToGridLengthConverter}}"/>
<ColumnDefinition Width="4"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Style="{ThemeResource BorderCardStyle}">
@@ -243,7 +251,7 @@
</StackPanel>
</Viewbox>
</Border>
<Border Grid.Column="1" Style="{ThemeResource BorderCardStyle}">
<Border Grid.Column="2" Style="{ThemeResource BorderCardStyle}">
<Viewbox Margin="8,0" StretchDirection="DownOnly">
<Grid>
<StackPanel
@@ -266,7 +274,7 @@
</Viewbox>
</Border>
<Grid Grid.Column="2" RowSpacing="2">
<Grid Grid.Column="4" RowSpacing="4">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
@@ -298,7 +306,7 @@
<RowDefinition/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid ColumnSpacing="2">
<Grid ColumnSpacing="4">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
@@ -360,7 +368,7 @@
</cwcont:Case>
<cwcont:Case Value="{shcm:Int32 Value=2}">
<Grid RowSpacing="2">
<Grid RowSpacing="4">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>

View File

@@ -0,0 +1,16 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using CommunityToolkit.WinUI.Converters;
using Microsoft.UI.Xaml;
namespace Snap.Hutao.View.Converter;
internal sealed class BoolToGridLengthConverter : BoolToObjectConverter
{
public BoolToGridLengthConverter()
{
TrueValue = new GridLength(1D, GridUnitType.Star);
FalseValue = new GridLength(0D);
}
}

View File

@@ -212,7 +212,7 @@
LocalSettingKeySuffixForCurrent="AchievementPage.AchievementGoals"/>
<Viewbox
Height="32"
MaxWidth="192"
MaxWidth="190"
Margin="8,0,0,0"
HorizontalAlignment="Left"
Stretch="Uniform"

View File

@@ -43,6 +43,7 @@
cw:VisualExtensions.NormalizedCenterPoint="0.5">
<cww:ConstrainedBox AspectRatio="1080:390" CornerRadius="{ThemeResource ControlCornerRadiusTop}">
<shci:CachedImage
Margin="-1"
VerticalAlignment="Center"
PlaceholderMargin="16"
PlaceholderSource="{StaticResource UI_EmotionIcon271}"

View File

@@ -3,6 +3,7 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:clw="using:CommunityToolkit.Labs.WinUI"
xmlns:cw="using:CommunityToolkit.WinUI"
xmlns:cwcont="using:CommunityToolkit.WinUI.Controls"
xmlns:cwconv="using:CommunityToolkit.WinUI.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
@@ -50,240 +51,248 @@
<SplitView.Pane>
<ScrollViewer>
<StackPanel Margin="16" Spacing="3">
<Border Style="{ThemeResource AcrylicBorderCardStyle}">
<cwcont:SettingsExpander
Description="{Binding RuntimeOptions.Version}"
Header="{shcm:ResourceString Name=AppName}"
HeaderIcon="{shcm:FontIcon Glyph=&#xECAA;}"
IsExpanded="True">
<cwcont:SettingsExpander.Items>
<cwcont:SettingsCard
ActionIcon="{shcm:FontIcon Glyph=&#xE8C8;}"
ActionIconToolTip="{shcm:ResourceString Name=ViewPageSettingCopyDeviceIdAction}"
Command="{Binding CopyDeviceIdCommand}"
Description="{Binding RuntimeOptions.DeviceId}"
Header="{shcm:ResourceString Name=ViewPageSettingDeviceIdHeader}"
IsClickEnabled="True"/>
<cwcont:SettingsCard Description="{Binding IPInformation}" Header="{shcm:ResourceString Name=ViewPageSettingDeviceIpHeader}"/>
<cwcont:SettingsCard Description="{Binding DynamicHttpProxy.CurrentProxyUri}" Header="{shcm:ResourceString Name=ViewPageFeedbackCurrentProxyHeader}"/>
<cwcont:SettingsCard
Command="{Binding EnableLoopbackCommand}"
Header="{shcm:ResourceString Name=ViewPageFeedbackEnableLoopbackHeader}"
IsClickEnabled="True"
IsEnabled="{Binding LoopbackManager.IsLoopbackEnabled, Converter={StaticResource BoolNegationConverter}, Mode=OneWay}">
<cwcont:SettingsCard.Description>
<UserControl Content="{Binding LoopbackManager.IsLoopbackEnabled, Converter={StaticResource BoolToLoopbackDescriptionControlConverter}, Mode=OneWay}"/>
</cwcont:SettingsCard.Description>
</cwcont:SettingsCard>
<cwcont:SettingsCard Description="{Binding RuntimeOptions.WebView2Version}" Header="{shcm:ResourceString Name=ViewPageSettingWebview2Header}"/>
</cwcont:SettingsExpander.Items>
</cwcont:SettingsExpander>
<Border cw:Effects.Shadow="{ThemeResource CompatCardShadow}">
<Border Style="{ThemeResource AcrylicBorderCardStyle}">
<cwcont:SettingsExpander
Description="{Binding RuntimeOptions.Version}"
Header="{shcm:ResourceString Name=AppName}"
HeaderIcon="{shcm:FontIcon Glyph=&#xECAA;}"
IsExpanded="True">
<cwcont:SettingsExpander.Items>
<cwcont:SettingsCard
ActionIcon="{shcm:FontIcon Glyph=&#xE8C8;}"
ActionIconToolTip="{shcm:ResourceString Name=ViewPageSettingCopyDeviceIdAction}"
Command="{Binding CopyDeviceIdCommand}"
Description="{Binding RuntimeOptions.DeviceId}"
Header="{shcm:ResourceString Name=ViewPageSettingDeviceIdHeader}"
IsClickEnabled="True"/>
<cwcont:SettingsCard Description="{Binding IPInformation}" Header="{shcm:ResourceString Name=ViewPageSettingDeviceIpHeader}"/>
<cwcont:SettingsCard Description="{Binding DynamicHttpProxy.CurrentProxyUri}" Header="{shcm:ResourceString Name=ViewPageFeedbackCurrentProxyHeader}"/>
<cwcont:SettingsCard
Command="{Binding EnableLoopbackCommand}"
Header="{shcm:ResourceString Name=ViewPageFeedbackEnableLoopbackHeader}"
IsClickEnabled="True"
IsEnabled="{Binding LoopbackManager.IsLoopbackEnabled, Converter={StaticResource BoolNegationConverter}, Mode=OneWay}">
<cwcont:SettingsCard.Description>
<UserControl Content="{Binding LoopbackManager.IsLoopbackEnabled, Converter={StaticResource BoolToLoopbackDescriptionControlConverter}, Mode=OneWay}"/>
</cwcont:SettingsCard.Description>
</cwcont:SettingsCard>
<cwcont:SettingsCard Description="{Binding RuntimeOptions.WebView2Version}" Header="{shcm:ResourceString Name=ViewPageSettingWebview2Header}"/>
</cwcont:SettingsExpander.Items>
</cwcont:SettingsExpander>
</Border>
</Border>
<Border Style="{ThemeResource AcrylicBorderCardStyle}">
<cwcont:SettingsExpander
Description="{shcm:ResourceString Name=ViewPageFeedbackEngageWithUsDescription}"
Header="{shcm:ResourceString Name=ViewPageFeedbackCommonLinksHeader}"
HeaderIcon="{shcm:FontIcon Glyph=&#xE71B;}"
IsExpanded="True">
<cwcont:SettingsExpander.Items>
<cwcont:SettingsCard
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://github.com/DGP-Studio/Snap.Hutao/issues/new/choose"
Description="{shcm:ResourceString Name=ViewPageFeedbackGithubIssuesDescription}"
Header="GitHub Issues"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://github.com/orgs/DGP-Studio/projects/2"
Description="{shcm:ResourceString Name=ViewPageFeedbackRoadmapDescription}"
Header="GitHub Projects"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://status.hut.ao"
Description="{shcm:ResourceString Name=ViewPageFeedbackServerStatusDescription}"
Header="{shcm:ResourceString Name=ViewPageFeedbackServerStatusHeader}"
IsClickEnabled="True"/>
</cwcont:SettingsExpander.Items>
</cwcont:SettingsExpander>
<Border cw:Effects.Shadow="{ThemeResource CompatCardShadow}">
<Border Style="{ThemeResource AcrylicBorderCardStyle}">
<cwcont:SettingsExpander
Description="{shcm:ResourceString Name=ViewPageFeedbackEngageWithUsDescription}"
Header="{shcm:ResourceString Name=ViewPageFeedbackCommonLinksHeader}"
HeaderIcon="{shcm:FontIcon Glyph=&#xE71B;}"
IsExpanded="True">
<cwcont:SettingsExpander.Items>
<cwcont:SettingsCard
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://github.com/DGP-Studio/Snap.Hutao/issues/new/choose"
Description="{shcm:ResourceString Name=ViewPageFeedbackGithubIssuesDescription}"
Header="GitHub Issues"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://github.com/orgs/DGP-Studio/projects/2"
Description="{shcm:ResourceString Name=ViewPageFeedbackRoadmapDescription}"
Header="GitHub Projects"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://status.hut.ao"
Description="{shcm:ResourceString Name=ViewPageFeedbackServerStatusDescription}"
Header="{shcm:ResourceString Name=ViewPageFeedbackServerStatusHeader}"
IsClickEnabled="True"/>
</cwcont:SettingsExpander.Items>
</cwcont:SettingsExpander>
</Border>
</Border>
<Border Style="{ThemeResource AcrylicBorderCardStyle}">
<cwcont:SettingsExpander
Header="{shcm:ResourceString Name=ViewPageFeedbackFeatureGuideHeader}"
HeaderIcon="{shcm:FontIcon Glyph=&#xF8A5;}"
IsExpanded="True">
<cwcont:SettingsExpander.Items>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/dashboard.html"
Header="{shcm:ResourceString Name=ViewAnnouncementHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/Announcement.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/game-launcher.html"
Header="{shcm:ResourceString Name=ViewLaunchGameHeader}"
IsClickEnabled="True">
<cwcont:SettingsCard.HeaderIcon>
<!-- This icon is not a square -->
<BitmapIcon
Width="24"
Height="24"
ShowAsMonochrome="False"
UriSource="ms-appx:///Resource/Navigation/LaunchGame.png"/>
</cwcont:SettingsCard.HeaderIcon>
</cwcont:SettingsCard>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/wish-export.html"
Header="{shcm:ResourceString Name=ViewGachaLogHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/GachaLog.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/achievements.html"
Header="{shcm:ResourceString Name=ViewAchievementHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/Achievement.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/real-time-notes.html"
Header="{shcm:ResourceString Name=ViewDailyNoteHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/DailyNote.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/character-data.html"
Header="{shcm:ResourceString Name=ViewAvatarPropertyHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/AvatarProperty.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/hutao-API.html"
Header="{shcm:ResourceString Name=ViewSpiralAbyssHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/SpiralAbyss.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/develop-plan.html"
Header="{shcm:ResourceString Name=ViewCultivationHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/Cultivation.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/character-wiki.html"
Header="{shcm:ResourceString Name=ViewWikiAvatarHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/WikiAvatar.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/weapon-wiki.html"
Header="{shcm:ResourceString Name=ViewWikiWeaponHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/WikiWeapon.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/monster-wiki.html"
Header="{shcm:ResourceString Name=ViewWikiMonsterHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/WikiMonster.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/hutao-settings.html"
Header="{shcm:ResourceString Name=ViewSettingHeader}"
HeaderIcon="{shcm:FontIcon Glyph=&#xE713;}"
IsClickEnabled="True"/>
</cwcont:SettingsExpander.Items>
</cwcont:SettingsExpander>
<Border cw:Effects.Shadow="{ThemeResource CompatCardShadow}">
<Border Style="{ThemeResource AcrylicBorderCardStyle}">
<cwcont:SettingsExpander
Header="{shcm:ResourceString Name=ViewPageFeedbackFeatureGuideHeader}"
HeaderIcon="{shcm:FontIcon Glyph=&#xF8A5;}"
IsExpanded="True">
<cwcont:SettingsExpander.Items>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/dashboard.html"
Header="{shcm:ResourceString Name=ViewAnnouncementHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/Announcement.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/game-launcher.html"
Header="{shcm:ResourceString Name=ViewLaunchGameHeader}"
IsClickEnabled="True">
<cwcont:SettingsCard.HeaderIcon>
<!-- This icon is not a square -->
<BitmapIcon
Width="24"
Height="24"
ShowAsMonochrome="False"
UriSource="ms-appx:///Resource/Navigation/LaunchGame.png"/>
</cwcont:SettingsCard.HeaderIcon>
</cwcont:SettingsCard>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/wish-export.html"
Header="{shcm:ResourceString Name=ViewGachaLogHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/GachaLog.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/achievements.html"
Header="{shcm:ResourceString Name=ViewAchievementHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/Achievement.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/real-time-notes.html"
Header="{shcm:ResourceString Name=ViewDailyNoteHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/DailyNote.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/character-data.html"
Header="{shcm:ResourceString Name=ViewAvatarPropertyHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/AvatarProperty.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/hutao-API.html"
Header="{shcm:ResourceString Name=ViewSpiralAbyssHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/SpiralAbyss.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/develop-plan.html"
Header="{shcm:ResourceString Name=ViewCultivationHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/Cultivation.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/character-wiki.html"
Header="{shcm:ResourceString Name=ViewWikiAvatarHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/WikiAvatar.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/weapon-wiki.html"
Header="{shcm:ResourceString Name=ViewWikiWeaponHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/WikiWeapon.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/monster-wiki.html"
Header="{shcm:ResourceString Name=ViewWikiMonsterHeader}"
HeaderIcon="{shcm:BitmapIcon Source=ms-appx:///Resource/Navigation/WikiMonster.png}"
IsClickEnabled="True"/>
<cwcont:SettingsCard
Padding="{ThemeResource SettingsExpanderItemHasIconPadding}"
Command="{Binding NavigateToUriCommand}"
CommandParameter="https://hut.ao/features/hutao-settings.html"
Header="{shcm:ResourceString Name=ViewSettingHeader}"
HeaderIcon="{shcm:FontIcon Glyph=&#xE713;}"
IsClickEnabled="True"/>
</cwcont:SettingsExpander.Items>
</cwcont:SettingsExpander>
</Border>
</Border>
</StackPanel>
</ScrollViewer>
</SplitView.Pane>
<Grid Margin="16,16,0,16" Style="{ThemeResource AcrylicGridCardStyle}">
<Grid
Padding="16"
RowSpacing="8"
Visibility="{Binding IsInitialized, Converter={StaticResource BoolToVisibilityConverter}, Mode=OneWay}">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<AutoSuggestBox
Grid.Row="0"
Height="36"
Margin="0,0,0,8"
HorizontalAlignment="Stretch"
VerticalContentAlignment="Center"
PlaceholderText="{shcm:ResourceString Name=ViewPageFeedbackAutoSuggestBoxPlaceholder}"
QueryIcon="{shcm:FontIcon Glyph=&#xE721;}"
Style="{StaticResource DefaultAutoSuggestBoxStyle}"
Text="{Binding SearchText, Mode=TwoWay}">
<mxi:Interaction.Behaviors>
<mxic:EventTriggerBehavior EventName="QuerySubmitted">
<mxic:InvokeCommandAction Command="{Binding SearchDocumentCommand}" CommandParameter="{Binding SearchText}"/>
</mxic:EventTriggerBehavior>
</mxi:Interaction.Behaviors>
</AutoSuggestBox>
<StackPanel
Grid.Row="1"
VerticalAlignment="Center"
Visibility="{Binding SearchResults.Count, Converter={StaticResource Int32ToVisibilityRevertConverter}}">
<shci:CachedImage
Height="120"
MinWidth="{ThemeResource SettingsCardContentControlMinWidth}"
EnableLazyLoading="False"
Source="{StaticResource UI_EmotionIcon52}"/>
<TextBlock
Margin="0,5,0,21"
HorizontalAlignment="Center"
Style="{StaticResource SubtitleTextBlockStyle}"
Text="{shcm:ResourceString Name=ViewPageFeedbackSearchResultPlaceholderTitle}"/>
</StackPanel>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Hidden">
<ItemsControl
ItemContainerTransitions="{ThemeResource ListViewLikeThemeTransitions}"
ItemsPanel="{ThemeResource StackPanelSpacing8Template}"
ItemsSource="{Binding SearchResults}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Style="{ThemeResource BorderCardStyle}">
<HyperlinkButton
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch"
NavigateUri="{Binding Url}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<BreadcrumbBar
Grid.Column="0"
Margin="4,8,8,4"
IsHitTestVisible="False"
ItemsSource="{Binding Hierarchy.DisplayLevels}"/>
</Grid>
</HyperlinkButton>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
<Border Margin="16,16,0,16" cw:Effects.Shadow="{ThemeResource CompatCardShadow}">
<Grid Style="{ThemeResource AcrylicGridCardStyle}">
<Grid
Padding="16"
RowSpacing="8"
Visibility="{Binding IsInitialized, Converter={StaticResource BoolToVisibilityConverter}, Mode=OneWay}">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<AutoSuggestBox
Grid.Row="0"
Height="36"
Margin="0,0,0,8"
HorizontalAlignment="Stretch"
VerticalContentAlignment="Center"
PlaceholderText="{shcm:ResourceString Name=ViewPageFeedbackAutoSuggestBoxPlaceholder}"
QueryIcon="{shcm:FontIcon Glyph=&#xE721;}"
Style="{StaticResource DefaultAutoSuggestBoxStyle}"
Text="{Binding SearchText, Mode=TwoWay}">
<mxi:Interaction.Behaviors>
<mxic:EventTriggerBehavior EventName="QuerySubmitted">
<mxic:InvokeCommandAction Command="{Binding SearchDocumentCommand}" CommandParameter="{Binding SearchText}"/>
</mxic:EventTriggerBehavior>
</mxi:Interaction.Behaviors>
</AutoSuggestBox>
<StackPanel
Grid.Row="1"
VerticalAlignment="Center"
Visibility="{Binding SearchResults.Count, Converter={StaticResource Int32ToVisibilityRevertConverter}}">
<shci:CachedImage
Height="120"
MinWidth="{ThemeResource SettingsCardContentControlMinWidth}"
EnableLazyLoading="False"
Source="{StaticResource UI_EmotionIcon52}"/>
<TextBlock
Margin="0,5,0,21"
HorizontalAlignment="Center"
Style="{StaticResource SubtitleTextBlockStyle}"
Text="{shcm:ResourceString Name=ViewPageFeedbackSearchResultPlaceholderTitle}"/>
</StackPanel>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Hidden">
<ItemsControl
ItemContainerTransitions="{ThemeResource ListViewLikeThemeTransitions}"
ItemsPanel="{ThemeResource StackPanelSpacing8Template}"
ItemsSource="{Binding SearchResults}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Style="{ThemeResource BorderCardStyle}">
<HyperlinkButton
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch"
NavigateUri="{Binding Url}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<BreadcrumbBar
Grid.Column="0"
Margin="4,8,8,4"
IsHitTestVisible="False"
ItemsSource="{Binding Hierarchy.DisplayLevels}"/>
</Grid>
</HyperlinkButton>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
<clw:Shimmer IsActive="{Binding IsInitialized, Converter={StaticResource BoolNegationConverter}, Mode=OneWay}" Visibility="{Binding IsInitialized, Converter={StaticResource BoolToVisibilityRevertConverter}, Mode=OneWay}"/>
</Grid>
<clw:Shimmer IsActive="{Binding IsInitialized, Converter={StaticResource BoolNegationConverter}, Mode=OneWay}" Visibility="{Binding IsInitialized, Converter={StaticResource BoolToVisibilityRevertConverter}, Mode=OneWay}"/>
</Grid>
</Border>
</SplitView>
</Grid>
</shc:ScopedPage>

View File

@@ -12,6 +12,7 @@
xmlns:shcb="using:Snap.Hutao.Control.Behavior"
xmlns:shci="using:Snap.Hutao.Control.Image"
xmlns:shcm="using:Snap.Hutao.Control.Markup"
xmlns:shcp="using:Snap.Hutao.Control.Panel"
xmlns:shvc="using:Snap.Hutao.View.Control"
xmlns:shvg="using:Snap.Hutao.ViewModel.GachaLog"
d:DataContext="{d:DesignInstance shvg:GachaLogViewModel}"
@@ -285,26 +286,31 @@
</CommandBar>
</Pivot.RightHeader>
<PivotItem Header="{shcm:ResourceString Name=ViewPageGahcaLogPivotOverview}">
<Grid Margin="0,0,16,0">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<shvc:StatisticsCard
Grid.Column="0"
Margin="16,16,0,16"
DataContext="{Binding Statistics.AvatarWish}"/>
<shvc:StatisticsCard
Grid.Column="1"
Margin="16,16,0,16"
DataContext="{Binding Statistics.WeaponWish}"/>
<shvc:StatisticsCard
Grid.Column="2"
Margin="16,16,0,16"
DataContext="{Binding Statistics.StandardWish}"
ShowUpPull="False"/>
</Grid>
<ScrollViewer
Margin="16,0"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollMode="Enabled"
VerticalScrollMode="Disabled">
<shcp:HorizontalEqualPanel
Margin="0,16"
MinItemWidth="302"
Spacing="16">
<shvc:StatisticsCard DataContext="{Binding Statistics.AvatarWish}"/>
<shvc:StatisticsCard DataContext="{Binding Statistics.WeaponWish}"/>
<shvc:StatisticsCard DataContext="{Binding Statistics.StandardWish}" ShowUpPull="False"/>
<shvc:StatisticsCard DataContext="{Binding Statistics.ChronicledWish}" ShowUpPull="False"/>
</shcp:HorizontalEqualPanel>
<!--<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="240"/>
<ColumnDefinition Width="*" MinWidth="240"/>
<ColumnDefinition Width="*" MinWidth="240"/>
<ColumnDefinition Width="*" MinWidth="240"/>
</Grid.ColumnDefinitions>
</Grid>-->
</ScrollViewer>
</PivotItem>
<PivotItem Header="{shcm:ResourceString Name=ViewPageGahcaLogPivotHistory}">
<Border Margin="16" cw:Effects.Shadow="{ThemeResource CompatCardShadow}">
@@ -379,7 +385,6 @@
</SplitView>
</Border>
</Border>
</PivotItem>
<PivotItem Header="{shcm:ResourceString Name=ViewPageGahcaLogPivotAvatar}">
<ScrollViewer>
@@ -487,7 +492,6 @@
<shvc:HutaoStatisticsCard Grid.Column="2" DataContext="{Binding HutaoCloudStatisticsViewModel.Statistics.WeaponEvent}"/>
</Grid>
</Grid>
</PivotItem>
</Pivot>
</Grid>

View File

@@ -314,6 +314,17 @@
SelectedItem="{Binding SelectedBackdropType, Mode=TwoWay}"/>
</shc:SizeRestrictedContentControl>
</cwc:SettingsCard>
<cwc:SettingsCard
Description="{shcm:ResourceString Name=ViewPageSettingThemeDescription}"
Header="{shcm:ResourceString Name=ViewPageSettingThemeHeader}"
HeaderIcon="{shcm:FontIcon Glyph=&#xE790;}">
<shc:SizeRestrictedContentControl>
<ComboBox
DisplayMemberPath="Name"
ItemsSource="{Binding AppOptions.LazyElementThemes.Value}"
SelectedItem="{Binding SelectedElementTheme, Mode=TwoWay}"/>
</shc:SizeRestrictedContentControl>
</cwc:SettingsCard>
<cwc:SettingsExpander
Description="{shcm:ResourceString Name=ViewPageSettingBackgroundImageDescription}"
Header="{shcm:ResourceString Name=ViewPageSettingBackgroundImageHeader}"
@@ -337,6 +348,7 @@
</mxic:EventTriggerBehavior>
</mxi:Interaction.Behaviors>
</cwc:SettingsCard>
<cwc:SettingsCard Header="{shcm:ResourceString Name=ViewPageSettingBackgroundImageLocalFolderCopyrightHeader}" Visibility="{Binding BackgroundImageOptions.Wallpaper, Converter={StaticResource EmptyObjectToBoolRevertConverter}}"/>
</cwc:SettingsExpander.Items>
</cwc:SettingsExpander>
</StackPanel>

View File

@@ -203,19 +203,23 @@
</Border>
</cwc:Case>
<cwc:Case Value="Grid">
<GridView
Padding="16,16,4,4"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Left"
ItemContainerStyle="{StaticResource LargeGridViewItemStyle}"
ItemTemplate="{StaticResource MonsterGridTemplate}"
ItemsSource="{Binding Monsters}"
SelectedItem="{Binding Selected, Mode=TwoWay}"
SelectionMode="Single">
<mxi:Interaction.Behaviors>
<shcb:SelectedItemInViewBehavior/>
</mxi:Interaction.Behaviors>
</GridView>
<Border Margin="16,0,16,16" cw:Effects.Shadow="{ThemeResource CompatCardShadow}">
<Border Style="{ThemeResource AcrylicBorderCardStyle}">
<GridView
Padding="16,16,4,4"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Left"
ItemContainerStyle="{StaticResource LargeGridViewItemStyle}"
ItemTemplate="{StaticResource MonsterGridTemplate}"
ItemsSource="{Binding Monsters}"
SelectedItem="{Binding Selected, Mode=TwoWay}"
SelectionMode="Single">
<mxi:Interaction.Behaviors>
<shcb:SelectedItemInViewBehavior/>
</mxi:Interaction.Behaviors>
</GridView>
</Border>
</Border>
</cwc:Case>
</cwc:SwitchPresenter>
</Grid>

View File

@@ -5,7 +5,6 @@ using Microsoft.Extensions.Primitives;
using Snap.Hutao.Model.Metadata.Avatar;
using Snap.Hutao.Model.Primitive;
using Snap.Hutao.Web.Hutao.SpiralAbyss;
using System.Diagnostics;
using System.Globalization;
namespace Snap.Hutao.ViewModel.Complex;

View File

@@ -104,10 +104,14 @@ internal sealed partial class GachaLogViewModel : Abstraction.ViewModel
ArgumentNullException.ThrowIfNull(gachaLogService.ArchiveCollection);
ObservableCollection<GachaArchive> archives = gachaLogService.ArchiveCollection;
await taskContext.SwitchToMainThreadAsync();
Archives = archives;
HutaoCloudViewModel.RetrieveCommand = RetrieveFromCloudCommand;
await SetSelectedArchiveAndUpdateStatisticsAsync(Archives.SelectedOrDefault(), true).ConfigureAwait(false);
using (await EnterCriticalExecutionAsync().ConfigureAwait(false))
{
await taskContext.SwitchToMainThreadAsync();
Archives = archives;
HutaoCloudViewModel.RetrieveCommand = RetrieveFromCloudCommand;
await SetSelectedArchiveAndUpdateStatisticsAsync(Archives.SelectedOrDefault(), true).ConfigureAwait(false);
}
return true;
}
}

View File

@@ -21,7 +21,15 @@ internal abstract class Wish
public string TimeSpanFormatted
{
get => $"{From:yyyy.MM.dd} - {To:yyyy.MM.dd}";
get
{
if (From == DateTimeOffset.MaxValue && To == DateTimeOffset.MinValue)
{
return string.Empty;
}
return $"{From:yyyy.MM.dd} - {To:yyyy.MM.dd}";
}
}
/// <summary>

View File

@@ -2,6 +2,7 @@
// Licensed under the MIT license.
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.Windows.AppLifecycle;
using Snap.Hutao.Core;
@@ -58,6 +59,7 @@ internal sealed partial class SettingViewModel : Abstraction.ViewModel
private readonly IMessenger messenger;
private NameValue<BackdropType>? selectedBackdropType;
private NameValue<ElementTheme>? selectedElementTheme;
private NameValue<BackgroundImageType>? selectedBackgroundImageType;
private NameValue<CultureInfo>? selectedCulture;
private NameValue<Region>? selectedRegion;
@@ -94,6 +96,18 @@ internal sealed partial class SettingViewModel : Abstraction.ViewModel
}
}
public NameValue<ElementTheme>? SelectedElementTheme
{
get => selectedElementTheme ??= AppOptions.LazyElementThemes.Value.Single(t => t.Value == AppOptions.ElementTheme);
set
{
if (SetProperty(ref selectedElementTheme, value) && value is not null)
{
AppOptions.ElementTheme = value.Value;
}
}
}
public NameValue<BackgroundImageType>? SelectedBackgroundImageType
{
get => selectedBackgroundImageType ??= AppOptions.BackgroundImageTypes.Single(t => t.Value == AppOptions.BackgroundImageType);

View File

@@ -92,39 +92,49 @@ internal sealed partial class WikiAvatarViewModel : Abstraction.ViewModel
protected override async ValueTask<bool> InitializeUIAsync()
{
if (!await metadataService.InitializeAsync().ConfigureAwait(false))
if (await metadataService.InitializeAsync().ConfigureAwait(false))
{
return false;
try
{
levelAvatarCurveMap = await metadataService.GetLevelToAvatarCurveMapAsync().ConfigureAwait(false);
promotes = await metadataService.GetAvatarPromoteListAsync().ConfigureAwait(false);
Dictionary<MaterialId, Material> idMaterialMap = await metadataService.GetIdToMaterialMapAsync().ConfigureAwait(false);
List<Avatar> avatars = await metadataService.GetAvatarListAsync().ConfigureAwait(false);
IOrderedEnumerable<Avatar> sorted = avatars
.OrderByDescending(avatar => avatar.BeginTime)
.ThenByDescending(avatar => avatar.Sort);
List<Avatar> list = [.. sorted];
await CombineComplexDataAsync(list, idMaterialMap).ConfigureAwait(false);
using (await EnterCriticalExecutionAsync().ConfigureAwait(false))
{
await taskContext.SwitchToMainThreadAsync();
Avatars = new(list, true);
Selected = Avatars.View.ElementAtOrDefault(0);
}
FilterTokens = [];
availableTokens = FrozenDictionary.ToFrozenDictionary(
[
.. avatars.Select(avatar => KeyValuePair.Create(avatar.Name, new SearchToken(SearchTokenKind.Avatar, avatar.Name, sideIconUri: AvatarSideIconConverter.IconNameToUri(avatar.SideIcon)))),
.. IntrinsicFrozen.AssociationTypes.Select(assoc => KeyValuePair.Create(assoc, new SearchToken(SearchTokenKind.AssociationType, assoc, iconUri: AssociationTypeIconConverter.AssociationTypeNameToIconUri(assoc)))),
.. IntrinsicFrozen.BodyTypes.Select(b => KeyValuePair.Create(b, new SearchToken(SearchTokenKind.BodyType, b))),
.. IntrinsicFrozen.ElementNames.Select(e => KeyValuePair.Create(e, new SearchToken(SearchTokenKind.ElementName, e, iconUri: ElementNameIconConverter.ElementNameToIconUri(e)))),
.. IntrinsicFrozen.ItemQualities.Select(i => KeyValuePair.Create(i, new SearchToken(SearchTokenKind.ItemQuality, i, quality: QualityColorConverter.QualityNameToColor(i)))),
.. IntrinsicFrozen.WeaponTypes.Select(w => KeyValuePair.Create(w, new SearchToken(SearchTokenKind.WeaponType, w, iconUri: WeaponTypeIconConverter.WeaponTypeNameToIconUri(w)))),
]);
return true;
}
catch (OperationCanceledException)
{
}
}
levelAvatarCurveMap = await metadataService.GetLevelToAvatarCurveMapAsync().ConfigureAwait(false);
promotes = await metadataService.GetAvatarPromoteListAsync().ConfigureAwait(false);
Dictionary<MaterialId, Material> idMaterialMap = await metadataService.GetIdToMaterialMapAsync().ConfigureAwait(false);
List<Avatar> avatars = await metadataService.GetAvatarListAsync().ConfigureAwait(false);
IOrderedEnumerable<Avatar> sorted = avatars
.OrderByDescending(avatar => avatar.BeginTime)
.ThenByDescending(avatar => avatar.Sort);
List<Avatar> list = [.. sorted];
await CombineComplexDataAsync(list, idMaterialMap).ConfigureAwait(false);
await taskContext.SwitchToMainThreadAsync();
Avatars = new(list, true);
Selected = Avatars.View.ElementAtOrDefault(0);
FilterTokens = [];
availableTokens = FrozenDictionary.ToFrozenDictionary(
[
.. avatars.Select(avatar => KeyValuePair.Create(avatar.Name, new SearchToken(SearchTokenKind.Avatar, avatar.Name, sideIconUri: AvatarSideIconConverter.IconNameToUri(avatar.SideIcon)))),
.. IntrinsicFrozen.AssociationTypes.Select(assoc => KeyValuePair.Create(assoc, new SearchToken(SearchTokenKind.AssociationType, assoc, iconUri: AssociationTypeIconConverter.AssociationTypeNameToIconUri(assoc)))),
.. IntrinsicFrozen.BodyTypes.Select(b => KeyValuePair.Create(b, new SearchToken(SearchTokenKind.BodyType, b))),
.. IntrinsicFrozen.ElementNames.Select(e => KeyValuePair.Create(e, new SearchToken(SearchTokenKind.ElementName, e, iconUri: ElementNameIconConverter.ElementNameToIconUri(e)))),
.. IntrinsicFrozen.ItemQualities.Select(i => KeyValuePair.Create(i, new SearchToken(SearchTokenKind.ItemQuality, i, quality: QualityColorConverter.QualityNameToColor(i)))),
.. IntrinsicFrozen.WeaponTypes.Select(w => KeyValuePair.Create(w, new SearchToken(SearchTokenKind.WeaponType, w, iconUri: WeaponTypeIconConverter.WeaponTypeNameToIconUri(w)))),
]);
return true;
return false;
}
private async ValueTask CombineComplexDataAsync(List<Avatar> avatars, Dictionary<MaterialId, Material> idMaterialMap)

View File

@@ -53,21 +53,31 @@ internal sealed partial class WikiMonsterViewModel : Abstraction.ViewModel
{
if (await metadataService.InitializeAsync().ConfigureAwait(false))
{
levelMonsterCurveMap = await metadataService.GetLevelToMonsterCurveMapAsync().ConfigureAwait(false);
List<Monster> monsters = await metadataService.GetMonsterListAsync().ConfigureAwait(false);
Dictionary<MaterialId, DisplayItem> idDisplayMap = await metadataService.GetIdToDisplayItemAndMaterialMapAsync().ConfigureAwait(false);
foreach (Monster monster in monsters)
try
{
levelMonsterCurveMap = await metadataService.GetLevelToMonsterCurveMapAsync().ConfigureAwait(false);
List<Monster> monsters = await metadataService.GetMonsterListAsync().ConfigureAwait(false);
Dictionary<MaterialId, DisplayItem> idDisplayMap = await metadataService.GetIdToDisplayItemAndMaterialMapAsync().ConfigureAwait(false);
foreach (Monster monster in monsters)
{
monster.DropsView ??= monster.Drops?.SelectList(i => idDisplayMap.GetValueOrDefault(i, Material.Default));
}
List<Monster> ordered = monsters.SortBy(m => m.RelationshipId.Value);
using (await EnterCriticalExecutionAsync().ConfigureAwait(false))
{
await taskContext.SwitchToMainThreadAsync();
Monsters = new(ordered, true);
Selected = Monsters.View.ElementAtOrDefault(0);
}
return true;
}
catch (OperationCanceledException)
{
monster.DropsView ??= monster.Drops?.SelectList(i => idDisplayMap.GetValueOrDefault(i, Material.Default));
}
List<Monster> ordered = monsters.SortBy(m => m.RelationshipId.Value);
await taskContext.SwitchToMainThreadAsync();
Monsters = new(ordered, true);
Selected = Monsters.View.ElementAtOrDefault(0);
return true;
}
return false;

View File

@@ -92,32 +92,42 @@ internal sealed partial class WikiWeaponViewModel : Abstraction.ViewModel
{
if (await metadataService.InitializeAsync().ConfigureAwait(false))
{
levelWeaponCurveMap = await metadataService.GetLevelToWeaponCurveMapAsync().ConfigureAwait(false);
promotes = await metadataService.GetWeaponPromoteListAsync().ConfigureAwait(false);
Dictionary<MaterialId, Material> idMaterialMap = await metadataService.GetIdToMaterialMapAsync().ConfigureAwait(false);
try
{
levelWeaponCurveMap = await metadataService.GetLevelToWeaponCurveMapAsync().ConfigureAwait(false);
promotes = await metadataService.GetWeaponPromoteListAsync().ConfigureAwait(false);
Dictionary<MaterialId, Material> idMaterialMap = await metadataService.GetIdToMaterialMapAsync().ConfigureAwait(false);
List<Weapon> weapons = await metadataService.GetWeaponListAsync().ConfigureAwait(false);
IEnumerable<Weapon> sorted = weapons
.OrderByDescending(weapon => weapon.RankLevel)
.ThenBy(weapon => weapon.WeaponType)
.ThenByDescending(weapon => weapon.Id.Value);
List<Weapon> list = [.. sorted];
List<Weapon> weapons = await metadataService.GetWeaponListAsync().ConfigureAwait(false);
IEnumerable<Weapon> sorted = weapons
.OrderByDescending(weapon => weapon.RankLevel)
.ThenBy(weapon => weapon.WeaponType)
.ThenByDescending(weapon => weapon.Id.Value);
List<Weapon> list = [.. sorted];
await CombineComplexDataAsync(list, idMaterialMap).ConfigureAwait(false);
await CombineComplexDataAsync(list, idMaterialMap).ConfigureAwait(false);
await taskContext.SwitchToMainThreadAsync();
using (await EnterCriticalExecutionAsync().ConfigureAwait(false))
{
await taskContext.SwitchToMainThreadAsync();
Weapons = new(list, true);
Selected = Weapons.View.ElementAtOrDefault(0);
FilterTokens = [];
Weapons = new(list, true);
Selected = Weapons.View.ElementAtOrDefault(0);
}
availableTokens = FrozenDictionary.ToFrozenDictionary(
[
.. weapons.Select(w => KeyValuePair.Create(w.Name, new SearchToken(SearchTokenKind.Weapon, w.Name, sideIconUri: EquipIconConverter.IconNameToUri(w.Icon)))),
.. IntrinsicFrozen.FightProperties.Select(f => KeyValuePair.Create(f, new SearchToken(SearchTokenKind.FightProperty, f))),
.. IntrinsicFrozen.ItemQualities.Select(i => KeyValuePair.Create(i, new SearchToken(SearchTokenKind.ItemQuality, i, quality: QualityColorConverter.QualityNameToColor(i)))),
.. IntrinsicFrozen.WeaponTypes.Select(w => KeyValuePair.Create(w, new SearchToken(SearchTokenKind.WeaponType, w, iconUri: WeaponTypeIconConverter.WeaponTypeNameToIconUri(w)))),
]);
FilterTokens = [];
availableTokens = FrozenDictionary.ToFrozenDictionary(
[
.. weapons.Select(w => KeyValuePair.Create(w.Name, new SearchToken(SearchTokenKind.Weapon, w.Name, sideIconUri: EquipIconConverter.IconNameToUri(w.Icon)))),
.. IntrinsicFrozen.FightProperties.Select(f => KeyValuePair.Create(f, new SearchToken(SearchTokenKind.FightProperty, f))),
.. IntrinsicFrozen.ItemQualities.Select(i => KeyValuePair.Create(i, new SearchToken(SearchTokenKind.ItemQuality, i, quality: QualityColorConverter.QualityNameToColor(i)))),
.. IntrinsicFrozen.WeaponTypes.Select(w => KeyValuePair.Create(w, new SearchToken(SearchTokenKind.WeaponType, w, iconUri: WeaponTypeIconConverter.WeaponTypeNameToIconUri(w)))),
]);
}
catch (OperationCanceledException)
{
}
}
}

View File

@@ -1,16 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Core.DependencyInjection.Annotation.HttpClient;
using Snap.Hutao.Service.Game.Scheme;
using Snap.Hutao.Web.Hoyolab.SdkStatic.Hk4e.Launcher.Resource;
using Snap.Hutao.Web.Request.Builder;
using Snap.Hutao.Web.Request.Builder.Abstraction;
using Snap.Hutao.Web.Response;
using System.IO;
using System.Net.Http;
using System.Text;
namespace Snap.Hutao.Web.Hoyolab.SdkStatic.Hk4e.Launcher;
internal sealed class IconLink

View File

@@ -0,0 +1,21 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using System.Text;
namespace Snap.Hutao.Web.Hoyolab.SdkStatic.Hk4e.Launcher.Resource;
internal static class LatestPackageExtension
{
public static void Patch(this LatestPackage latest)
{
StringBuilder pathBuilder = new();
foreach (PackageSegment segment in latest.Segments)
{
pathBuilder.AppendLine(segment.Path);
}
latest.Path = pathBuilder.ToStringTrimEndReturn();
latest.Name = latest.Segments[0].Path[..^4]; // .00X
}
}

View File

@@ -46,18 +46,16 @@ internal sealed partial class ResourceClient
.TryCatchSendAsync<Response<GameResource>>(httpClient, logger, token)
.ConfigureAwait(false);
// 补全缺失的信息
// 最新版完整包
if (resp is { Data.Game.Latest: LatestPackage latest })
{
StringBuilder pathBuilder = new();
foreach (PackageSegment segment in latest.Segments)
{
pathBuilder.AppendLine(segment.Path);
}
latest.Patch();
}
latest.Path = pathBuilder.ToStringTrimEndReturn();
string path = latest.Segments[0].Path[..^4]; // .00X
latest.Name = Path.GetFileName(path);
// 预下载完整包
if (resp is { Data.PreDownloadGame.Latest: LatestPackage preDownloadLatest })
{
preDownloadLatest.Patch();
}
return Response.Response.DefaultIfNull(resp);