Compare commits

...

47 Commits

Author SHA1 Message Date
Lightczx
9f8f2870ae remove blank spaces 2024-05-28 16:01:13 +08:00
qhy040404
7aa4696ba5 drop else 2024-05-27 22:11:38 +08:00
qhy040404
cd91af8ae9 use ref readonly 2024-05-27 09:29:58 +08:00
qhy040404
67f6fda900 another impl of hint when icon promoted for win10 2024-05-26 21:53:22 +08:00
DismissedLight
db4b0d3dcb Merge pull request #1641 from DGP-Studio/develop 2024-05-26 18:16:20 +08:00
DismissedLight
ec0abb4b16 bump version 2024-05-26 18:15:30 +08:00
DismissedLight
8cdf2b01f2 minor fix 2024-05-26 15:06:55 +08:00
qhy040404
c1bf3dad52 fix daily note setting 2024-05-26 11:16:46 +08:00
Lightczx
492e867391 exception refine 2024-05-24 17:16:33 +08:00
Lightczx
9cbb36f3e6 disable runtime marshaling 2024-05-24 16:54:05 +08:00
Lightczx
e15c06a194 fix build 2024-05-24 14:58:36 +08:00
Lightczx
f71a2a3d40 code style 2024-05-24 14:27:26 +08:00
DismissedLight
fb89e5f9f0 code style 2024-05-24 00:32:44 +08:00
DismissedLight
3f97f4207c Merge pull request #1636 from DGP-Studio/fix/1632
fix #1632
2024-05-23 20:14:47 +08:00
DismissedLight
a4ea798ad0 Merge pull request #1637 from DGP-Studio/feat/dailynote_prompt 2024-05-23 20:14:11 +08:00
qhy040404
80a0daf02d refine ui 2024-05-23 19:36:48 +08:00
qhy040404
c511d27b2f disable settings when not elevated 2024-05-23 19:36:48 +08:00
qhy040404
c5dcbc9c79 fix #1632 2024-05-23 19:36:48 +08:00
qhy040404
91949214ba apply suggestion 2024-05-23 19:21:29 +08:00
qhy040404
a126a330ff prompt user dailynote auto-refresh is not effective while notify icon is disabled 2024-05-23 19:21:29 +08:00
Lightczx
055846dfd6 fix notify icon context menu theme 2024-05-23 15:00:20 +08:00
DismissedLight
b68462b56e Update README.md 2024-05-23 11:46:48 +08:00
qhy040404
9d47082f47 fix #1631 2024-05-22 22:59:53 +08:00
DismissedLight
cd4516d9a7 Merge pull request #1630 from DGP-Studio/feat/1595 2024-05-22 17:02:13 +08:00
Lightczx
f7e94fe2f2 refine view 2024-05-22 16:46:06 +08:00
qhy040404
e93802d5a5 partial impl #1595 2024-05-22 15:37:04 +08:00
Lightczx
370f2fe1f7 impl #1542 2024-05-22 12:44:20 +08:00
qhy040404
c6f747a89b fix wrap layout 2024-05-21 23:53:23 +08:00
DismissedLight
cf431719df temp fix wrap layout 2024-05-21 23:14:51 +08:00
DismissedLight
c36c15f9be Merge pull request #1628 from DGP-Studio/fix/1609
fix #1609
2024-05-21 22:07:27 +08:00
DismissedLight
f80a63f557 Merge pull request #1627 from DGP-Studio/fix/1608
fix #1608
2024-05-21 22:03:48 +08:00
DismissedLight
36376f5af6 Update SH.resx 2024-05-21 22:03:10 +08:00
DismissedLight
2c057458a3 Merge pull request #1626 from DGP-Studio/fix/1613
fix #1613
2024-05-21 21:59:38 +08:00
DismissedLight
f0f50e0e30 Merge pull request #1625 from DGP-Studio/fix/1588
fix #1588
2024-05-21 21:48:25 +08:00
DismissedLight
b834daef93 Merge pull request #1619 from DGP-Studio/fix/new_dailynote_archon 2024-05-21 21:34:04 +08:00
DismissedLight
ff10543c21 Merge pull request #1615 from DGP-Studio/build/alpha 2024-05-21 21:12:58 +08:00
qhy040404
a55b25ae53 add alpha build constant 2024-05-21 17:34:45 +08:00
qhy040404
c0fbb823d4 fix empty archon quest in new added dailynote 2024-05-21 17:34:29 +08:00
qhy040404
4306af94be fix #1588 2024-05-21 17:34:03 +08:00
qhy040404
dfc83d4a34 fix #1613 2024-05-21 17:33:44 +08:00
qhy040404
c6a47eb7be fix #1608 2024-05-21 17:33:20 +08:00
qhy040404
7413a81ff4 fix #1609 2024-05-21 17:32:59 +08:00
Lightczx
24d143ea9f add France 2024-05-21 17:15:58 +08:00
DismissedLight
9f6611cd20 Merge pull request #1621 from DGP-Studio/feat/ShellNotifyIcon 2024-05-21 17:07:46 +08:00
Masterain
8252e43bac Update alpha.yml
#1623
2024-05-15 21:18:35 -07:00
qhy040404
ce58e35a8f Merge pull request #1617 from DGP-Studio/typo/ci 2024-05-12 16:54:24 +08:00
目棃
a10e9e40a2 ✏️ 修正CI内容 2024-05-12 16:46:32 +08:00
152 changed files with 984 additions and 786 deletions

View File

@@ -29,7 +29,14 @@ on:
jobs: jobs:
build: build:
runs-on: self-hosted runs-on: ${{ matrix.runner }}
strategy:
matrix:
runner:
- self-hosted
- windows-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4

View File

@@ -10,7 +10,7 @@ jobs:
- uses: actions/stale@v9 - uses: actions/stale@v9
with: with:
any-of-labels: 'needs-more-info,需要更多信息' any-of-labels: 'needs-more-info,需要更多信息'
stale-issue-message: 'This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 3 days.' stale-issue-message: 'This issue is stale because it has been open 7 days with no activity. Remove stale label or comment or this will be closed in 3 days.'
days-before-stale: 7 days-before-stale: 7
days-before-close: 3 days-before-close: 3
close-issue-reason: not_planned close-issue-reason: not_planned

View File

@@ -17,7 +17,15 @@ You can follow the instructions in the [Quick Start](https://hut.ao/en/quick-sta
## 本地化翻译 / Localization ## 本地化翻译 / Localization
[![zh-TW translation](https://img.shields.io/badge/dynamic/json?color=blue&label=zh-TW&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27zh-TW%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao) [![en translation](https://img.shields.io/badge/dynamic/json?color=blue&label=en&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27en%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao) [![id translation](https://img.shields.io/badge/dynamic/json?color=blue&label=id&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27id%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao) [![ja translation](https://img.shields.io/badge/dynamic/json?color=blue&label=ja&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27ja%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao) [![ko translation](https://img.shields.io/badge/dynamic/json?color=blue&label=ko&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27ko%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao) [![pt-PT translation](https://img.shields.io/badge/dynamic/json?color=blue&label=pt-PT&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27pt-PT%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao) [![ru translation](https://img.shields.io/badge/dynamic/json?color=blue&label=ru&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27ru%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao) [![zh-TW translation](https://img.shields.io/badge/dynamic/json?color=blue&label=zh-TW&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27zh-TW%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao)
[![en translation](https://img.shields.io/badge/dynamic/json?color=blue&label=en&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27en%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao)
[![fr translation](https://img.shields.io/badge/dynamic/json?color=blue&label=fr&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27fr%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao)
[![id translation](https://img.shields.io/badge/dynamic/json?color=blue&label=id&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27id%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao)
[![ja translation](https://img.shields.io/badge/dynamic/json?color=blue&label=ja&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27ja%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao)
[![ko translation](https://img.shields.io/badge/dynamic/json?color=blue&label=ko&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27ko%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao)
[![pt-PT translation](https://img.shields.io/badge/dynamic/json?color=blue&label=pt-PT&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27pt-PT%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao)
[![ru translation](https://img.shields.io/badge/dynamic/json?color=blue&label=ru&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27ru%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao)
[![vi translation](https://img.shields.io/badge/dynamic/json?color=blue&label=vi&style=flat&logo=crowdin&query=%24.progress[?(@.data.languageId==%27vi%27)].data.translationProgress&url=https%3A%2F%2Fbadges.awesome-crowdin.com%2Fstats-15670597-565845.json)](https://crowdin.com/project/snap-hutao)
Snap Hutao 使用 [Crowdin](https://translate.hut.ao/) 作为客户端文本翻译平台,在该平台上你可以为你熟悉的语言提交翻译文本。我们感谢每一个为 Snap Hutao 做出贡献的社区成员,并且欢迎更多的朋友能参与到这个项目中。 Snap Hutao 使用 [Crowdin](https://translate.hut.ao/) 作为客户端文本翻译平台,在该平台上你可以为你熟悉的语言提交翻译文本。我们感谢每一个为 Snap Hutao 做出贡献的社区成员,并且欢迎更多的朋友能参与到这个项目中。
@@ -46,13 +54,13 @@ Snap Hutao uses [Crowdin](https://translate.hut.ao/) as a client text translatio
* [CommunityToolkit/dotnet](https://github.com/CommunityToolkit/dotnet) * [CommunityToolkit/dotnet](https://github.com/CommunityToolkit/dotnet)
* [CommunityToolkit/Labs-Windows](https://github.com/CommunityToolkit/Labs-Windows) * [CommunityToolkit/Labs-Windows](https://github.com/CommunityToolkit/Labs-Windows)
* [CommunityToolkit/Windows](https://github.com/CommunityToolkit/Windows) * [CommunityToolkit/Windows](https://github.com/CommunityToolkit/Windows)
* [dahall/taskscheduler](https://github.com/dahall/taskscheduler)
* [dotnet/efcore](https://github.com/dotnet/efcore) * [dotnet/efcore](https://github.com/dotnet/efcore)
* [dotnet/runtime](https://github.com/dotnet/runtime) * [dotnet/runtime](https://github.com/dotnet/runtime)
* [DotNetAnalyzers/StyleCopAnalyzers](https://github.com/DotNetAnalyzers/StyleCopAnalyzers) * [DotNetAnalyzers/StyleCopAnalyzers](https://github.com/DotNetAnalyzers/StyleCopAnalyzers)
* [microsoft/vs-validation](https://github.com/microsoft/vs-validation) * [microsoft/vs-validation](https://github.com/microsoft/vs-validation)
* [microsoft/WindowsAppSDK](https://github.com/microsoft/WindowsAppSDK) * [microsoft/WindowsAppSDK](https://github.com/microsoft/WindowsAppSDK)
* [microsoft/microsoft-ui-xaml](https://github.com/microsoft/microsoft-ui-xaml) * [microsoft/microsoft-ui-xaml](https://github.com/microsoft/microsoft-ui-xaml)
* [quartznet/quartznet](https://github.com/quartznet/quartznet)
### 支撑项目 / Supporter Project ### 支撑项目 / Supporter Project
@@ -64,9 +72,9 @@ Snap Hutao uses [Crowdin](https://translate.hut.ao/) as a client text translatio
Snap Hutao is currently using sponsored software from the following service providers. Snap Hutao is currently using sponsored software from the following service providers.
| [![](https://www.netlify.com/v3/img/components/netlify-light.svg)](https://www.netlify.com/) | [![](https://support.crowdin.com/assets/logos/core-logo/svg/crowdin-core-logo-cDark.svg)](https://crowdin.com/) | [![](https://gitlab.cn/images/icons/logos/logo-121-75.svg)](https://gitlab.cn/) | | [![](https://www.netlify.com/v3/img/components/netlify-light.svg)](https://www.netlify.com/) | [![](https://support.crowdin.com/assets/logos/core-logo/svg/crowdin-core-logo-cDark.svg)](https://crowdin.com/) | [![](https://gitlab.cn/images/icons/logos/logo-121-75.svg)](https://gitlab.cn/) |
|:----------------------------------------------------------------------------------------------------:|:-----------------------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------------------------------:| |:-:|:-:|:-:|
| [![](https://github.com/DGP-Studio/Snap.Hutao/assets/10614984/73ae8b90-f3c7-4033-b2b7-f4126331ce66)](https://about.signpath.io) | [![](https://github.com/DGP-Studio/Snap.Hutao/assets/10614984/49aed8ee-9f19-4a8a-998c-7b93ee286d65)](https://1password.com/) | [![](https://github.com/DGP-Studio/Snap.Hutao/assets/10614984/ad121220-d2d3-4f49-b215-b6d063dc229d)](https://about.signpath.io) | |[![](https://github.com/DGP-Studio/Snap.Hutao/assets/10614984/73ae8b90-f3c7-4033-b2b7-f4126331ce66)](https://about.signpath.io)|[![](https://github.com/DGP-Studio/Snap.Hutao/assets/10614984/49aed8ee-9f19-4a8a-998c-7b93ee286d65)](https://1password.com/)|[![](https://github.com/DGP-Studio/Snap.Hutao/assets/10614984/ad121220-d2d3-4f49-b215-b6d063dc229d)](https://www.digitalocean.com)|
|[![jetbrains](https://github.com/DGP-Studio/Snap.Hutao/assets/36357191/4105772a-728a-4a84-9c6e-d713a5698a20)](https://www.jetbrains.com/opensource/)|||
- Netlify provides document and home page hosting service for Snap Hutao - Netlify provides document and home page hosting service for Snap Hutao
@@ -80,6 +88,8 @@ Snap Hutao is currently using sponsored software from the following service prov
- DigitalOcean provides reliable cloud database for Snap Hutao database backup - DigitalOcean provides reliable cloud database for Snap Hutao database backup
- Jetbrains provides powerful IDE for Snap Hutao infrastructure services coding
## 开发 / Development ## 开发 / Development
![Snap.Hutao](https://repobeats.axiom.co/api/embed/f029553fbe0c60689b1710476ec8512452163fc9.svg) ![Snap.Hutao](https://repobeats.axiom.co/api/embed/f029553fbe0c60689b1710476ec8512452163fc9.svg)

View File

@@ -11,6 +11,15 @@ var version = "version";
var repoDir = "repoDir"; var repoDir = "repoDir";
var outputPath = "outputPath"; var outputPath = "outputPath";
// Extension
static ProcessArgumentBuilder AppendIf(this ProcessArgumentBuilder builder, string text, bool condition)
{
return condition ? builder.Append(text) : builder;
}
// Properties
string solution string solution
{ {
get => System.IO.Path.Combine(repoDir, "src", "Snap.Hutao", "Snap.Hutao.sln"); get => System.IO.Path.Combine(repoDir, "src", "Snap.Hutao", "Snap.Hutao.sln");
@@ -157,6 +166,7 @@ Task("Build binary package")
.Append("/p:AppxPackageSigningEnabled=false") .Append("/p:AppxPackageSigningEnabled=false")
.Append("/p:AppxBundle=Never") .Append("/p:AppxBundle=Never")
.Append("/p:AppxPackageOutput=" + outputPath) .Append("/p:AppxPackageOutput=" + outputPath)
.AppendIf("/p:AlphaConstants=IS_ALPHA_BUILD", !AppVeyor.IsRunningOnAppVeyor)
}; };
DotNetBuild(project, settings); DotNetBuild(project, settings);

View File

@@ -1,5 +1,4 @@
using Microsoft.VisualStudio.TestTools.UnitTesting; using System;
using System;
namespace Snap.Hutao.Test.BaseClassLibrary; namespace Snap.Hutao.Test.BaseClassLibrary;

View File

@@ -16,7 +16,7 @@ public class UnsafeAccessorTest
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "get_TestProperty")] [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "get_TestProperty")]
private static extern int InternalGetInterfaceProperty(ITestInterface instance); private static extern int InternalGetInterfaceProperty(ITestInterface instance);
interface ITestInterface internal interface ITestInterface
{ {
internal int TestProperty { get; } internal int TestProperty { get; }
} }

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@@ -46,7 +47,14 @@ public sealed class UnsafeRuntimeBehaviorTest
Assert.AreEqual(1212, testStruct.Value4); Assert.AreEqual(1212, testStruct.Value4);
} }
[TestMethod]
public unsafe void UnsafeUtf8StringReference()
{
void* ptr = Unsafe.AsPointer(ref MemoryMarshal.GetReference("test"u8));
GC.Collect(GC.MaxGeneration);
ReadOnlySpan<byte> bytes = MemoryMarshal.CreateReadOnlySpanFromNullTerminated((byte*)ptr);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(bytes));
}
private readonly struct TestStruct private readonly struct TestStruct
{ {

View File

@@ -85,7 +85,7 @@ public sealed partial class App : Application
} }
catch (Exception ex) catch (Exception ex)
{ {
System.Diagnostics.Debug.WriteLine(ex); Debug.WriteLine(ex);
Process.GetCurrentProcess().Kill(); Process.GetCurrentProcess().Kill();
} }
} }

View File

@@ -7,7 +7,7 @@ namespace Snap.Hutao.Control.Collection.AdvancedCollectionView;
internal sealed class VectorChangedEventArgs : IVectorChangedEventArgs internal sealed class VectorChangedEventArgs : IVectorChangedEventArgs
{ {
public VectorChangedEventArgs(CollectionChange cc, int index = -1, object item = null!) public VectorChangedEventArgs(CollectionChange cc, int index = -1, object item = default!)
{ {
CollectionChange = cc; CollectionChange = cc;
Index = (uint)index; Index = (uint)index;

View File

@@ -3,6 +3,7 @@
using Microsoft.UI.Xaml; using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Data; using Microsoft.UI.Xaml.Data;
using Snap.Hutao.Core.ExceptionService;
namespace Snap.Hutao.Control; namespace Snap.Hutao.Control;
@@ -40,6 +41,6 @@ internal abstract class DependencyValueConverter<TFrom, TTo> : DependencyObject,
/// <returns>源</returns> /// <returns>源</returns>
public virtual TFrom ConvertBack(TTo to) public virtual TFrom ConvertBack(TTo to)
{ {
throw Must.NeverHappen(); throw HutaoException.NotSupported();
} }
} }

View File

@@ -39,7 +39,6 @@ internal static class FrameworkElementExtension
} }
catch (Exception ex) catch (Exception ex)
{ {
ILogger? logger = service.GetRequiredService(typeof(ILogger<>).MakeGenericType([frameworkElement.GetType()])) as ILogger; ILogger? logger = service.GetRequiredService(typeof(ILogger<>).MakeGenericType([frameworkElement.GetType()])) as ILogger;
logger?.LogError(ex, "Failed to initialize DataContext"); logger?.LogError(ex, "Failed to initialize DataContext");
throw; throw;

View File

@@ -7,6 +7,8 @@ namespace Snap.Hutao.Control.Helper;
[SuppressMessage("", "SH001")] [SuppressMessage("", "SH001")]
[DependencyProperty("SquareLength", typeof(double), 0D, nameof(OnSquareLengthChanged), IsAttached = true, AttachedType = typeof(FrameworkElement))] [DependencyProperty("SquareLength", typeof(double), 0D, nameof(OnSquareLengthChanged), IsAttached = true, AttachedType = typeof(FrameworkElement))]
[DependencyProperty("IsActualThemeBindingEnabled", typeof(bool), false, nameof(OnIsActualThemeBindingEnabled), IsAttached = true, AttachedType = typeof(FrameworkElement))]
[DependencyProperty("ActualTheme", typeof(ElementTheme), ElementTheme.Default, IsAttached = true, AttachedType = typeof(FrameworkElement))]
public sealed partial class FrameworkElementHelper public sealed partial class FrameworkElementHelper
{ {
private static void OnSquareLengthChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e) private static void OnSquareLengthChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
@@ -15,4 +17,22 @@ public sealed partial class FrameworkElementHelper
element.Width = (double)e.NewValue; element.Width = (double)e.NewValue;
element.Height = (double)e.NewValue; element.Height = (double)e.NewValue;
} }
private static void OnIsActualThemeBindingEnabled(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)dp;
if ((bool)e.NewValue)
{
element.ActualThemeChanged += OnActualThemeChanged;
}
else
{
element.ActualThemeChanged -= OnActualThemeChanged;
}
static void OnActualThemeChanged(FrameworkElement sender, object args)
{
SetActualTheme(sender, sender.ActualTheme);
}
}
} }

View File

@@ -1,8 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved. // Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license. // Licensed under the MIT license.
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using Snap.Hutao.Control.Extension; using Snap.Hutao.Control.Extension;
using Snap.Hutao.Core.Caching; using Snap.Hutao.Core.Caching;
using Snap.Hutao.Core.ExceptionService; using Snap.Hutao.Core.ExceptionService;

View File

@@ -6,9 +6,6 @@ using Microsoft.UI.Composition;
using Microsoft.UI.Xaml; using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging; using Microsoft.UI.Xaml.Media.Imaging;
using Snap.Hutao.Win32;
using System.IO;
using Windows.Foundation;
namespace Snap.Hutao.Control.Image.Implementation; namespace Snap.Hutao.Control.Image.Implementation;

View File

@@ -63,12 +63,12 @@ internal sealed partial class UniformStaggeredLayout : VirtualizingLayout
/// <inheritdoc/> /// <inheritdoc/>
protected override Size MeasureOverride(VirtualizingLayoutContext context, Size availableSize) protected override Size MeasureOverride(VirtualizingLayoutContext context, Size availableSize)
{ {
if (context.ItemCount == 0) if (context.ItemCount is 0)
{ {
return new Size(availableSize.Width, 0); return new Size(availableSize.Width, 0);
} }
if ((context.RealizationRect.Width == 0) && (context.RealizationRect.Height == 0)) if ((context.RealizationRect.Width is 0) && (context.RealizationRect.Height is 0))
{ {
return new Size(availableSize.Width, 0.0f); return new Size(availableSize.Width, 0.0f);
} }

View File

@@ -0,0 +1,25 @@
// Licensed to the .NET Fou// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Xaml;
using Windows.Foundation;
namespace Snap.Hutao.Control.Layout;
internal sealed class WrapItem
{
public WrapItem(int index)
{
Index = index;
}
public static Point EmptyPosition { get; } = new(float.NegativeInfinity, float.NegativeInfinity);
public int Index { get; }
public Size Size { get; set; } = Size.Empty;
public Point Position { get; set; } = EmptyPosition;
public UIElement? Element { get; set; }
}

View File

@@ -0,0 +1,220 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System.Collections.Specialized;
using Windows.Foundation;
namespace Snap.Hutao.Control.Layout;
[DependencyProperty("HorizontalSpacing", typeof(double), 0D, nameof(LayoutPropertyChanged))]
[DependencyProperty("VerticalSpacing", typeof(double), 0D, nameof(LayoutPropertyChanged))]
internal sealed partial class WrapLayout : VirtualizingLayout
{
protected override void InitializeForContextCore(VirtualizingLayoutContext context)
{
context.LayoutState = new WrapLayoutState(context);
}
protected override void UninitializeForContextCore(VirtualizingLayoutContext context)
{
context.LayoutState = default;
}
protected override void OnItemsChangedCore(VirtualizingLayoutContext context, object source, NotifyCollectionChangedEventArgs args)
{
WrapLayoutState state = (WrapLayoutState)context.LayoutState;
switch (args.Action)
{
case NotifyCollectionChangedAction.Add:
state.RemoveFromIndex(args.NewStartingIndex);
break;
case NotifyCollectionChangedAction.Move:
int minIndex = Math.Min(args.NewStartingIndex, args.OldStartingIndex);
state.RemoveFromIndex(minIndex);
state.RecycleElementAt(args.OldStartingIndex);
state.RecycleElementAt(args.NewStartingIndex);
break;
case NotifyCollectionChangedAction.Remove:
state.RemoveFromIndex(args.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Replace:
state.RemoveFromIndex(args.NewStartingIndex);
state.RecycleElementAt(args.NewStartingIndex);
break;
case NotifyCollectionChangedAction.Reset:
state.Clear();
break;
}
base.OnItemsChangedCore(context, source, args);
}
protected override Size MeasureOverride(VirtualizingLayoutContext context, Size availableSize)
{
if (context.ItemCount is 0)
{
return new Size(availableSize.Width, 0);
}
if ((context.RealizationRect.Width is 0) && (context.RealizationRect.Height is 0))
{
return new Size(availableSize.Width, 0.0f);
}
Size spacing = new(HorizontalSpacing, VerticalSpacing);
WrapLayoutState state = (WrapLayoutState)context.LayoutState;
if (spacing != state.Spacing || state.AvailableWidth != availableSize.Width)
{
state.ClearPositions();
state.Spacing = spacing;
state.AvailableWidth = availableSize.Width;
}
double currentHeight = 0;
Point itemPosition = default;
for (int i = 0; i < context.ItemCount; ++i)
{
bool itemMeasured = false;
WrapItem item = state.GetItemAt(i);
if (item.Size == Size.Empty)
{
item.Element = context.GetOrCreateElementAt(i);
item.Element.Measure(availableSize);
item.Size = item.Element.DesiredSize;
itemMeasured = true;
}
Size itemSize = item.Size;
if (item.Position == WrapItem.EmptyPosition)
{
if (availableSize.Width < itemPosition.X + itemSize.Width)
{
// New Row
itemPosition.X = 0;
itemPosition.Y += currentHeight + spacing.Height;
currentHeight = 0;
}
item.Position = itemPosition;
}
itemPosition = item.Position;
double bottom = itemPosition.Y + itemSize.Height;
if (bottom < context.RealizationRect.Top)
{
// Item is "above" the bounds
if (item.Element is not null)
{
context.RecycleElement(item.Element);
item.Element = default;
}
continue;
}
else if (itemPosition.Y > context.RealizationRect.Bottom)
{
// Item is "below" the bounds.
if (item.Element is not null)
{
context.RecycleElement(item.Element);
item.Element = default;
}
// We don't need to measure anything below the bounds
break;
}
else if (!itemMeasured)
{
// Always measure elements that are within the bounds
item.Element = context.GetOrCreateElementAt(i);
item.Element.Measure(availableSize);
itemSize = item.Element.DesiredSize;
if (itemSize != item.Size)
{
// this item changed size; we need to recalculate layout for everything after this
state.RemoveFromIndex(i + 1);
item.Size = itemSize;
// did the change make it go into the new row?
if (availableSize.Width < itemPosition.X + itemSize.Width)
{
// New Row
itemPosition.X = 0;
itemPosition.Y += currentHeight + spacing.Height;
currentHeight = 0;
}
item.Position = itemPosition;
}
}
itemPosition.X += itemSize.Width + spacing.Width;
currentHeight = Math.Max(itemSize.Height, currentHeight);
}
return new Size(double.IsInfinity(availableSize.Width) ? 0 : Math.Ceiling(availableSize.Width), state.GetHeight());
}
protected override Size ArrangeOverride(VirtualizingLayoutContext context, Size finalSize)
{
if (context.ItemCount > 0)
{
WrapLayoutState state = (WrapLayoutState)context.LayoutState;
for (int i = 0; i < context.ItemCount; ++i)
{
if (!ArrangeItem(context, state.GetItemAt(i)))
{
break;
}
}
}
return finalSize;
static bool ArrangeItem(VirtualizingLayoutContext context, WrapItem item)
{
if (item.Size == Size.Empty || item.Position == WrapItem.EmptyPosition)
{
return false;
}
Size size = item.Size;
Point position = item.Position;
if (context.RealizationRect.Top <= position.Y + size.Height && position.Y <= context.RealizationRect.Bottom)
{
// place the item
UIElement child = context.GetOrCreateElementAt(item.Index);
child.Arrange(new Rect(position, size));
}
else if (position.Y > context.RealizationRect.Bottom)
{
return false;
}
return true;
}
}
private static void LayoutPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is WrapLayout layout)
{
layout.InvalidateMeasure();
layout.InvalidateArrange();
}
}
}

View File

@@ -0,0 +1,109 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Xaml.Controls;
using System.Runtime.InteropServices;
using Windows.Foundation;
namespace Snap.Hutao.Control.Layout;
internal sealed class WrapLayoutState
{
private readonly List<WrapItem> items = [];
private readonly VirtualizingLayoutContext context;
public WrapLayoutState(VirtualizingLayoutContext context)
{
this.context = context;
}
public Orientation Orientation { get; private set; }
public Size Spacing { get; set; }
public double AvailableWidth { get; set; }
public WrapItem GetItemAt(int index)
{
ArgumentOutOfRangeException.ThrowIfNegative(index);
if (index <= (items.Count - 1))
{
return items[index];
}
else
{
WrapItem item = new(index);
items.Add(item);
return item;
}
}
public void Clear()
{
for (int i = 0; i < items.Count; i++)
{
RecycleElementAt(i);
}
items.Clear();
}
public void RemoveFromIndex(int index)
{
if (index >= items.Count)
{
// Item was added/removed but we haven't realized that far yet
return;
}
int numToRemove = items.Count - index;
items.RemoveRange(index, numToRemove);
}
public void ClearPositions()
{
foreach (ref readonly WrapItem item in CollectionsMarshal.AsSpan(items))
{
item.Position = WrapItem.EmptyPosition;
}
}
public double GetHeight()
{
if (items.Count is 0)
{
return 0;
}
Point? lastPosition = default;
double maxHeight = 0;
Span<WrapItem> itemSpan = CollectionsMarshal.AsSpan(items);
for (int i = items.Count - 1; i >= 0; --i)
{
ref readonly WrapItem item = ref itemSpan[i];
if (item.Position == WrapItem.EmptyPosition || item.Size == Size.Empty)
{
continue;
}
if (lastPosition is not null && lastPosition.Value.Y > item.Position.Y)
{
// This is a row above the last item.
break;
}
lastPosition = item.Position;
maxHeight = Math.Max(maxHeight, item.Size.Height);
}
return lastPosition?.Y + maxHeight ?? 0;
}
public void RecycleElementAt(int index)
{
context.RecycleElement(context.GetOrCreateElementAt(index));
}
}

View File

@@ -1,6 +1,8 @@
// Copyright (c) DGP Studio. All rights reserved. // Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license. // Licensed under the MIT license.
using Snap.Hutao.Core.ExceptionService;
namespace Snap.Hutao.Control.Text.Syntax.MiHoYo; namespace Snap.Hutao.Control.Text.Syntax.MiHoYo;
internal sealed class MiHoYoColorTextSyntax : MiHoYoXmlElementSyntax internal sealed class MiHoYoColorTextSyntax : MiHoYoXmlElementSyntax
@@ -27,7 +29,7 @@ internal sealed class MiHoYoColorTextSyntax : MiHoYoXmlElementSyntax
{ {
MiHoYoColorKind.Rgba => new(Position.Start + 17, Position.End - 8), MiHoYoColorKind.Rgba => new(Position.Start + 17, Position.End - 8),
MiHoYoColorKind.Rgb => new(Position.Start + 15, Position.End - 8), MiHoYoColorKind.Rgb => new(Position.Start + 15, Position.End - 8),
_ => throw Must.NeverHappen(), _ => throw HutaoException.NotSupported(),
}; };
} }
} }
@@ -40,7 +42,7 @@ internal sealed class MiHoYoColorTextSyntax : MiHoYoXmlElementSyntax
{ {
MiHoYoColorKind.Rgba => new(Position.Start + 8, Position.Start + 16), MiHoYoColorKind.Rgba => new(Position.Start + 8, Position.Start + 16),
MiHoYoColorKind.Rgb => new(Position.Start + 8, Position.Start + 14), MiHoYoColorKind.Rgb => new(Position.Start + 8, Position.Start + 14),
_ => throw Must.NeverHappen(), _ => throw HutaoException.NotSupported(),
}; };
} }
} }

View File

@@ -1,8 +1,11 @@
// Copyright (c) DGP Studio. All rights reserved. // Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license. // Licensed under the MIT license.
using Snap.Hutao.Core.ExceptionService;
namespace Snap.Hutao.Control.Text.Syntax.MiHoYo; namespace Snap.Hutao.Control.Text.Syntax.MiHoYo;
// TODO: Pooling syntax nodes to reduce memory allocation
internal sealed class MiHoYoSyntaxTree internal sealed class MiHoYoSyntaxTree
{ {
public MiHoYoSyntaxNode Root { get; set; } = default!; public MiHoYoSyntaxNode Root { get; set; } = default!;
@@ -75,7 +78,7 @@ internal sealed class MiHoYoSyntaxTree
{ {
17 => MiHoYoColorKind.Rgba, 17 => MiHoYoColorKind.Rgba,
15 => MiHoYoColorKind.Rgb, 15 => MiHoYoColorKind.Rgb,
_ => throw Must.NeverHappen(), _ => throw HutaoException.NotSupported(),
}; };
TextPosition position = new(0, endOfXmlColorRightClosingAtUnprocessedContent); TextPosition position = new(0, endOfXmlColorRightClosingAtUnprocessedContent);

View File

@@ -2,6 +2,7 @@
// Licensed under the MIT license. // Licensed under the MIT license.
using Microsoft.UI.Xaml.Data; using Microsoft.UI.Xaml.Data;
using Snap.Hutao.Core.ExceptionService;
namespace Snap.Hutao.Control; namespace Snap.Hutao.Control;
@@ -39,6 +40,6 @@ internal abstract class ValueConverter<TFrom, TTo> : IValueConverter
/// <returns>源</returns> /// <returns>源</returns>
public virtual TFrom ConvertBack(TTo to) public virtual TFrom ConvertBack(TTo to)
{ {
throw Must.NeverHappen(); throw HutaoException.NotSupported();
} }
} }

View File

@@ -2,13 +2,9 @@
// Licensed under the MIT license. // Licensed under the MIT license.
using CommunityToolkit.Mvvm.Messaging; using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Quartz; using Quartz;
using Snap.Hutao.Core.Logging; using Snap.Hutao.Core.Logging;
using Snap.Hutao.Service; using Snap.Hutao.Service;
using Snap.Hutao.Service.DailyNote;
using Snap.Hutao.Service.Job;
using System.Collections.Specialized;
using System.Globalization; using System.Globalization;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Windows.Globalization; using Windows.Globalization;

View File

@@ -1,22 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Core.ExceptionService;
/// <summary>
/// 数据库损坏异常
/// </summary>
[HighQuality]
[Obsolete("Use HutaoException instead")]
internal sealed class DatabaseCorruptedException : Exception
{
/// <summary>
/// 构造一个新的用户数据损坏异常
/// </summary>
/// <param name="message">消息</param>
/// <param name="innerException">内部错误</param>
public DatabaseCorruptedException(string message, Exception? innerException)
: base(SH.FormatCoreExceptionServiceDatabaseCorruptedMessage($"{message}\n{innerException?.Message}"), innerException)
{
}
}

View File

@@ -1,6 +1,8 @@
// Copyright (c) DGP Studio. All rights reserved. // Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license. // Licensed under the MIT license.
using System.Runtime.CompilerServices;
namespace Snap.Hutao.Core.ExceptionService; namespace Snap.Hutao.Core.ExceptionService;
internal sealed class HutaoException : Exception internal sealed class HutaoException : Exception
@@ -11,11 +13,13 @@ internal sealed class HutaoException : Exception
} }
[DoesNotReturn] [DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static HutaoException Throw(string message, Exception? innerException = default) public static HutaoException Throw(string message, Exception? innerException = default)
{ {
throw new HutaoException(message, innerException); throw new HutaoException(message, innerException);
} }
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ThrowIf([DoesNotReturnIf(true)] bool condition, string message, Exception? innerException = default) public static void ThrowIf([DoesNotReturnIf(true)] bool condition, string message, Exception? innerException = default)
{ {
if (condition) if (condition)
@@ -24,6 +28,7 @@ internal sealed class HutaoException : Exception
} }
} }
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ThrowIfNot([DoesNotReturnIf(false)] bool condition, string message, Exception? innerException = default) public static void ThrowIfNot([DoesNotReturnIf(false)] bool condition, string message, Exception? innerException = default)
{ {
if (!condition) if (!condition)
@@ -33,18 +38,28 @@ internal sealed class HutaoException : Exception
} }
[DoesNotReturn] [DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static ArgumentException Argument(string message, string? paramName)
{
throw new ArgumentException(message, paramName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static HutaoException GachaStatisticsInvalidItemId(uint id, Exception? innerException = default) public static HutaoException GachaStatisticsInvalidItemId(uint id, Exception? innerException = default)
{ {
throw new HutaoException(SH.FormatServiceGachaStatisticsFactoryItemIdInvalid(id), innerException); throw new HutaoException(SH.FormatServiceGachaStatisticsFactoryItemIdInvalid(id), innerException);
} }
[DoesNotReturn] [DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static HutaoException UserdataCorrupted(string message, Exception? innerException = default) public static HutaoException UserdataCorrupted(string message, Exception? innerException = default)
{ {
throw new HutaoException(message, innerException); throw new HutaoException(message, innerException);
} }
[DoesNotReturn] [DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static InvalidCastException InvalidCast<TFrom, TTo>(string name, Exception? innerException = default) public static InvalidCastException InvalidCast<TFrom, TTo>(string name, Exception? innerException = default)
{ {
string message = $"This instance of '{typeof(TFrom).FullName}' '{name}' doesn't implement '{typeof(TTo).FullName}'"; string message = $"This instance of '{typeof(TFrom).FullName}' '{name}' doesn't implement '{typeof(TTo).FullName}'";
@@ -52,18 +67,21 @@ internal sealed class HutaoException : Exception
} }
[DoesNotReturn] [DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static InvalidOperationException InvalidOperation(string message, Exception? innerException = default) public static InvalidOperationException InvalidOperation(string message, Exception? innerException = default)
{ {
throw new InvalidOperationException(message, innerException); throw new InvalidOperationException(message, innerException);
} }
[DoesNotReturn] [DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static NotSupportedException NotSupported(string? message = default, Exception? innerException = default) public static NotSupportedException NotSupported(string? message = default, Exception? innerException = default)
{ {
throw new NotSupportedException(message, innerException); throw new NotSupportedException(message, innerException);
} }
[DoesNotReturn] [DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static OperationCanceledException OperationCanceled(string message, Exception? innerException = default) public static OperationCanceledException OperationCanceled(string message, Exception? innerException = default)
{ {
throw new OperationCanceledException(message, innerException); throw new OperationCanceledException(message, innerException);

View File

@@ -1,23 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Core.ExceptionService;
/// <summary>
/// 运行环境异常
/// 用户的计算机中的某些设置不符合要求
/// </summary>
[HighQuality]
[Obsolete("Use HutaoException instead")]
internal sealed class RuntimeEnvironmentException : Exception
{
/// <summary>
/// 构造一个新的运行环境异常
/// </summary>
/// <param name="message">消息</param>
/// <param name="innerException">内部错误</param>
public RuntimeEnvironmentException(string message, Exception? innerException)
: base($"{message}\n{innerException?.Message}", innerException)
{
}
}

View File

@@ -1,9 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved. // Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license. // Licensed under the MIT license.
using Snap.Hutao.Service.Game;
using Snap.Hutao.Service.Game.Package;
using System.IO;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
namespace Snap.Hutao.Core.ExceptionService; namespace Snap.Hutao.Core.ExceptionService;
@@ -22,92 +19,4 @@ internal static class ThrowHelper
{ {
throw new ArgumentException(message, paramName); throw new ArgumentException(message, paramName);
} }
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static DatabaseCorruptedException DatabaseCorrupted(string message, Exception? inner)
{
throw new DatabaseCorruptedException(message, inner);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static GameFileOperationException GameFileOperation(string message, Exception? inner)
{
throw new GameFileOperationException(message, inner);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static InvalidDataException InvalidData(string message, Exception? inner = default)
{
throw new InvalidDataException(message, inner);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void InvalidDataIf([DoesNotReturnIf(true)] bool condition, string message, Exception? inner = default)
{
if (condition)
{
throw new InvalidDataException(message, inner);
}
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static InvalidOperationException InvalidOperation(string message, Exception? inner = default)
{
throw new InvalidOperationException(message, inner);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static NotSupportedException NotSupported()
{
throw new NotSupportedException();
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static NotSupportedException NotSupported(string message)
{
throw new NotSupportedException(message);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void NotSupportedIf(bool condition, string message)
{
if (condition)
{
throw new NotSupportedException(message);
}
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static OperationCanceledException OperationCanceled(string message, Exception? inner = default)
{
throw new OperationCanceledException(message, inner);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static PackageConvertException PackageConvert(string message, Exception? inner = default)
{
throw new PackageConvertException(message, inner);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static RuntimeEnvironmentException RuntimeEnvironment(string message, Exception? inner)
{
throw new RuntimeEnvironmentException(message, inner);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static UserdataCorruptedException UserdataCorrupted(string message, Exception? inner)
{
throw new UserdataCorruptedException(message, inner);
}
} }

View File

@@ -1,22 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Core.ExceptionService;
/// <summary>
/// 用户数据损坏异常
/// </summary>
[HighQuality]
[Obsolete("Use HutaoException instead")]
internal sealed class UserdataCorruptedException : Exception
{
/// <summary>
/// 构造一个新的用户数据损坏异常
/// </summary>
/// <param name="message">消息</param>
/// <param name="innerException">内部错误</param>
public UserdataCorruptedException(string message, Exception? innerException)
: base(SH.FormatCoreExceptionServiceUserdataCorruptedMessage($"{message}\n{innerException?.Message}"), innerException)
{
}
}

View File

@@ -78,7 +78,7 @@ internal sealed class HttpShardCopyWorker<TStatus> : IDisposable
using (HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false)) using (HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false))
{ {
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
using (IMemoryOwner<byte> memoryOwner = MemoryPool<byte>.Shared.Rent()) using (IMemoryOwner<byte> memoryOwner = MemoryPool<byte>.Shared.Rent(bufferSize))
{ {
Memory<byte> buffer = memoryOwner.Memory; Memory<byte> buffer = memoryOwner.Memory;
using (Stream stream = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false)) using (Stream stream = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false))

View File

@@ -27,6 +27,7 @@ internal sealed class StreamReaderWriter : IDisposable
} }
/// <inheritdoc cref="StreamWriter.WriteAsync(string?)"/> /// <inheritdoc cref="StreamWriter.WriteAsync(string?)"/>
[SuppressMessage("", "SH003")]
public Task WriteAsync(string value) public Task WriteAsync(string value)
{ {
return writer.WriteAsync(value); return writer.WriteAsync(value);

View File

@@ -22,7 +22,7 @@ internal sealed class SeparatorCommaInt32EnumerableConverter : JsonConverter<IEn
return EnumerateNumbers(source); return EnumerateNumbers(source);
} }
return Enumerable.Empty<int>(); return [];
} }
/// <inheritdoc/> /// <inheritdoc/>

View File

@@ -44,6 +44,7 @@ internal sealed partial class AppActivation : IAppActivation, IAppActivationActi
private readonly IServiceProvider serviceProvider; private readonly IServiceProvider serviceProvider;
private readonly ICurrentXamlWindowReference currentWindowReference; private readonly ICurrentXamlWindowReference currentWindowReference;
private readonly ITaskContext taskContext; private readonly ITaskContext taskContext;
private readonly SemaphoreSlim activateSemaphore = new(1); private readonly SemaphoreSlim activateSemaphore = new(1);
/// <inheritdoc/> /// <inheritdoc/>
@@ -65,16 +66,27 @@ internal sealed partial class AppActivation : IAppActivation, IAppActivationActi
serviceProvider.GetRequiredService<PrivateNamedPipeServer>().RunAsync().SafeForget(); serviceProvider.GetRequiredService<PrivateNamedPipeServer>().RunAsync().SafeForget();
ToastNotificationManagerCompat.OnActivated += NotificationActivate; ToastNotificationManagerCompat.OnActivated += NotificationActivate;
serviceProvider.GetRequiredService<HotKeyOptions>().RegisterAll(); using (activateSemaphore.Enter())
if (serviceProvider.GetRequiredService<AppOptions>().IsNotifyIconEnabled)
{ {
XamlWindowLifetime.ApplicationLaunchedWithNotifyIcon = true; // TODO: Introduced in 1.10.2, remove in later version
serviceProvider.GetRequiredService<App>().DispatcherShutdownMode = DispatcherShutdownMode.OnExplicitShutdown; serviceProvider.GetRequiredService<IScheduleTaskInterop>().UnregisterAllTasks();
_ = serviceProvider.GetRequiredService<NotifyIconController>();
}
serviceProvider.GetRequiredService<IScheduleTaskInterop>().UnregisterAllTasks(); if (UnsafeLocalSetting.Get(SettingKeys.Major1Minor10Revision0GuideState, GuideState.Language) < GuideState.Completed)
serviceProvider.GetRequiredService<IQuartzService>().StartAsync(default).SafeForget(); {
return;
}
serviceProvider.GetRequiredService<HotKeyOptions>().RegisterAll();
if (serviceProvider.GetRequiredService<AppOptions>().IsNotifyIconEnabled)
{
XamlWindowLifetime.ApplicationLaunchedWithNotifyIcon = true;
serviceProvider.GetRequiredService<App>().DispatcherShutdownMode = DispatcherShutdownMode.OnExplicitShutdown;
_ = serviceProvider.GetRequiredService<NotifyIconController>();
}
serviceProvider.GetRequiredService<IQuartzService>().StartAsync(default).SafeForget();
}
} }
public void Dispose() public void Dispose()
@@ -172,7 +184,6 @@ internal sealed partial class AppActivation : IAppActivation, IAppActivationActi
} }
} }
// If it's the first time launch, show the guide window anyway.
if (UnsafeLocalSetting.Get(SettingKeys.Major1Minor10Revision0GuideState, GuideState.Language) < GuideState.Completed) if (UnsafeLocalSetting.Get(SettingKeys.Major1Minor10Revision0GuideState, GuideState.Language) < GuideState.Completed)
{ {
await taskContext.SwitchToMainThreadAsync(); await taskContext.SwitchToMainThreadAsync();

View File

@@ -4,7 +4,6 @@
using Microsoft.UI.Xaml; using Microsoft.UI.Xaml;
using Snap.Hutao.Core.Windowing; using Snap.Hutao.Core.Windowing;
using Snap.Hutao.Win32.Foundation; using Snap.Hutao.Win32.Foundation;
using WinRT.Interop;
namespace Snap.Hutao.Core.LifeCycle; namespace Snap.Hutao.Core.LifeCycle;

View File

@@ -83,9 +83,10 @@ internal static class LoggerExtension
logger.LogColorized(logLevel, 0, exception, message, args); logger.LogColorized(logLevel, 0, exception, message, args);
} }
[SuppressMessage("", "CA2254")]
public static void LogColorized(this ILogger logger, LogLevel logLevel, EventId eventId, Exception? exception, LogMessage message, params LogArgument[] args) public static void LogColorized(this ILogger logger, LogLevel logLevel, EventId eventId, Exception? exception, LogMessage message, params LogArgument[] args)
{ {
string colorizedMessage = Colorize(message, args, out object?[] outArgs)!; string? colorizedMessage = Colorize(message, args, out object?[] outArgs);
logger.Log(logLevel, eventId, exception, colorizedMessage, outArgs); logger.Log(logLevel, eventId, exception, colorizedMessage, outArgs);
} }

View File

@@ -2,9 +2,7 @@
// Licensed under the MIT license. // Licensed under the MIT license.
using Microsoft.Win32.TaskScheduler; using Microsoft.Win32.TaskScheduler;
using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Windows.Storage;
namespace Snap.Hutao.Core.Shell; namespace Snap.Hutao.Core.Shell;

View File

@@ -25,7 +25,7 @@ internal class AsyncBarrier
/// <param name="participants">The number of participants.</param> /// <param name="participants">The number of participants.</param>
public AsyncBarrier(int participants) public AsyncBarrier(int participants)
{ {
Must.Range(participants >= 1, "Participants of AsyncBarrier can not be less than 1"); ArgumentOutOfRangeException.ThrowIfLessThan(participants, 1, "Participants of AsyncBarrier can not be less than 1");
participantCount = participants; participantCount = participants;
// Allocate the stack so no resizing is necessary. // Allocate the stack so no resizing is necessary.

View File

@@ -15,7 +15,7 @@ internal static class SemaphoreSlimExtension
} }
catch (ObjectDisposedException ex) catch (ObjectDisposedException ex)
{ {
ThrowHelper.OperationCanceled(SH.CoreThreadingSemaphoreSlimDisposed, ex); HutaoException.OperationCanceled(SH.CoreThreadingSemaphoreSlimDisposed, ex);
} }
return new SemaphoreSlimToken(semaphoreSlim); return new SemaphoreSlimToken(semaphoreSlim);
@@ -29,7 +29,7 @@ internal static class SemaphoreSlimExtension
} }
catch (ObjectDisposedException ex) catch (ObjectDisposedException ex)
{ {
ThrowHelper.OperationCanceled(SH.CoreThreadingSemaphoreSlimDisposed, ex); HutaoException.OperationCanceled(SH.CoreThreadingSemaphoreSlimDisposed, ex);
} }
return new SemaphoreSlimToken(semaphoreSlim); return new SemaphoreSlimToken(semaphoreSlim);

View File

@@ -1,56 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using System.Runtime.CompilerServices;
namespace Snap.Hutao.Core.Validation;
/// <summary>
/// 封装验证方法,简化微软验证
/// </summary>
[HighQuality]
[Obsolete("Use HutaoException instead")]
internal static class Must
{
/// <summary>
/// Throws an <see cref="ArgumentException"/> if a condition does not evaluate to true.
/// </summary>
/// <param name="condition">The condition to check.</param>
/// <param name="message">message</param>
/// <param name="parameterName">The name of the parameter to blame in the exception, if thrown.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Argument([DoesNotReturnIf(false)] bool condition, string? message, [CallerArgumentExpression(nameof(condition))] string? parameterName = null)
{
if (!condition)
{
throw new ArgumentException(message, parameterName);
}
}
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> if a condition does not evaluate to true.
/// </summary>
/// <param name="condition">The condition to check.</param>
/// <param name="message">message</param>
/// <param name="parameterName">The name of the parameter to blame in the exception, if thrown.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Range([DoesNotReturnIf(false)] bool condition, string? message, [CallerArgumentExpression(nameof(condition))] string? parameterName = null)
{
if (!condition)
{
throw new ArgumentOutOfRangeException(parameterName, message);
}
}
/// <summary>
/// Unconditionally throws an <see cref="NotSupportedException"/>.
/// </summary>
/// <param name="context">上下文</param>
/// <returns>Nothing. This method always throws.</returns>
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Exception NeverHappen(string? context = null)
{
throw new NotSupportedException(context);
}
}

View File

@@ -10,7 +10,7 @@ using System.Collections.Concurrent;
namespace Snap.Hutao.Core.Windowing.Backdrop; namespace Snap.Hutao.Core.Windowing.Backdrop;
// https://github.com/microsoft/microsoft-ui-xaml/blob/winui3/release/1.5-stable/controls/dev/Materials/DesktopAcrylicBackdrop/DesktopAcrylicBackdrop.cpp // https://github.com/microsoft/microsoft-ui-xaml/blob/winui3/release/1.5-stable/controls/dev/Materials/DesktopAcrylicBackdrop/DesktopAcrylicBackdrop.cpp
internal sealed class InputActiveDesktopAcrylicBackdrop : SystemBackdrop internal sealed partial class InputActiveDesktopAcrylicBackdrop : SystemBackdrop
{ {
private readonly ConcurrentDictionary<ICompositionSupportsSystemBackdrop, DesktopAcrylicController> controllers = []; private readonly ConcurrentDictionary<ICompositionSupportsSystemBackdrop, DesktopAcrylicController> controllers = [];
@@ -18,11 +18,10 @@ internal sealed class InputActiveDesktopAcrylicBackdrop : SystemBackdrop
{ {
base.OnTargetConnected(target, xamlRoot); base.OnTargetConnected(target, xamlRoot);
DesktopAcrylicController newController = new();
SystemBackdropConfiguration configuration = GetDefaultSystemBackdropConfiguration(target, xamlRoot); SystemBackdropConfiguration configuration = GetDefaultSystemBackdropConfiguration(target, xamlRoot);
configuration.IsInputActive = true; configuration.IsInputActive = true;
DesktopAcrylicController newController = new();
newController.AddSystemBackdropTarget(target); newController.AddSystemBackdropTarget(target);
newController.SetSystemBackdropConfiguration(configuration); newController.SetSystemBackdropConfiguration(configuration);
controllers.TryAdd(target, newController); controllers.TryAdd(target, newController);

View File

@@ -24,6 +24,8 @@ internal sealed class SystemBackdropDesktopWindowXamlSourceAccess : SystemBackdr
get; private set; get; private set;
} }
public SystemBackdrop? InnerBackdrop { get => innerBackdrop; }
protected override void OnTargetConnected(ICompositionSupportsSystemBackdrop target, XamlRoot xamlRoot) protected override void OnTargetConnected(ICompositionSupportsSystemBackdrop target, XamlRoot xamlRoot)
{ {
DesktopWindowXamlSource = DesktopWindowXamlSource.FromAbi(target.As<IInspectable>().ThisPtr); DesktopWindowXamlSource = DesktopWindowXamlSource.FromAbi(target.As<IInspectable>().ThisPtr);

View File

@@ -29,25 +29,26 @@ internal sealed class TransparentBackdrop : SystemBackdrop, IBackdropNeedEraseBa
internal Windows.UI.Composition.Compositor Compositor internal Windows.UI.Composition.Compositor Compositor
{ {
get get => LazyInitializer.EnsureInitialized(ref compositor, ref compositorLock, () =>
{ {
return LazyInitializer.EnsureInitialized(ref compositor, ref compositorLock, () => DispatcherQueue.EnsureSystemDispatcherQueue();
{ return new Windows.UI.Composition.Compositor();
DispatcherQueue.EnsureSystemDispatcherQueue(); });
return new Windows.UI.Composition.Compositor();
});
}
} }
protected override void OnTargetConnected(ICompositionSupportsSystemBackdrop connectedTarget, XamlRoot xamlRoot) protected override void OnTargetConnected(ICompositionSupportsSystemBackdrop target, XamlRoot xamlRoot)
{ {
base.OnTargetConnected(target, xamlRoot);
brush ??= Compositor.CreateColorBrush(tintColor); brush ??= Compositor.CreateColorBrush(tintColor);
connectedTarget.SystemBackdrop = brush; target.SystemBackdrop = brush;
} }
protected override void OnTargetDisconnected(ICompositionSupportsSystemBackdrop disconnectedTarget) protected override void OnTargetDisconnected(ICompositionSupportsSystemBackdrop target)
{ {
disconnectedTarget.SystemBackdrop = null; base.OnTargetDisconnected(target);
target.SystemBackdrop = null;
if (compositorLock is not null) if (compositorLock is not null)
{ {

View File

@@ -2,7 +2,6 @@
// Licensed under the MIT license. // Licensed under the MIT license.
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using Snap.Hutao.Core.LifeCycle;
using Snap.Hutao.Core.Setting; using Snap.Hutao.Core.Setting;
using Snap.Hutao.Model; using Snap.Hutao.Model;
using Snap.Hutao.Service.Notification; using Snap.Hutao.Service.Notification;
@@ -27,7 +26,6 @@ internal sealed class HotKeyCombination : ObservableObject
private bool registered; private bool registered;
private bool modifierHasWindows;
private bool modifierHasControl; private bool modifierHasControl;
private bool modifierHasShift; private bool modifierHasShift;
private bool modifierHasAlt; private bool modifierHasAlt;
@@ -36,6 +34,7 @@ internal sealed class HotKeyCombination : ObservableObject
private VirtualKey key; private VirtualKey key;
private bool isEnabled; private bool isEnabled;
[SuppressMessage("", "SH002")]
public HotKeyCombination(IServiceProvider serviceProvider, HWND hwnd, string settingKey, int hotKeyId, HOT_KEY_MODIFIERS defaultModifiers, VirtualKey defaultKey) public HotKeyCombination(IServiceProvider serviceProvider, HWND hwnd, string settingKey, int hotKeyId, HOT_KEY_MODIFIERS defaultModifiers, VirtualKey defaultKey)
{ {
infoBarService = serviceProvider.GetRequiredService<IInfoBarService>(); infoBarService = serviceProvider.GetRequiredService<IInfoBarService>();
@@ -52,7 +51,10 @@ internal sealed class HotKeyCombination : ObservableObject
isEnabled = LocalSetting.Get($"{settingKey}.IsEnabled", true); isEnabled = LocalSetting.Get($"{settingKey}.IsEnabled", true);
HotKeyParameter actual = LocalSettingGetHotKeyParameter(); HotKeyParameter actual = LocalSettingGetHotKeyParameter();
modifiers = actual.Modifiers;
// HOT_KEY_MODIFIERS.MOD_WIN is reversed for use by the OS.
// It should not be used by the application.
modifiers = actual.Modifiers & ~HOT_KEY_MODIFIERS.MOD_WIN;
InitializeModifiersCompositionFields(); InitializeModifiersCompositionFields();
key = actual.Key; key = actual.Key;
@@ -61,18 +63,6 @@ internal sealed class HotKeyCombination : ObservableObject
} }
#region Binding Property #region Binding Property
public bool ModifierHasWindows
{
get => modifierHasWindows;
set
{
if (SetProperty(ref modifierHasWindows, value))
{
UpdateModifiers();
}
}
}
public bool ModifierHasControl public bool ModifierHasControl
{ {
get => modifierHasControl; get => modifierHasControl;
@@ -218,11 +208,6 @@ internal sealed class HotKeyCombination : ObservableObject
{ {
StringBuilder stringBuilder = new(); StringBuilder stringBuilder = new();
if (Modifiers.HasFlag(HOT_KEY_MODIFIERS.MOD_WIN))
{
stringBuilder.Append("Win").Append(" + ");
}
if (Modifiers.HasFlag(HOT_KEY_MODIFIERS.MOD_CONTROL)) if (Modifiers.HasFlag(HOT_KEY_MODIFIERS.MOD_CONTROL))
{ {
stringBuilder.Append("Ctrl").Append(" + "); stringBuilder.Append("Ctrl").Append(" + ");
@@ -247,11 +232,6 @@ internal sealed class HotKeyCombination : ObservableObject
{ {
HOT_KEY_MODIFIERS modifiers = default; HOT_KEY_MODIFIERS modifiers = default;
if (ModifierHasWindows)
{
modifiers |= HOT_KEY_MODIFIERS.MOD_WIN;
}
if (ModifierHasControl) if (ModifierHasControl)
{ {
modifiers |= HOT_KEY_MODIFIERS.MOD_CONTROL; modifiers |= HOT_KEY_MODIFIERS.MOD_CONTROL;
@@ -272,11 +252,6 @@ internal sealed class HotKeyCombination : ObservableObject
private void InitializeModifiersCompositionFields() private void InitializeModifiersCompositionFields()
{ {
if (Modifiers.HasFlag(HOT_KEY_MODIFIERS.MOD_WIN))
{
modifierHasWindows = true;
}
if (Modifiers.HasFlag(HOT_KEY_MODIFIERS.MOD_CONTROL)) if (Modifiers.HasFlag(HOT_KEY_MODIFIERS.MOD_CONTROL))
{ {
modifierHasControl = true; modifierHasControl = true;

View File

@@ -33,7 +33,7 @@ internal sealed class HotKeyMessageWindow : IDisposable
atom = RegisterClassW(&wc); atom = RegisterClassW(&wc);
} }
ArgumentOutOfRangeException.ThrowIfEqual<ushort>(atom, 0); ArgumentOutOfRangeException.ThrowIfZero(atom);
HWND = CreateWindowExW(0, WindowClassName, WindowClassName, 0, 0, 0, 0, 0, default, default, default, default); HWND = CreateWindowExW(0, WindowClassName, WindowClassName, 0, 0, 0, 0, 0, default, default, default, default);

View File

@@ -2,8 +2,10 @@
x:Class="Snap.Hutao.Core.Windowing.NotifyIcon.NotifyIconContextMenu" x:Class="Snap.Hutao.Core.Windowing.NotifyIcon.NotifyIconContextMenu"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cw="using:CommunityToolkit.WinUI"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:shch="using:Snap.Hutao.Control.Helper"
xmlns:shcm="using:Snap.Hutao.Control.Markup" xmlns:shcm="using:Snap.Hutao.Control.Markup"
xmlns:shcwb="using:Snap.Hutao.Core.Windowing.Backdrop" xmlns:shcwb="using:Snap.Hutao.Core.Windowing.Backdrop"
xmlns:shv="using:Snap.Hutao.ViewModel" xmlns:shv="using:Snap.Hutao.ViewModel"
@@ -30,7 +32,10 @@
<RowDefinition/> <RowDefinition/>
<RowDefinition/> <RowDefinition/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<TextBlock Margin="8" Text="{Binding Title}"/> <TextBlock
Margin="8"
Style="{StaticResource BodyTextBlockStyle}"
Text="{Binding Title}"/>
<Grid Grid.Row="1" Background="{ThemeResource CardBackgroundFillColorSecondaryBrush}"> <Grid Grid.Row="1" Background="{ThemeResource CardBackgroundFillColorSecondaryBrush}">
<StackPanel <StackPanel
Margin="4,0" Margin="4,0"

View File

@@ -30,7 +30,8 @@ internal sealed class NotifyIconController : IDisposable
icon = new(iconFile.Path); icon = new(iconFile.Path);
id = Unsafe.As<byte, Guid>(ref MemoryMarshal.GetArrayDataReference(MD5.HashData(Encoding.UTF8.GetBytes(iconFile.Path)))); id = Unsafe.As<byte, Guid>(ref MemoryMarshal.GetArrayDataReference(MD5.HashData(Encoding.UTF8.GetBytes(iconFile.Path))));
xamlHostWindow = new(); xamlHostWindow = new(serviceProvider);
xamlHostWindow.MoveAndResize(default);
messageWindow = new() messageWindow = new()
{ {
@@ -46,8 +47,6 @@ internal sealed class NotifyIconController : IDisposable
messageWindow.Dispose(); messageWindow.Dispose();
NotifyIconMethods.Delete(id); NotifyIconMethods.Delete(id);
icon.Dispose(); icon.Dispose();
xamlHostWindow.Dispose();
} }
public RECT GetRect() public RECT GetRect()

View File

@@ -38,7 +38,7 @@ internal sealed class NotifyIconMessageWindow : IDisposable
atom = RegisterClassW(&wc); atom = RegisterClassW(&wc);
} }
ArgumentOutOfRangeException.ThrowIfEqual<ushort>(atom, 0); ArgumentOutOfRangeException.ThrowIfZero(atom);
// https://learn.microsoft.com/zh,cn/windows/win32/shell/taskbar#taskbar,creation,notification // https://learn.microsoft.com/zh,cn/windows/win32/shell/taskbar#taskbar,creation,notification
WM_TASKBARCREATED = RegisterWindowMessageW("TaskbarCreated"); WM_TASKBARCREATED = RegisterWindowMessageW("TaskbarCreated");
@@ -145,7 +145,9 @@ internal sealed class NotifyIconMessageWindow : IDisposable
private readonly struct LPARAM2 private readonly struct LPARAM2
{ {
#pragma warning disable CS0649
public readonly uint Low; public readonly uint Low;
public readonly uint High; public readonly uint High;
#pragma warning restore CS0649
} }
} }

View File

@@ -15,11 +15,9 @@ using static Snap.Hutao.Win32.User32;
namespace Snap.Hutao.Core.Windowing.NotifyIcon; namespace Snap.Hutao.Core.Windowing.NotifyIcon;
internal sealed class NotifyIconXamlHostWindow : Window, IDisposable, IWindowNeedEraseBackground internal sealed class NotifyIconXamlHostWindow : Window, IWindowNeedEraseBackground
{ {
private readonly XamlWindowSubclass subclass; public NotifyIconXamlHostWindow(IServiceProvider serviceProvider)
public NotifyIconXamlHostWindow()
{ {
Content = new Border(); Content = new Border();
@@ -36,10 +34,7 @@ internal sealed class NotifyIconXamlHostWindow : Window, IDisposable, IWindowNee
presenter.SetBorderAndTitleBar(false, false); presenter.SetBorderAndTitleBar(false, false);
} }
subclass = new(this); this.InitializeController(serviceProvider);
subclass.Initialize();
Activate();
} }
public void ShowFlyoutAt(FlyoutBase flyout, Point point, RECT icon) public void ShowFlyoutAt(FlyoutBase flyout, Point point, RECT icon)
@@ -53,7 +48,7 @@ internal sealed class NotifyIconXamlHostWindow : Window, IDisposable, IWindowNee
ShowWindow(hwnd, SHOW_WINDOW_CMD.SW_NORMAL); ShowWindow(hwnd, SHOW_WINDOW_CMD.SW_NORMAL);
SetForegroundWindow(hwnd); SetForegroundWindow(hwnd);
AppWindow.MoveAndResize(StructMarshal.RectInt32(icon)); MoveAndResize(icon);
flyout.ShowAt(Content, new() flyout.ShowAt(Content, new()
{ {
Placement = FlyoutPlacementMode.Auto, Placement = FlyoutPlacementMode.Auto,
@@ -61,8 +56,8 @@ internal sealed class NotifyIconXamlHostWindow : Window, IDisposable, IWindowNee
}); });
} }
public void Dispose() public void MoveAndResize(RECT icon)
{ {
subclass.Dispose(); AppWindow.MoveAndResize(StructMarshal.RectInt32(icon));
} }
} }

View File

@@ -76,13 +76,17 @@ internal static class WindowExtension
ShowWindow(GetWindowHandle(window), SHOW_WINDOW_CMD.SW_HIDE); ShowWindow(GetWindowHandle(window), SHOW_WINDOW_CMD.SW_HIDE);
} }
public static void SetLayered(this Window window) public static void SetLayered(this Window window, bool full = true)
{ {
HWND hwnd = (HWND)WindowNative.GetWindowHandle(window); HWND hwnd = (HWND)WindowNative.GetWindowHandle(window);
nint style = GetWindowLongPtrW(hwnd, WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE); nint style = GetWindowLongPtrW(hwnd, WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE);
style |= (nint)WINDOW_EX_STYLE.WS_EX_LAYERED; style |= (nint)WINDOW_EX_STYLE.WS_EX_LAYERED;
SetWindowLongPtrW(hwnd, WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE, style); SetWindowLongPtrW(hwnd, WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE, style);
SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 0, LAYERED_WINDOW_ATTRIBUTES_FLAGS.LWA_COLORKEY | LAYERED_WINDOW_ATTRIBUTES_FLAGS.LWA_ALPHA);
if (full)
{
SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 0, LAYERED_WINDOW_ATTRIBUTES_FLAGS.LWA_COLORKEY | LAYERED_WINDOW_ATTRIBUTES_FLAGS.LWA_ALPHA);
}
} }
public static unsafe void BringToForeground(this Window window) public static unsafe void BringToForeground(this Window window)

View File

@@ -104,9 +104,7 @@ internal sealed class XamlWindowController
args.Handled = true; args.Handled = true;
window.Hide(); window.Hide();
RECT iconRect = serviceProvider.GetRequiredService<NotifyIconController>().GetRect(); if (!IsNotifyIconVisible())
RECT primaryRect = StructMarshal.RECT(DisplayArea.Primary.OuterBounds);
if (!IntersectRect(out _, in primaryRect, in iconRect))
{ {
new ToastContentBuilder() new ToastContentBuilder()
.AddText(SH.CoreWindowingNotifyIconPromotedHint) .AddText(SH.CoreWindowingNotifyIconPromotedHint)
@@ -133,6 +131,28 @@ internal sealed class XamlWindowController
} }
} }
private unsafe bool IsNotifyIconVisible()
{
RECT iconRect = serviceProvider.GetRequiredService<NotifyIconController>().GetRect();
if (UniversalApiContract.IsPresent(WindowsVersion.Windows11))
{
RECT primaryRect = StructMarshal.RECT(DisplayArea.Primary.OuterBounds);
return IntersectRect(out _, in primaryRect, in iconRect);
}
HWND shellTrayWnd = FindWindowExW(default, default, "Shell_TrayWnd", default);
HWND trayNotifyWnd = FindWindowExW(shellTrayWnd, default, "TrayNotifyWnd", default);
HWND button = FindWindowExW(trayNotifyWnd, default, "Button", default);
if (GetWindowRect(button, out RECT buttonRect))
{
return !EqualRect(in buttonRect, in iconRect);
}
return false;
}
#region SystemBackdrop & ElementTheme #region SystemBackdrop & ElementTheme
private void OnOptionsPropertyChanged(object? sender, PropertyChangedEventArgs e) private void OnOptionsPropertyChanged(object? sender, PropertyChangedEventArgs e)

View File

@@ -12,6 +12,7 @@ internal sealed class XamlWindowNonRudeHWND : IDisposable
private const string NonRudeHWND = "NonRudeHWND"; private const string NonRudeHWND = "NonRudeHWND";
private readonly HWND hwnd; private readonly HWND hwnd;
[SuppressMessage("", "SH002")]
public XamlWindowNonRudeHWND(HWND hwnd) public XamlWindowNonRudeHWND(HWND hwnd)
{ {
this.hwnd = hwnd; this.hwnd = hwnd;

View File

@@ -5,12 +5,10 @@ using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml; using Microsoft.UI.Xaml;
using Snap.Hutao.Core.Windowing.Abstraction; using Snap.Hutao.Core.Windowing.Abstraction;
using Snap.Hutao.Core.Windowing.Backdrop; using Snap.Hutao.Core.Windowing.Backdrop;
using Snap.Hutao.Core.Windowing.NotifyIcon;
using Snap.Hutao.Win32; using Snap.Hutao.Win32;
using Snap.Hutao.Win32.Foundation; using Snap.Hutao.Win32.Foundation;
using Snap.Hutao.Win32.UI.Shell; using Snap.Hutao.Win32.UI.Shell;
using Snap.Hutao.Win32.UI.WindowsAndMessaging; using Snap.Hutao.Win32.UI.WindowsAndMessaging;
using System.Diagnostics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using static Snap.Hutao.Win32.ComCtl32; using static Snap.Hutao.Win32.ComCtl32;
@@ -87,7 +85,9 @@ internal sealed class XamlWindowSubclass : IDisposable
case WM_ERASEBKGND: case WM_ERASEBKGND:
{ {
if (state.window is IWindowNeedEraseBackground || state.window.SystemBackdrop is IBackdropNeedEraseBackground) if (state.window is IWindowNeedEraseBackground ||
state.window.SystemBackdrop is IBackdropNeedEraseBackground ||
state.window.SystemBackdrop is SystemBackdropDesktopWindowXamlSourceAccess { InnerBackdrop: IBackdropNeedEraseBackground })
{ {
return (LRESULT)(int)BOOL.TRUE; return (LRESULT)(int)BOOL.TRUE;
} }

View File

@@ -15,7 +15,7 @@ internal sealed partial class ProgressFactory : IProgressFactory
{ {
if (taskContext is not ITaskContextUnsafe @unsafe) if (taskContext is not ITaskContextUnsafe @unsafe)
{ {
throw ThrowHelper.NotSupported(); throw HutaoException.NotSupported();
} }
return new DispatcherQueueProgress<T>(handler, @unsafe.DispatcherQueue); return new DispatcherQueueProgress<T>(handler, @unsafe.DispatcherQueue);

View File

@@ -14,7 +14,6 @@ global using Snap.Hutao.Core.Annotation;
global using Snap.Hutao.Core.DependencyInjection; global using Snap.Hutao.Core.DependencyInjection;
global using Snap.Hutao.Core.DependencyInjection.Annotation; global using Snap.Hutao.Core.DependencyInjection.Annotation;
global using Snap.Hutao.Core.Threading; global using Snap.Hutao.Core.Threading;
global using Snap.Hutao.Core.Validation;
global using Snap.Hutao.Extension; global using Snap.Hutao.Extension;
global using Snap.Hutao.Resource.Localization; global using Snap.Hutao.Resource.Localization;

View File

@@ -3,6 +3,7 @@
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using Snap.Hutao.Core.Abstraction; using Snap.Hutao.Core.Abstraction;
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Core.Setting; using Snap.Hutao.Core.Setting;
using Snap.Hutao.Model.Intrinsic; using Snap.Hutao.Model.Intrinsic;
using Snap.Hutao.Model.Metadata.Avatar; using Snap.Hutao.Model.Metadata.Avatar;
@@ -97,7 +98,7 @@ internal sealed class CalculableSkill
SkillType.A => SettingKeys.CultivationAvatarSkillACurrent, SkillType.A => SettingKeys.CultivationAvatarSkillACurrent,
SkillType.E => SettingKeys.CultivationAvatarSkillECurrent, SkillType.E => SettingKeys.CultivationAvatarSkillECurrent,
SkillType.Q => SettingKeys.CultivationAvatarSkillQCurrent, SkillType.Q => SettingKeys.CultivationAvatarSkillQCurrent,
_ => throw Must.NeverHappen(), _ => throw HutaoException.NotSupported(),
}; };
} }
@@ -108,7 +109,7 @@ internal sealed class CalculableSkill
SkillType.A => SettingKeys.CultivationAvatarSkillATarget, SkillType.A => SettingKeys.CultivationAvatarSkillATarget,
SkillType.E => SettingKeys.CultivationAvatarSkillETarget, SkillType.E => SettingKeys.CultivationAvatarSkillETarget,
SkillType.Q => SettingKeys.CultivationAvatarSkillQTarget, SkillType.Q => SettingKeys.CultivationAvatarSkillQTarget,
_ => throw Must.NeverHappen(), _ => throw HutaoException.NotSupported(),
}; };
} }
} }

View File

@@ -2,6 +2,7 @@
// Licensed under the MIT license. // Licensed under the MIT license.
using Snap.Hutao.Core.Abstraction; using Snap.Hutao.Core.Abstraction;
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Model.Entity.Primitive; using Snap.Hutao.Model.Entity.Primitive;
using Snap.Hutao.Service.Cultivation; using Snap.Hutao.Service.Cultivation;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
@@ -63,7 +64,7 @@ internal sealed class CultivateEntryLevelInformation : IMappingFrom<CultivateEnt
WeaponLevelFrom = source.WeaponLevelFrom, WeaponLevelFrom = source.WeaponLevelFrom,
WeaponLevelTo = source.WeaponLevelTo, WeaponLevelTo = source.WeaponLevelTo,
}, },
_ => throw Must.NeverHappen($"不支持的养成类型{type}"), _ => throw HutaoException.NotSupported($"不支持的养成类型{type}"),
}; };
} }
} }

View File

@@ -4,7 +4,6 @@
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using Snap.Hutao.Core.Abstraction; using Snap.Hutao.Core.Abstraction;
using Snap.Hutao.Model.Entity.Abstraction; using Snap.Hutao.Model.Entity.Abstraction;
using Snap.Hutao.Model.Primitive;
using Snap.Hutao.ViewModel.DailyNote; using Snap.Hutao.ViewModel.DailyNote;
using Snap.Hutao.ViewModel.User; using Snap.Hutao.ViewModel.User;
using Snap.Hutao.Web.Hoyolab.Takumi.Binding; using Snap.Hutao.Web.Hoyolab.Takumi.Binding;

View File

@@ -20,7 +20,7 @@ internal sealed class AppDbContextDesignTimeFactory : IDesignTimeDbContextFactor
string userdataDbName = @"D:\Hutao\Userdata.db"; string userdataDbName = @"D:\Hutao\Userdata.db";
return AppDbContext.Create(default!, $"Data Source={userdataDbName}"); return AppDbContext.Create(default!, $"Data Source={userdataDbName}");
#else #else
throw Must.NeverHappen(); throw Core.ExceptionService.HutaoException.NotSupported();
#endif #endif
} }
} }

View File

@@ -11,25 +11,25 @@ namespace Snap.Hutao.Model.Intrinsic.Frozen;
[HighQuality] [HighQuality]
internal static class IntrinsicFrozen internal static class IntrinsicFrozen
{ {
public static FrozenSet<string> AssociationTypes { get; } = Enum.GetValues<AssociationType>().Select(e => e.GetLocalizedDescriptionOrDefault()).OfType<string>().ToFrozenSet(); public static FrozenSet<string> AssociationTypes { get; } = NamesFromEnum<AssociationType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<NameValue<AssociationType>> AssociationTypeNameValues { get; } = Enum.GetValues<AssociationType>().Select(e => new NameValue<AssociationType>(e.GetLocalizedDescriptionOrDefault()!, e)).Where(nv => !string.IsNullOrEmpty(nv.Name)).ToFrozenSet(); public static FrozenSet<NameValue<AssociationType>> AssociationTypeNameValues { get; } = NameValuesFromEnum<AssociationType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<string> WeaponTypes { get; } = Enum.GetValues<WeaponType>().Select(e => e.GetLocalizedDescriptionOrDefault()).OfType<string>().ToFrozenSet(); public static FrozenSet<string> WeaponTypes { get; } = NamesFromEnum<WeaponType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<NameValue<WeaponType>> WeaponTypeNameValues { get; } = Enum.GetValues<WeaponType>().Select(e => new NameValue<WeaponType>(e.GetLocalizedDescriptionOrDefault()!, e)).Where(nv => !string.IsNullOrEmpty(nv.Name)).ToFrozenSet(); public static FrozenSet<NameValue<WeaponType>> WeaponTypeNameValues { get; } = NameValuesFromEnum<WeaponType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<string> ItemQualities { get; } = Enum.GetValues<QualityType>().Select(e => e.GetLocalizedDescriptionOrDefault()).OfType<string>().ToFrozenSet(); public static FrozenSet<string> ItemQualities { get; } = NamesFromEnum<QualityType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<NameValue<QualityType>> ItemQualityNameValues { get; } = Enum.GetValues<QualityType>().Select(e => new NameValue<QualityType>(e.GetLocalizedDescriptionOrDefault()!, e)).Where(nv => !string.IsNullOrEmpty(nv.Name)).ToFrozenSet(); public static FrozenSet<NameValue<QualityType>> ItemQualityNameValues { get; } = NameValuesFromEnum<QualityType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<string> BodyTypes { get; } = Enum.GetValues<BodyType>().Select(e => e.GetLocalizedDescriptionOrDefault()).OfType<string>().ToFrozenSet(); public static FrozenSet<string> BodyTypes { get; } = NamesFromEnum<BodyType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<NameValue<BodyType>> BodyTypeNameValues { get; } = Enum.GetValues<BodyType>().Select(e => new NameValue<BodyType>(e.GetLocalizedDescriptionOrDefault()!, e)).Where(nv => !string.IsNullOrEmpty(nv.Name)).ToFrozenSet(); public static FrozenSet<NameValue<BodyType>> BodyTypeNameValues { get; } = NameValuesFromEnum<BodyType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<string> FightProperties { get; } = Enum.GetValues<FightProperty>().Select(e => e.GetLocalizedDescriptionOrDefault()).OfType<string>().ToFrozenSet(); public static FrozenSet<string> FightProperties { get; } = NamesFromEnum<FightProperty>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<NameValue<FightProperty>> FightPropertyNameValues { get; } = Enum.GetValues<FightProperty>().Select(e => new NameValue<FightProperty>(e.GetLocalizedDescriptionOrDefault()!, e)).Where(nv => !string.IsNullOrEmpty(nv.Name)).ToFrozenSet(); public static FrozenSet<NameValue<FightProperty>> FightPropertyNameValues { get; } = NameValuesFromEnum<FightProperty>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<string> ElementNames { get; } = FrozenSet.ToFrozenSet( public static FrozenSet<string> ElementNames { get; } = FrozenSet.ToFrozenSet(
[ [
@@ -63,4 +63,50 @@ internal static class IntrinsicFrozen
SH.ModelMetadataMaterialWeaponEnhancementMaterial, SH.ModelMetadataMaterialWeaponEnhancementMaterial,
SH.ModelMetadataMaterialWeaponAscensionMaterial, SH.ModelMetadataMaterialWeaponAscensionMaterial,
]); ]);
private static FrozenSet<string> NamesFromEnum<TEnum>(Func<TEnum, string?> selector)
where TEnum : struct, Enum
{
return NamesFromEnumValues(Enum.GetValues<TEnum>(), selector);
}
private static FrozenSet<string> NamesFromEnumValues<TEnum>(TEnum[] values, Func<TEnum, string?> selector)
{
return NotNull(values, selector).ToFrozenSet();
static IEnumerable<string> NotNull(TEnum[] values, Func<TEnum, string?> selector)
{
foreach (TEnum value in values)
{
string? name = selector(value);
if (!string.IsNullOrEmpty(name))
{
yield return name;
}
}
}
}
private static FrozenSet<NameValue<TEnum>> NameValuesFromEnum<TEnum>(Func<TEnum, string?> selector)
where TEnum : struct, Enum
{
return NameValuesFromEnumValues(Enum.GetValues<TEnum>(), selector);
}
private static FrozenSet<NameValue<TEnum>> NameValuesFromEnumValues<TEnum>(TEnum[] values, Func<TEnum, string?> selector)
{
return NotNull(values, selector).ToFrozenSet();
static IEnumerable<NameValue<TEnum>> NotNull(TEnum[] values, Func<TEnum, string?> selector)
{
foreach (TEnum value in values)
{
string? name = selector(value);
if (!string.IsNullOrEmpty(name))
{
yield return new(name, value);
}
}
}
}
} }

View File

@@ -2,6 +2,7 @@
// Licensed under the MIT license. // Licensed under the MIT license.
using Snap.Hutao.Control; using Snap.Hutao.Control;
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Model.Intrinsic; using Snap.Hutao.Model.Intrinsic;
namespace Snap.Hutao.Model.Metadata.Converter; namespace Snap.Hutao.Model.Metadata.Converter;
@@ -21,7 +22,7 @@ internal sealed class AssociationTypeIconConverter : ValueConverter<AssociationT
AssociationType.ASSOC_TYPE_FONTAINE => "Fontaine", AssociationType.ASSOC_TYPE_FONTAINE => "Fontaine",
AssociationType.ASSOC_TYPE_NATLAN => default, AssociationType.ASSOC_TYPE_NATLAN => default,
AssociationType.ASSOC_TYPE_SNEZHNAYA => default, AssociationType.ASSOC_TYPE_SNEZHNAYA => default,
_ => throw Must.NeverHappen(), _ => throw HutaoException.NotSupported(),
}; };
return association is null return association is null

View File

@@ -68,7 +68,7 @@ internal sealed partial class DescriptionsParametersDescriptor : ValueConverter<
} }
else else
{ {
ThrowHelper.InvalidOperation($"ParameterFormat failed, value: `{desc}`", default); HutaoException.InvalidOperation($"ParameterFormat failed, value: `{desc}`", default);
} }
} }

View File

@@ -2,6 +2,7 @@
// Licensed under the MIT license. // Licensed under the MIT license.
using Snap.Hutao.Control; using Snap.Hutao.Control;
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Model.Intrinsic; using Snap.Hutao.Model.Intrinsic;
using System.Collections.Frozen; using System.Collections.Frozen;
@@ -41,7 +42,7 @@ internal sealed class WeaponTypeIconConverter : ValueConverter<WeaponType, Uri>
WeaponType.WEAPON_POLE => "03", WeaponType.WEAPON_POLE => "03",
WeaponType.WEAPON_CLAYMORE => "04", WeaponType.WEAPON_CLAYMORE => "04",
WeaponType.WEAPON_CATALYST => "Catalyst_MD", WeaponType.WEAPON_CATALYST => "Catalyst_MD",
_ => throw Must.NeverHappen(), _ => throw HutaoException.NotSupported(),
}; };
return Web.HutaoEndpoints.StaticRaw("Skill", $"Skill_A_{weapon}.png").ToUri(); return Web.HutaoEndpoints.StaticRaw("Skill", $"Skill_A_{weapon}.png").ToUri();

View File

@@ -13,7 +13,7 @@
<Identity <Identity
Name="60568DGPStudio.SnapHutao" Name="60568DGPStudio.SnapHutao"
Publisher="CN=35C8E923-85DF-49A7-9172-B39DC6312C52" Publisher="CN=35C8E923-85DF-49A7-9172-B39DC6312C52"
Version="1.10.1.0" /> Version="1.10.2.0" />
<Properties> <Properties>
<DisplayName>Snap Hutao</DisplayName> <DisplayName>Snap Hutao</DisplayName>

View File

@@ -13,7 +13,7 @@
<Identity <Identity
Name="60568DGPStudio.SnapHutaoDev" Name="60568DGPStudio.SnapHutaoDev"
Publisher="CN=35C8E923-85DF-49A7-9172-B39DC6312C52" Publisher="CN=35C8E923-85DF-49A7-9172-B39DC6312C52"
Version="1.10.1.0" /> Version="1.10.2.0" />
<Properties> <Properties>
<DisplayName>Snap Hutao Dev</DisplayName> <DisplayName>Snap Hutao Dev</DisplayName>

View File

@@ -2,13 +2,13 @@
// Licensed under the MIT license. // Licensed under the MIT license.
using Microsoft.UI.Xaml; using Microsoft.UI.Xaml;
using Snap.Hutao.Core.Windowing.NotifyIcon;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using WinRT; using WinRT;
// Visible to test project. // Visible to test project.
[assembly: InternalsVisibleTo("Snap.Hutao.Test")] [assembly: InternalsVisibleTo("Snap.Hutao.Test")]
[assembly: DisableRuntimeMarshalling]
namespace Snap.Hutao; namespace Snap.Hutao;

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

View File

@@ -1568,6 +1568,12 @@
<data name="ViewModelCultivationProjectInvalidName" xml:space="preserve"> <data name="ViewModelCultivationProjectInvalidName" xml:space="preserve">
<value>不能添加名称无效的计划</value> <value>不能添加名称无效的计划</value>
</data> </data>
<data name="ViewModelCultivationRemoveProjectContent" xml:space="preserve">
<value>此操作不可逆,此计划的养成物品与背包材料将会丢失</value>
</data>
<data name="ViewModelCultivationRemoveProjectTitle" xml:space="preserve">
<value>确认要删除当前计划吗?</value>
</data>
<data name="ViewModelDailyNoteConfigWebhookUrlComplete" xml:space="preserve"> <data name="ViewModelDailyNoteConfigWebhookUrlComplete" xml:space="preserve">
<value>实时便笺 Webhook Url 配置成功</value> <value>实时便笺 Webhook Url 配置成功</value>
</data> </data>
@@ -1958,6 +1964,9 @@
<data name="ViewPageDailyNoteNotificationSetting" xml:space="preserve"> <data name="ViewPageDailyNoteNotificationSetting" xml:space="preserve">
<value>通知设置</value> <value>通知设置</value>
</data> </data>
<data name="ViewPageDailyNoteNotificationUnavailableHint" xml:space="preserve">
<value>胡桃的通知权限已被关闭</value>
</data>
<data name="ViewPageDailyNoteRefresh" xml:space="preserve"> <data name="ViewPageDailyNoteRefresh" xml:space="preserve">
<value>立即刷新</value> <value>立即刷新</value>
</data> </data>
@@ -1988,6 +1997,9 @@
<data name="ViewPageDailyNoteSettingRefreshHeader" xml:space="preserve"> <data name="ViewPageDailyNoteSettingRefreshHeader" xml:space="preserve">
<value>刷新</value> <value>刷新</value>
</data> </data>
<data name="ViewPageDailyNoteSettingRefreshNotifyIconDisabledHint" xml:space="preserve">
<value>未启用通知区域图标,关闭窗口后自动刷新将不会执行</value>
</data>
<data name="ViewPageDailyNoteSlientModeDescription" xml:space="preserve"> <data name="ViewPageDailyNoteSlientModeDescription" xml:space="preserve">
<value>在我游玩原神时不通知我</value> <value>在我游玩原神时不通知我</value>
</data> </data>
@@ -3024,7 +3036,7 @@
<value>武器资料</value> <value>武器资料</value>
</data> </data>
<data name="WebAnnouncementMatchPermanentActivityTime" xml:space="preserve"> <data name="WebAnnouncementMatchPermanentActivityTime" xml:space="preserve">
<value>(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)后永久开放</value> <value>(?:(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)|&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;)后永久开放</value>
</data> </data>
<data name="WebAnnouncementMatchPersistentActivityTime" xml:space="preserve"> <data name="WebAnnouncementMatchPersistentActivityTime" xml:space="preserve">
<value>〓活动时间〓.*?(\d\.\d)版本期间持续开放</value> <value>〓活动时间〓.*?(\d\.\d)版本期间持续开放</value>
@@ -3245,6 +3257,9 @@
<data name="WebResponseRequestExceptionFormat" xml:space="preserve"> <data name="WebResponseRequestExceptionFormat" xml:space="preserve">
<value>[{0}] 中的 [{1}] 网络请求异常,请稍后再试</value> <value>[{0}] 中的 [{1}] 网络请求异常,请稍后再试</value>
</data> </data>
<data name="WebResponseSignInErrorHint" xml:space="preserve">
<value>登录失败,请前往 HoYoLAB 初始化账号,原始消息:{0}</value>
</data>
<data name="WindowIdentifyMonitorHeader" xml:space="preserve"> <data name="WindowIdentifyMonitorHeader" xml:space="preserve">
<value>显示器编号</value> <value>显示器编号</value>
</data> </data>

View File

@@ -152,6 +152,8 @@ internal sealed partial class AnnouncementService : IAnnouncementService
announcement.StartTime = versionStartTime; announcement.StartTime = versionStartTime;
continue; continue;
} }
announcement.StartTime = UnsafeDateTimeOffset.ParseDateTime(permanent.Groups[2].ValueSpan, offset);
} }
if (AnnouncementRegex.PersistentActivityAfterUpdateTimeRegex.Match(announcement.Content) is { Success: true } persistent) if (AnnouncementRegex.PersistentActivityAfterUpdateTimeRegex.Match(announcement.Content) is { Success: true } persistent)

View File

@@ -32,7 +32,7 @@ internal sealed partial class AvatarInfoDbBulkOperation
public async ValueTask<List<EntityAvatarInfo>> UpdateDbAvatarInfosByShowcaseAsync(string uid, IEnumerable<EnkaAvatarInfo> webInfos, CancellationToken token) public async ValueTask<List<EntityAvatarInfo>> UpdateDbAvatarInfosByShowcaseAsync(string uid, IEnumerable<EnkaAvatarInfo> webInfos, CancellationToken token)
{ {
List<EntityAvatarInfo> dbInfos = await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid).ConfigureAwait(false); List<EntityAvatarInfo> dbInfos = await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid, token).ConfigureAwait(false);
EnsureItemsAvatarIdUnique(ref dbInfos, uid, out Dictionary<AvatarId, EntityAvatarInfo> dbInfoMap); EnsureItemsAvatarIdUnique(ref dbInfos, uid, out Dictionary<AvatarId, EntityAvatarInfo> dbInfoMap);
using (IServiceScope scope = serviceProvider.CreateScope()) using (IServiceScope scope = serviceProvider.CreateScope())
@@ -50,14 +50,14 @@ internal sealed partial class AvatarInfoDbBulkOperation
AddOrUpdateAvatarInfo(entity, uid, appDbContext, webInfo); AddOrUpdateAvatarInfo(entity, uid, appDbContext, webInfo);
} }
return await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid).ConfigureAwait(false); return await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid, token).ConfigureAwait(false);
} }
} }
public async ValueTask<List<EntityAvatarInfo>> UpdateDbAvatarInfosByGameRecordCharacterAsync(UserAndUid userAndUid, CancellationToken token) public async ValueTask<List<EntityAvatarInfo>> UpdateDbAvatarInfosByGameRecordCharacterAsync(UserAndUid userAndUid, CancellationToken token)
{ {
string uid = userAndUid.Uid.Value; string uid = userAndUid.Uid.Value;
List<EntityAvatarInfo> dbInfos = await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid).ConfigureAwait(false); List<EntityAvatarInfo> dbInfos = await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid, token).ConfigureAwait(false);
EnsureItemsAvatarIdUnique(ref dbInfos, uid, out Dictionary<AvatarId, EntityAvatarInfo> dbInfoMap); EnsureItemsAvatarIdUnique(ref dbInfos, uid, out Dictionary<AvatarId, EntityAvatarInfo> dbInfoMap);
using (IServiceScope scope = serviceProvider.CreateScope()) using (IServiceScope scope = serviceProvider.CreateScope())
@@ -103,14 +103,14 @@ internal sealed partial class AvatarInfoDbBulkOperation
} }
Return: Return:
return await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid).ConfigureAwait(false); return await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid, token).ConfigureAwait(false);
} }
public async ValueTask<List<EntityAvatarInfo>> UpdateDbAvatarInfosByCalculateAvatarDetailAsync(UserAndUid userAndUid, CancellationToken token) public async ValueTask<List<EntityAvatarInfo>> UpdateDbAvatarInfosByCalculateAvatarDetailAsync(UserAndUid userAndUid, CancellationToken token)
{ {
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
string uid = userAndUid.Uid.Value; string uid = userAndUid.Uid.Value;
List<EntityAvatarInfo> dbInfos = await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid).ConfigureAwait(false); List<EntityAvatarInfo> dbInfos = await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid, token).ConfigureAwait(false);
EnsureItemsAvatarIdUnique(ref dbInfos, uid, out Dictionary<AvatarId, EntityAvatarInfo> dbInfoMap); EnsureItemsAvatarIdUnique(ref dbInfos, uid, out Dictionary<AvatarId, EntityAvatarInfo> dbInfoMap);
using (IServiceScope scope = serviceProvider.CreateScope()) using (IServiceScope scope = serviceProvider.CreateScope())
@@ -146,7 +146,7 @@ internal sealed partial class AvatarInfoDbBulkOperation
} }
} }
return await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid).ConfigureAwait(false); return await avatarInfoDbService.GetAvatarInfoListByUidAsync(uid, token).ConfigureAwait(false);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]

View File

@@ -32,6 +32,7 @@ internal static class AvatarViewBuilderExtension
return builder; return builder;
} }
[SuppressMessage("", "SH002")]
public static TBuilder SetCalculatorRefreshTimeFormat<TBuilder>(this TBuilder builder, DateTimeOffset refreshTime, Func<object?, string> format, string defaultValue) public static TBuilder SetCalculatorRefreshTimeFormat<TBuilder>(this TBuilder builder, DateTimeOffset refreshTime, Func<object?, string> format, string defaultValue)
where TBuilder : IAvatarViewBuilder where TBuilder : IAvatarViewBuilder
{ {
@@ -116,6 +117,7 @@ internal static class AvatarViewBuilderExtension
return builder.Configure(b => b.View.FetterLevel = level); return builder.Configure(b => b.View.FetterLevel = level);
} }
[SuppressMessage("", "SH002")]
public static TBuilder SetGameRecordRefreshTimeFormat<TBuilder>(this TBuilder builder, DateTimeOffset refreshTime, Func<object?, string> format, string defaultValue) public static TBuilder SetGameRecordRefreshTimeFormat<TBuilder>(this TBuilder builder, DateTimeOffset refreshTime, Func<object?, string> format, string defaultValue)
where TBuilder : IAvatarViewBuilder where TBuilder : IAvatarViewBuilder
{ {
@@ -128,6 +130,7 @@ internal static class AvatarViewBuilderExtension
return builder.Configure(b => b.View.GameRecordRefreshTimeFormat = gameRecordRefreshTimeFormat); return builder.Configure(b => b.View.GameRecordRefreshTimeFormat = gameRecordRefreshTimeFormat);
} }
[SuppressMessage("", "SH002")]
public static TBuilder SetId<TBuilder>(this TBuilder builder, AvatarId id) public static TBuilder SetId<TBuilder>(this TBuilder builder, AvatarId id)
where TBuilder : IAvatarViewBuilder where TBuilder : IAvatarViewBuilder
{ {
@@ -175,6 +178,7 @@ internal static class AvatarViewBuilderExtension
return builder.Configure(b => b.View.Reliquaries = reliquaries); return builder.Configure(b => b.View.Reliquaries = reliquaries);
} }
[SuppressMessage("", "SH002")]
public static TBuilder SetShowcaseRefreshTimeFormat<TBuilder>(this TBuilder builder, DateTimeOffset refreshTime, Func<object?, string> format, string defaultValue) public static TBuilder SetShowcaseRefreshTimeFormat<TBuilder>(this TBuilder builder, DateTimeOffset refreshTime, Func<object?, string> format, string defaultValue)
where TBuilder : IAvatarViewBuilder where TBuilder : IAvatarViewBuilder
{ {

View File

@@ -43,6 +43,7 @@ internal static class WeaponViewBuilderExtension
return builder.SetIcon<TBuilder, WeaponView>(icon); return builder.SetIcon<TBuilder, WeaponView>(icon);
} }
[SuppressMessage("", "SH002")]
public static TBuilder SetId<TBuilder>(this TBuilder builder, WeaponId id) public static TBuilder SetId<TBuilder>(this TBuilder builder, WeaponId id)
where TBuilder : IWeaponViewBuilder where TBuilder : IWeaponViewBuilder
{ {

View File

@@ -12,11 +12,13 @@ internal sealed class MaterialIdComparer : IComparer<MaterialId>
public static MaterialIdComparer Shared { get => LazyInitializer.EnsureInitialized(ref shared, ref syncRoot, () => new()); } public static MaterialIdComparer Shared { get => LazyInitializer.EnsureInitialized(ref shared, ref syncRoot, () => new()); }
[SuppressMessage("", "SH002")]
public int Compare(MaterialId x, MaterialId y) public int Compare(MaterialId x, MaterialId y)
{ {
return Transform(x).CompareTo(Transform(y)); return Transform(x).CompareTo(Transform(y));
} }
[SuppressMessage("", "SH002")]
private static uint Transform(MaterialId value) private static uint Transform(MaterialId value)
{ {
return value.Value switch return value.Value switch

View File

@@ -48,29 +48,9 @@ internal sealed partial class DailyNoteNotificationOperation
return; return;
} }
string? attribution = SH.ServiceDailyNoteNotifierAttribution; string attribution = entry.UserGameRole is not null
? entry.UserGameRole.ToString()
if (entry.UserGameRole is not null) : await GetUserUidAsync(entry).ConfigureAwait(false);
{
attribution = entry.UserGameRole.ToString();
}
else
{
Response<ListWrapper<UserGameRole>> rolesResponse;
using (IServiceScope scope = serviceScopeFactory.CreateScope())
{
BindingClient bindingClient = scope.ServiceProvider.GetRequiredService<BindingClient>();
rolesResponse = await bindingClient
.GetUserGameRolesOverseaAwareAsync(entry.User)
.ConfigureAwait(false);
}
if (rolesResponse.IsOk())
{
List<UserGameRole> roles = rolesResponse.Data.List;
attribution = roles.SingleOrDefault(r => r.GameUid == entry.Uid)?.ToString() ?? ToastAttributionUnknown;
}
}
ToastContentBuilder builder = new ToastContentBuilder() ToastContentBuilder builder = new ToastContentBuilder()
.AddHeader(ToastHeaderIdArgument, SH.ServiceDailyNoteNotifierTitle, ToastHeaderIdArgument) .AddHeader(ToastHeaderIdArgument, SH.ServiceDailyNoteNotifierTitle, ToastHeaderIdArgument)
@@ -130,4 +110,24 @@ internal sealed partial class DailyNoteNotificationOperation
// Prevent notify when we are in game && silent mode. // Prevent notify when we are in game && silent mode.
return options.IsSilentWhenPlayingGame && gameService.IsGameRunning(); return options.IsSilentWhenPlayingGame && gameService.IsGameRunning();
} }
private async ValueTask<string> GetUserUidAsync(DailyNoteEntry entry)
{
Response<ListWrapper<UserGameRole>> rolesResponse;
using (IServiceScope scope = serviceScopeFactory.CreateScope())
{
BindingClient bindingClient = scope.ServiceProvider.GetRequiredService<BindingClient>();
rolesResponse = await bindingClient
.GetUserGameRolesOverseaAwareAsync(entry.User)
.ConfigureAwait(false);
}
if (rolesResponse.IsOk())
{
List<UserGameRole> roles = rolesResponse.Data.List;
return roles.SingleOrDefault(r => r.GameUid == entry.Uid)?.ToString() ?? ToastAttributionUnknown;
}
return SH.ServiceDailyNoteNotifierAttribution;
}
} }

View File

@@ -54,6 +54,7 @@ internal sealed partial class DailyNoteService : IDailyNoteService, IRecipient<U
DailyNoteEntry newEntry = DailyNoteEntry.From(userAndUid); DailyNoteEntry newEntry = DailyNoteEntry.From(userAndUid);
Web.Response.Response<WebDailyNote> dailyNoteResponse; Web.Response.Response<WebDailyNote> dailyNoteResponse;
DailyNoteMetadataContext context;
using (IServiceScope scope = serviceProvider.CreateScope()) using (IServiceScope scope = serviceProvider.CreateScope())
{ {
IGameRecordClient gameRecordClient = scope.ServiceProvider IGameRecordClient gameRecordClient = scope.ServiceProvider
@@ -63,6 +64,8 @@ internal sealed partial class DailyNoteService : IDailyNoteService, IRecipient<U
dailyNoteResponse = await gameRecordClient dailyNoteResponse = await gameRecordClient
.GetDailyNoteAsync(userAndUid, token) .GetDailyNoteAsync(userAndUid, token)
.ConfigureAwait(false); .ConfigureAwait(false);
context = await scope.GetRequiredService<IMetadataService>().GetContextAsync<DailyNoteMetadataContext>(token).ConfigureAwait(false);
} }
if (dailyNoteResponse.IsOk()) if (dailyNoteResponse.IsOk())
@@ -71,6 +74,7 @@ internal sealed partial class DailyNoteService : IDailyNoteService, IRecipient<U
} }
newEntry.UserGameRole = userService.GetUserGameRoleByUid(roleUid); newEntry.UserGameRole = userService.GetUserGameRoleByUid(roleUid);
newEntry.ArchonQuestView = DailyNoteArchonQuestView.Create(newEntry.DailyNote, context.Chapters);
await dailyNoteDbService.AddDailyNoteEntryAsync(newEntry, token).ConfigureAwait(false); await dailyNoteDbService.AddDailyNoteEntryAsync(newEntry, token).ConfigureAwait(false);
newEntry.User = userAndUid.User; newEntry.User = userAndUid.User;

View File

@@ -18,6 +18,7 @@ internal sealed class NotifySuppressionContext : INotifySuppressionContext
public DailyNoteEntry Entry { get => entry; } public DailyNoteEntry Entry { get => entry; }
[SuppressMessage("", "SH002")]
public void Add(DailyNoteNotifyInfo info) public void Add(DailyNoteNotifyInfo info)
{ {
infos.Add(info); infos.Add(info);

View File

@@ -18,6 +18,7 @@ internal static class NotifySuppressionInvoker
context.Invoke<ExpeditionNotifySuppressionChecker>(); context.Invoke<ExpeditionNotifySuppressionChecker>();
} }
[SuppressMessage("", "CA1859")]
private static void Invoke<T>(this INotifySuppressionContext context) private static void Invoke<T>(this INotifySuppressionContext context)
where T : INotifySuppressionChecker, new() where T : INotifySuppressionChecker, new()
{ {

View File

@@ -59,7 +59,7 @@ internal sealed partial class GachaStatisticsFactory : IGachaStatisticsFactory
HomaGachaLogClient gachaLogClient, HomaGachaLogClient gachaLogClient,
List<Model.Entity.GachaItem> items, List<Model.Entity.GachaItem> items,
List<HistoryWishBuilder> historyWishBuilders, List<HistoryWishBuilder> historyWishBuilders,
in GachaLogServiceMetadataContext context, GachaLogServiceMetadataContext context,
AppOptions appOptions) AppOptions appOptions)
{ {
TypedWishSummaryBuilderContext standardContext = TypedWishSummaryBuilderContext.StandardWish(taskContext, gachaLogClient); TypedWishSummaryBuilderContext standardContext = TypedWishSummaryBuilderContext.StandardWish(taskContext, gachaLogClient);

View File

@@ -75,7 +75,7 @@ internal sealed class HutaoStatisticsFactory
QualityType.QUALITY_ORANGE => orangeItems, QualityType.QUALITY_ORANGE => orangeItems,
QualityType.QUALITY_PURPLE => purpleItems, QualityType.QUALITY_PURPLE => purpleItems,
QualityType.QUALITY_BLUE => blueItems, QualityType.QUALITY_BLUE => blueItems,
_ => throw Must.NeverHappen("意外的物品等级"), _ => throw HutaoException.NotSupported("意外的物品等级"),
}; };
list.Add(statisticsItem); list.Add(statisticsItem);

View File

@@ -31,7 +31,7 @@ internal sealed partial class GachaLogDbService : IGachaLogDbService
catch (SqliteException ex) catch (SqliteException ex)
{ {
string message = SH.FormatServiceGachaLogArchiveCollectionUserdataCorruptedMessage(ex.Message); string message = SH.FormatServiceGachaLogArchiveCollectionUserdataCorruptedMessage(ex.Message);
throw ThrowHelper.UserdataCorrupted(message, ex); throw HutaoException.Throw(message, ex);
} }
} }
@@ -97,7 +97,7 @@ internal sealed partial class GachaLogDbService : IGachaLogDbService
} }
catch (SqliteException ex) catch (SqliteException ex)
{ {
ThrowHelper.UserdataCorrupted(SH.ServiceGachaLogEndIdUserdataCorruptedMessage, ex); HutaoException.Throw(SH.ServiceGachaLogEndIdUserdataCorruptedMessage, ex);
} }
return item?.Id ?? 0L; return item?.Id ?? 0L;
@@ -126,7 +126,7 @@ internal sealed partial class GachaLogDbService : IGachaLogDbService
} }
catch (SqliteException ex) catch (SqliteException ex)
{ {
ThrowHelper.UserdataCorrupted(SH.ServiceGachaLogEndIdUserdataCorruptedMessage, ex); HutaoException.Throw(SH.ServiceGachaLogEndIdUserdataCorruptedMessage, ex);
} }
return item?.Id ?? 0L; return item?.Id ?? 0L;
@@ -156,7 +156,7 @@ internal sealed partial class GachaLogDbService : IGachaLogDbService
} }
catch (SqliteException ex) catch (SqliteException ex)
{ {
ThrowHelper.UserdataCorrupted(SH.ServiceGachaLogEndIdUserdataCorruptedMessage, ex); HutaoException.Throw(SH.ServiceGachaLogEndIdUserdataCorruptedMessage, ex);
} }
return item?.Id ?? 0L; return item?.Id ?? 0L;

View File

@@ -3,6 +3,7 @@
using Snap.Hutao.Core.Database; using Snap.Hutao.Core.Database;
using Snap.Hutao.Core.Diagnostics; using Snap.Hutao.Core.Diagnostics;
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Model.Entity; using Snap.Hutao.Model.Entity;
using Snap.Hutao.Model.InterChange.GachaLog; using Snap.Hutao.Model.InterChange.GachaLog;
using Snap.Hutao.Service.GachaLog.Factory; using Snap.Hutao.Service.GachaLog.Factory;
@@ -124,7 +125,7 @@ internal sealed partial class GachaLogService : IGachaLogService
{ {
RefreshStrategy.AggressiveMerge => false, RefreshStrategy.AggressiveMerge => false,
RefreshStrategy.LazyMerge => true, RefreshStrategy.LazyMerge => true,
_ => throw Must.NeverHappen(), _ => throw HutaoException.NotSupported(),
}; };
(bool authkeyValid, GachaArchive? result) = await FetchGachaLogsAsync(query, isLazy, progress, token).ConfigureAwait(false); (bool authkeyValid, GachaArchive? result) = await FetchGachaLogsAsync(query, isLazy, progress, token).ConfigureAwait(false);

View File

@@ -1,6 +1,7 @@
// Copyright (c) DGP Studio. All rights reserved. // Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license. // Licensed under the MIT license.
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Model; using Snap.Hutao.Model;
using Snap.Hutao.Model.Metadata; using Snap.Hutao.Model.Metadata;
using Snap.Hutao.Model.Metadata.Abstraction; using Snap.Hutao.Model.Metadata.Abstraction;
@@ -65,7 +66,7 @@ internal sealed class GachaLogServiceMetadataContext : IMetadataContext,
{ {
8U => IdAvatarMap[id], 8U => IdAvatarMap[id],
5U => IdWeaponMap[id], 5U => IdWeaponMap[id],
_ => throw Must.NeverHappen($"Id places: {place}"), _ => throw HutaoException.NotSupported($"Id places: {place}"),
}; };
} }

View File

@@ -1,6 +1,8 @@
// Copyright (c) DGP Studio. All rights reserved. // Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license. // Licensed under the MIT license.
using Snap.Hutao.Core.ExceptionService;
namespace Snap.Hutao.Service.GachaLog.QueryProvider; namespace Snap.Hutao.Service.GachaLog.QueryProvider;
[ConstructorGenerated] [ConstructorGenerated]
@@ -17,7 +19,7 @@ internal sealed partial class GachaLogQueryProviderFactory : IGachaLogQueryProvi
RefreshOption.SToken => serviceProvider.GetRequiredService<GachaLogQuerySTokenProvider>(), RefreshOption.SToken => serviceProvider.GetRequiredService<GachaLogQuerySTokenProvider>(),
RefreshOption.WebCache => serviceProvider.GetRequiredService<GachaLogQueryWebCacheProvider>(), RefreshOption.WebCache => serviceProvider.GetRequiredService<GachaLogQueryWebCacheProvider>(),
RefreshOption.ManualInput => serviceProvider.GetRequiredService<GachaLogQueryManualInputProvider>(), RefreshOption.ManualInput => serviceProvider.GetRequiredService<GachaLogQueryManualInputProvider>(),
_ => throw Must.NeverHappen("不支持的刷新选项"), _ => throw HutaoException.NotSupported("不支持的刷新选项"),
}; };
} }
} }

View File

@@ -28,7 +28,7 @@ internal sealed partial class UIGFImportService : IUIGFImportService
if (!uigf.IsCurrentVersionSupported(out UIGFVersion version)) if (!uigf.IsCurrentVersionSupported(out UIGFVersion version))
{ {
ThrowHelper.InvalidOperation(SH.ServiceUIGFImportUnsupportedVersion); HutaoException.InvalidOperation(SH.ServiceUIGFImportUnsupportedVersion);
} }
// v2.3+ support any locale // v2.3+ support any locale
@@ -39,13 +39,13 @@ internal sealed partial class UIGFImportService : IUIGFImportService
if (!cultureOptions.LanguageCodeFitsCurrentLocale(uigf.Info.Language)) if (!cultureOptions.LanguageCodeFitsCurrentLocale(uigf.Info.Language))
{ {
string message = SH.FormatServiceGachaUIGFImportLanguageNotMatch(uigf.Info.Language, cultureOptions.LanguageCode); string message = SH.FormatServiceGachaUIGFImportLanguageNotMatch(uigf.Info.Language, cultureOptions.LanguageCode);
ThrowHelper.InvalidOperation(message); HutaoException.InvalidOperation(message);
} }
if (!uigf.IsMajor2Minor2OrLowerListValid(out long id)) if (!uigf.IsMajor2Minor2OrLowerListValid(out long id))
{ {
string message = SH.FormatServiceGachaLogUIGFImportItemInvalidFormat(id); string message = SH.FormatServiceGachaLogUIGFImportItemInvalidFormat(id);
ThrowHelper.InvalidOperation(message); HutaoException.InvalidOperation(message);
} }
} }
@@ -54,7 +54,7 @@ internal sealed partial class UIGFImportService : IUIGFImportService
if (!uigf.IsMajor2Minor3OrHigherListValid(out long id)) if (!uigf.IsMajor2Minor3OrHigherListValid(out long id))
{ {
string message = SH.FormatServiceGachaLogUIGFImportItemInvalidFormat(id); string message = SH.FormatServiceGachaLogUIGFImportItemInvalidFormat(id);
ThrowHelper.InvalidOperation(message); HutaoException.InvalidOperation(message);
} }
} }
@@ -79,7 +79,7 @@ internal sealed partial class UIGFImportService : IUIGFImportService
.OrderByDescending(i => i.Id) .OrderByDescending(i => i.Id)
.Select(i => GachaItem.From(archiveId, i, context.GetItemId(i))) .Select(i => GachaItem.From(archiveId, i, context.GetItemId(i)))
.ToList(), .ToList(),
_ => throw Must.NeverHappen(), _ => throw HutaoException.NotSupported(),
}; };
ThrowIfContainsInvalidItem(currentTypedList); ThrowIfContainsInvalidItem(currentTypedList);
@@ -97,7 +97,7 @@ internal sealed partial class UIGFImportService : IUIGFImportService
// 因此从尾部开始查找 // 因此从尾部开始查找
if (currentTypeToAdd.LastOrDefault(item => item.ItemId is 0U) is { } item) if (currentTypeToAdd.LastOrDefault(item => item.ItemId is 0U) is { } item)
{ {
ThrowHelper.InvalidOperation(SH.FormatServiceGachaLogUIGFImportItemInvalidFormat(item.Id)); HutaoException.InvalidOperation(SH.FormatServiceGachaLogUIGFImportItemInvalidFormat(item.Id));
} }
} }
} }

View File

@@ -129,7 +129,7 @@ internal sealed partial class GameAccountService : IGameAccountService
} }
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
throw ThrowHelper.UserdataCorrupted(SH.ServiceGameDetectGameAccountMultiMatched, ex); throw HutaoException.Throw(SH.ServiceGameDetectGameAccountMultiMatched, ex);
} }
} }
} }

View File

@@ -70,7 +70,7 @@ internal static class RegistryInterop
{ {
SchemeType.ChineseOfficial => (ChineseKeyName, SdkChineseValueName), SchemeType.ChineseOfficial => (ChineseKeyName, SdkChineseValueName),
SchemeType.Oversea => (OverseaKeyName, SdkOverseaValueName), SchemeType.Oversea => (OverseaKeyName, SdkOverseaValueName),
_ => throw ThrowHelper.NotSupported($"Invalid account SchemeType: {scheme}"), _ => throw HutaoException.NotSupported($"Invalid account SchemeType: {scheme}"),
}; };
} }
} }

View File

@@ -22,6 +22,7 @@ internal readonly struct GameScreenCaptureContext
private readonly IDirect3DDevice direct3DDevice; private readonly IDirect3DDevice direct3DDevice;
private readonly HWND hwnd; private readonly HWND hwnd;
[SuppressMessage("", "SH002")]
public GameScreenCaptureContext(IDirect3DDevice direct3DDevice, HWND hwnd) public GameScreenCaptureContext(IDirect3DDevice direct3DDevice, HWND hwnd)
{ {
this.direct3DDevice = direct3DDevice; this.direct3DDevice = direct3DDevice;
@@ -87,6 +88,7 @@ internal readonly struct GameScreenCaptureContext
return clientBox.right <= width && clientBox.bottom <= height; return clientBox.right <= width && clientBox.bottom <= height;
} }
[SuppressMessage("", "SH002")]
private static DirectXPixelFormat DeterminePixelFormat(HWND hwnd) private static DirectXPixelFormat DeterminePixelFormat(HWND hwnd)
{ {
HDC hdc = GetDC(hwnd); HDC hdc = GetDC(hwnd);

View File

@@ -9,7 +9,7 @@ namespace Snap.Hutao.Service.Game.Automation.ScreenCapture;
internal sealed class GameScreenCaptureMemoryPool : MemoryPool<byte> internal sealed class GameScreenCaptureMemoryPool : MemoryPool<byte>
{ {
private static LazySlim<GameScreenCaptureMemoryPool> lazyShared = new(() => new()); private static readonly LazySlim<GameScreenCaptureMemoryPool> LazyShared = new(() => new());
private readonly object syncRoot = new(); private readonly object syncRoot = new();
private readonly LinkedList<GameScreenCaptureBuffer> unrentedBuffers = []; private readonly LinkedList<GameScreenCaptureBuffer> unrentedBuffers = [];
@@ -17,7 +17,7 @@ internal sealed class GameScreenCaptureMemoryPool : MemoryPool<byte>
private int bufferCount; private int bufferCount;
public new static GameScreenCaptureMemoryPool Shared { get => lazyShared.Value; } public static new GameScreenCaptureMemoryPool Shared { get => LazyShared.Value; }
public override int MaxBufferSize { get => Array.MaxLength; } public override int MaxBufferSize { get => Array.MaxLength; }
@@ -25,7 +25,7 @@ internal sealed class GameScreenCaptureMemoryPool : MemoryPool<byte>
public override IMemoryOwner<byte> Rent(int minBufferSize = -1) public override IMemoryOwner<byte> Rent(int minBufferSize = -1)
{ {
ArgumentOutOfRangeException.ThrowIfLessThan(minBufferSize, 0); ArgumentOutOfRangeException.ThrowIfNegative(minBufferSize);
lock (syncRoot) lock (syncRoot)
{ {

View File

@@ -9,7 +9,6 @@ using Snap.Hutao.Win32.Graphics.Dxgi;
using Snap.Hutao.Win32.Graphics.Dxgi.Common; using Snap.Hutao.Win32.Graphics.Dxgi.Common;
using Snap.Hutao.Win32.System.WinRT.Graphics.Capture; using Snap.Hutao.Win32.System.WinRT.Graphics.Capture;
using System.Buffers; using System.Buffers;
using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Windows.Graphics; using Windows.Graphics;
@@ -114,8 +113,9 @@ internal sealed class GameScreenCaptureSession : IDisposable
{ {
UnsafeProcessFrameSurface(frame.Surface); UnsafeProcessFrameSurface(frame.Surface);
} }
catch (Exception ex) // TODO: test if it's device lost. catch (Exception ex)
{ {
// TODO: test if it's device lost.
logger.LogError(ex, "Failed to process the frame surface."); logger.LogError(ex, "Failed to process the frame surface.");
needsReset = true; needsReset = true;
} }
@@ -209,8 +209,9 @@ internal sealed class GameScreenCaptureSession : IDisposable
{ {
subresource[row][..rowLength].CopyTo(buffer.Memory.Span.Slice(row * rowLength, rowLength)); subresource[row][..rowLength].CopyTo(buffer.Memory.Span.Slice(row * rowLength, rowLength));
} }
#pragma warning disable CA2000
frameRawPixelDataTaskCompletionSource.SetResult(new(buffer, (int)textureWidth, (int)textureHeight)); frameRawPixelDataTaskCompletionSource.SetResult(new(buffer, (int)textureWidth, (int)textureHeight));
#pragma warning restore CA2000
return; return;
} }
@@ -235,8 +236,9 @@ internal sealed class GameScreenCaptureSession : IDisposable
pixel.A = (byte)(float16Pixel.A * ByteMaxValue); pixel.A = (byte)(float16Pixel.A * ByteMaxValue);
} }
} }
#pragma warning disable CA2000
frameRawPixelDataTaskCompletionSource.SetResult(new(buffer, (int)textureWidth, (int)textureHeight)); frameRawPixelDataTaskCompletionSource.SetResult(new(buffer, (int)textureWidth, (int)textureHeight));
#pragma warning restore CA2000
return; return;
} }

View File

@@ -7,6 +7,7 @@ namespace Snap.Hutao.Service.Game.Package;
/// 包转换异常 /// 包转换异常
/// </summary> /// </summary>
[HighQuality] [HighQuality]
[Obsolete]
internal sealed class PackageConvertException : Exception internal sealed class PackageConvertException : Exception
{ {
/// <inheritdoc cref="Exception(string?, Exception?)"/> /// <inheritdoc cref="Exception(string?, Exception?)"/>

View File

@@ -180,7 +180,7 @@ internal sealed partial class PackageConverter
} }
catch (IOException ex) catch (IOException ex)
{ {
throw ThrowHelper.PackageConvert(SH.ServiceGamePackageRequestPackageVerionFailed, ex); throw HutaoException.Throw(SH.ServiceGamePackageRequestPackageVerionFailed, ex);
} }
} }
@@ -252,13 +252,13 @@ internal sealed partial class PackageConverter
{ {
// System.IO.IOException: The response ended prematurely. // System.IO.IOException: The response ended prematurely.
// System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream. // System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream.
ThrowHelper.PackageConvert(SH.FormatServiceGamePackageRequestScatteredFileFailed(remoteName), ex); HutaoException.Throw(SH.FormatServiceGamePackageRequestScatteredFileFailed(remoteName), ex);
} }
} }
if (!string.Equals(info.Remote.Md5, await MD5.HashFileAsync(cacheFile).ConfigureAwait(false), StringComparison.OrdinalIgnoreCase)) if (!string.Equals(info.Remote.Md5, await MD5.HashFileAsync(cacheFile).ConfigureAwait(false), StringComparison.OrdinalIgnoreCase))
{ {
ThrowHelper.PackageConvert(SH.FormatServiceGamePackageRequestScatteredFileFailed(remoteName)); HutaoException.Throw(SH.FormatServiceGamePackageRequestScatteredFileFailed(remoteName));
} }
} }
@@ -318,7 +318,7 @@ internal sealed partial class PackageConverter
{ {
// Access to the path is denied. // Access to the path is denied.
// When user install the game in special folder like 'Program Files' // When user install the game in special folder like 'Program Files'
throw ThrowHelper.GameFileOperation(SH.ServiceGamePackageRenameDataFolderFailed, ex); throw HutaoException.Throw(SH.ServiceGamePackageRenameDataFolderFailed, ex);
} }
// 重新下载所有 *pkg_version 文件 // 重新下载所有 *pkg_version 文件

View File

@@ -27,7 +27,7 @@ internal sealed partial class HutaoAsAService : IHutaoAsAService
{ {
RelayCommand<HutaoAnnouncement> dismissCommand = new(DismissAnnouncement); RelayCommand<HutaoAnnouncement> dismissCommand = new(DismissAnnouncement);
ApplicationDataCompositeValue excludedIds = LocalSetting.Get(SettingKeys.ExcludedAnnouncementIds, new ApplicationDataCompositeValue()); ApplicationDataCompositeValue excludedIds = LocalSetting.Get(SettingKeys.ExcludedAnnouncementIds, []);
List<long> data = excludedIds.Select(kvp => long.Parse(kvp.Key, CultureInfo.InvariantCulture)).ToList(); List<long> data = excludedIds.Select(kvp => long.Parse(kvp.Key, CultureInfo.InvariantCulture)).ToList();
Response<List<HutaoAnnouncement>> response; Response<List<HutaoAnnouncement>> response;
@@ -56,7 +56,7 @@ internal sealed partial class HutaoAsAService : IHutaoAsAService
{ {
if (announcement is not null && announcements is not null) if (announcement is not null && announcements is not null)
{ {
ApplicationDataCompositeValue excludedIds = LocalSetting.Get(SettingKeys.ExcludedAnnouncementIds, new ApplicationDataCompositeValue()); ApplicationDataCompositeValue excludedIds = LocalSetting.Get(SettingKeys.ExcludedAnnouncementIds, []);
foreach ((string key, object value) in excludedIds) foreach ((string key, object value) in excludedIds)
{ {

View File

@@ -59,14 +59,14 @@ internal sealed partial class HutaoSpiralAbyssStatisticsCache : IHutaoSpiralAbys
if (await metadataService.InitializeAsync().ConfigureAwait(false)) if (await metadataService.InitializeAsync().ConfigureAwait(false))
{ {
Dictionary<AvatarId, Avatar> idAvatarMap = await GetIdAvatarMapExtendedAsync().ConfigureAwait(false); Dictionary<AvatarId, Avatar> idAvatarMap = await GetIdAvatarMapExtendedAsync().ConfigureAwait(false);
List<Task> tasks = new(5) List<Task> tasks =
{ [
AvatarAppearanceRankAsync(idAvatarMap), AvatarAppearanceRankAsync(idAvatarMap),
AvatarUsageRanksAsync(idAvatarMap), AvatarUsageRanksAsync(idAvatarMap),
AvatarConstellationInfosAsync(idAvatarMap), AvatarConstellationInfosAsync(idAvatarMap),
TeamAppearancesAsync(idAvatarMap), TeamAppearancesAsync(idAvatarMap),
OverviewAsync(), OverviewAsync(),
}; ];
await Task.WhenAll(tasks).ConfigureAwait(false); await Task.WhenAll(tasks).ConfigureAwait(false);

View File

@@ -55,7 +55,7 @@ internal sealed partial class ObjectCacheDbService : IObjectCacheDbService
} }
catch (DbUpdateException ex) catch (DbUpdateException ex)
{ {
ThrowHelper.DatabaseCorrupted($"无法存储 Key:{key} 对应的值到数据库缓存", ex); HutaoException.Throw($"无法存储 Key:{key} 对应的值到数据库缓存", ex);
} }
return default!; return default!;

View File

@@ -1,9 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved. // Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license. // Licensed under the MIT license.
using Quartz;
using Snap.Hutao.Service.DailyNote;
namespace Snap.Hutao.Service.Job; namespace Snap.Hutao.Service.Job;
internal static class JobIdentity internal static class JobIdentity

View File

@@ -62,7 +62,7 @@ internal sealed partial class QuartzService : IQuartzService, IDisposable
{ {
DisposeAsync().GetAwaiter().GetResult(); DisposeAsync().GetAwaiter().GetResult();
async ValueTask DisposeAsync() async Task DisposeAsync()
{ {
if (scheduler is null) if (scheduler is null)
{ {

View File

@@ -21,7 +21,6 @@ namespace Snap.Hutao.Service.SpiralAbyss;
[Injection(InjectAs.Scoped, typeof(ISpiralAbyssRecordService))] [Injection(InjectAs.Scoped, typeof(ISpiralAbyssRecordService))]
internal sealed partial class SpiralAbyssRecordService : ISpiralAbyssRecordService internal sealed partial class SpiralAbyssRecordService : ISpiralAbyssRecordService
{ {
//private readonly IOverseaSupportFactory<IGameRecordClient> gameRecordClientFactory;
private readonly ISpiralAbyssRecordDbService spiralAbyssRecordDbService; private readonly ISpiralAbyssRecordDbService spiralAbyssRecordDbService;
private readonly IServiceScopeFactory serviceScopeFactory; private readonly IServiceScopeFactory serviceScopeFactory;
private readonly IMetadataService metadataService; private readonly IMetadataService metadataService;

View File

@@ -15,7 +15,7 @@ internal static class SupportedCultures
/*ToNameValue(CultureInfo.GetCultureInfo("de")),*/ /*ToNameValue(CultureInfo.GetCultureInfo("de")),*/
ToNameValue(CultureInfo.GetCultureInfo("en")), ToNameValue(CultureInfo.GetCultureInfo("en")),
/*ToNameValue(CultureInfo.GetCultureInfo("es")),*/ /*ToNameValue(CultureInfo.GetCultureInfo("es")),*/
/*ToNameValue(CultureInfo.GetCultureInfo("fr")),*/ ToNameValue(CultureInfo.GetCultureInfo("fr")),
ToNameValue(CultureInfo.GetCultureInfo("id")), ToNameValue(CultureInfo.GetCultureInfo("id")),
/*ToNameValue(CultureInfo.GetCultureInfo("it")),*/ /*ToNameValue(CultureInfo.GetCultureInfo("it")),*/
ToNameValue(CultureInfo.GetCultureInfo("ja")), ToNameValue(CultureInfo.GetCultureInfo("ja")),

View File

@@ -25,7 +25,7 @@
<AppxBundle>Never</AppxBundle> <AppxBundle>Never</AppxBundle>
<HoursBetweenUpdateChecks>0</HoursBetweenUpdateChecks> <HoursBetweenUpdateChecks>0</HoursBetweenUpdateChecks>
<StartupObject>Snap.Hutao.Program</StartupObject> <StartupObject>Snap.Hutao.Program</StartupObject>
<DefineConstants>$(DefineConstants);DISABLE_XAML_GENERATED_MAIN;DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION;DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT</DefineConstants> <DefineConstants>$(DefineConstants);DISABLE_XAML_GENERATED_MAIN;DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION;DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT;$(AlphaConstants)</DefineConstants>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks> <AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>embedded</DebugType> <DebugType>embedded</DebugType>
@@ -117,6 +117,7 @@
<None Remove="Resource\BlurBackground.png" /> <None Remove="Resource\BlurBackground.png" />
<None Remove="Resource\Font\CascadiaMono.ttf" /> <None Remove="Resource\Font\CascadiaMono.ttf" />
<None Remove="Resource\Font\MiSans-Regular.ttf" /> <None Remove="Resource\Font\MiSans-Regular.ttf" />
<None Remove="Resource\GuideStaticResourceQualityComparison.png" />
<None Remove="Resource\HutaoIconSourceTransparentBackgroundGradient1.png" /> <None Remove="Resource\HutaoIconSourceTransparentBackgroundGradient1.png" />
<None Remove="Resource\Icon\UI_AchievementIcon_3_3.png" /> <None Remove="Resource\Icon\UI_AchievementIcon_3_3.png" />
<None Remove="Resource\Icon\UI_GachaShowPanel_Bg_Weapon.png" /> <None Remove="Resource\Icon\UI_GachaShowPanel_Bg_Weapon.png" />
@@ -216,6 +217,7 @@
<AdditionalFiles Include="stylecop.json" /> <AdditionalFiles Include="stylecop.json" />
<AdditionalFiles Include="Resource\Localization\SH.resx" /> <AdditionalFiles Include="Resource\Localization\SH.resx" />
<AdditionalFiles Include="Resource\Localization\SH.en.resx" /> <AdditionalFiles Include="Resource\Localization\SH.en.resx" />
<AdditionalFiles Include="Resource\Localization\SH.fr.resx" />
<AdditionalFiles Include="Resource\Localization\SH.id.resx" /> <AdditionalFiles Include="Resource\Localization\SH.id.resx" />
<AdditionalFiles Include="Resource\Localization\SH.ja.resx" /> <AdditionalFiles Include="Resource\Localization\SH.ja.resx" />
<AdditionalFiles Include="Resource\Localization\SH.ko.resx" /> <AdditionalFiles Include="Resource\Localization\SH.ko.resx" />
@@ -265,6 +267,7 @@
<Content Include="Resource\BlurBackground.png" /> <Content Include="Resource\BlurBackground.png" />
<Content Include="Resource\Font\CascadiaMono.ttf" /> <Content Include="Resource\Font\CascadiaMono.ttf" />
<Content Include="Resource\Font\MiSans-Regular.ttf" /> <Content Include="Resource\Font\MiSans-Regular.ttf" />
<Content Include="Resource\GuideStaticResourceQualityComparison.png" />
<Content Include="Resource\HutaoIconSourceTransparentBackgroundGradient1.png" /> <Content Include="Resource\HutaoIconSourceTransparentBackgroundGradient1.png" />
<Content Include="Resource\Icon\UI_AchievementIcon_3_3.png" /> <Content Include="Resource\Icon\UI_AchievementIcon_3_3.png" />
<Content Include="Resource\Icon\UI_GachaShowPanel_Bg_Weapon.png" /> <Content Include="Resource\Icon\UI_GachaShowPanel_Bg_Weapon.png" />
@@ -323,7 +326,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Validation" Version="17.8.8" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="17.8.8" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.22621.3233" /> <PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.26100.1" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240428000" /> <PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240428000" />
<PackageReference Include="QRCoder" Version="1.5.1" /> <PackageReference Include="QRCoder" Version="1.5.1" />
<PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.9.0" /> <PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.9.0" />
@@ -336,7 +339,7 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Snap.Hutao.SourceGeneration" Version="1.0.7"> <PackageReference Include="Snap.Hutao.SourceGeneration" Version="1.0.8">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>

View File

@@ -22,6 +22,6 @@ internal sealed class Int32ToVisibilityConverter : IValueConverter
/// <inheritdoc/> /// <inheritdoc/>
public object ConvertBack(object value, Type targetType, object parameter, string language) public object ConvertBack(object value, Type targetType, object parameter, string language)
{ {
throw ThrowHelper.NotSupported(); throw HutaoException.NotSupported();
} }
} }

View File

@@ -22,6 +22,6 @@ internal sealed class Int32ToVisibilityRevertConverter : IValueConverter
/// <inheritdoc/> /// <inheritdoc/>
public object ConvertBack(object value, Type targetType, object parameter, string language) public object ConvertBack(object value, Type targetType, object parameter, string language)
{ {
throw ThrowHelper.NotSupported(); throw HutaoException.NotSupported();
} }
} }

View File

@@ -2,6 +2,7 @@
x:Class="Snap.Hutao.View.Guide.GuideView" x:Class="Snap.Hutao.View.Guide.GuideView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cw="using:CommunityToolkit.WinUI"
xmlns:cwc="using:CommunityToolkit.WinUI.Controls" xmlns:cwc="using:CommunityToolkit.WinUI.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
@@ -210,28 +211,75 @@
<RowDefinition Height="auto"/> <RowDefinition Height="auto"/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<StackPanel <Grid
Grid.Row="0" Grid.Row="0"
Margin="16" Margin="72"
HorizontalAlignment="Center" HorizontalAlignment="Center"
VerticalAlignment="Center"> ColumnSpacing="32">
<TextBlock Style="{StaticResource SubtitleTextBlockStyle}" Text="{shcm:ResourceString Name=ViewGuideStepStaticResourceSettingQualityHeader}"/> <Grid.ColumnDefinitions>
<ListView <ColumnDefinition/>
MinWidth="320" <ColumnDefinition/>
Margin="0,8,0,32" </Grid.ColumnDefinitions>
DisplayMemberPath="Name" <cwc:ConstrainedBox Grid.Column="0" AspectRatio="1:1">
ItemsSource="{Binding StaticResourceOptions.ImageQualities}" <Border cw:Effects.Shadow="{ThemeResource CompatCardShadow}">
SelectedItem="{Binding StaticResourceOptions.ImageQuality, Mode=TwoWay}"/> <Grid
<TextBlock Style="{StaticResource SubtitleTextBlockStyle}" Text="{shcm:ResourceString Name=ViewGuideStepStaticResourceSettingMinimumHeader}"/> BorderBrush="{x:Null}"
<ListView BorderThickness="0"
MinWidth="320" Style="{ThemeResource GridCardStyle}">
Margin="0,8,0,32" <Grid.RowDefinitions>
DisplayMemberPath="Name" <RowDefinition/>
ItemsSource="{Binding StaticResourceOptions.ImageArchives}" <RowDefinition Height="auto"/>
SelectedItem="{Binding StaticResourceOptions.ImageArchive, Mode=TwoWay}"/> </Grid.RowDefinitions>
<Grid Grid.Row="0">
<TextBlock Margin="0,16,0,0" Text="{Binding StaticResourceOptions.SizeInformationText, Mode=OneWay}"/> <Image
</StackPanel> HorizontalAlignment="Center"
VerticalAlignment="Center"
Source="ms-appx:///Resource/GuideStaticResourceQualityComparison.png"/>
<Rectangle
Width="2"
HorizontalAlignment="Center"
VerticalAlignment="Stretch"
Fill="White"/>
</Grid>
<Grid
Grid.Row="1"
Padding="16"
HorizontalAlignment="Stretch"
VerticalAlignment="Bottom"
Background="{ThemeResource ContentDialogBackground}"
BorderThickness="0,1,0,0"
CornerRadius="{ThemeResource ControlCornerRadiusBottom}"
Style="{ThemeResource GridCardStyle}">
<StackPanel HorizontalAlignment="Left" Orientation="Vertical">
<TextBlock Text="{shcm:ResourceString Name=ViewModelGuideStaticResourceQualityHigh}" TextAlignment="Left"/>
<TextBlock Text="233 KB" TextAlignment="Left"/>
</StackPanel>
<StackPanel HorizontalAlignment="Right" Orientation="Vertical">
<TextBlock Text="{shcm:ResourceString Name=ViewModelGuideStaticResourceQualityRaw}" TextAlignment="Right"/>
<TextBlock Text="1030 KB" TextAlignment="Right"/>
</StackPanel>
</Grid>
</Grid>
</Border>
</cwc:ConstrainedBox>
<StackPanel Grid.Column="1" VerticalAlignment="Top">
<TextBlock Style="{StaticResource SubtitleTextBlockStyle}" Text="{shcm:ResourceString Name=ViewGuideStepStaticResourceSettingQualityHeader}"/>
<ListView
MinWidth="320"
Margin="0,8,0,32"
DisplayMemberPath="Name"
ItemsSource="{Binding StaticResourceOptions.ImageQualities}"
SelectedItem="{Binding StaticResourceOptions.ImageQuality, Mode=TwoWay}"/>
<TextBlock Style="{StaticResource SubtitleTextBlockStyle}" Text="{shcm:ResourceString Name=ViewGuideStepStaticResourceSettingMinimumHeader}"/>
<ListView
MinWidth="320"
Margin="0,8,0,32"
DisplayMemberPath="Name"
ItemsSource="{Binding StaticResourceOptions.ImageArchives}"
SelectedItem="{Binding StaticResourceOptions.ImageArchive, Mode=TwoWay}"/>
<TextBlock Margin="0,16,0,0" Text="{Binding StaticResourceOptions.SizeInformationText, Mode=OneWay}"/>
</StackPanel>
</Grid>
<TextBlock <TextBlock
Grid.Row="1" Grid.Row="1"

View File

@@ -381,7 +381,7 @@
ItemTemplate="{StaticResource InventoryItemTemplate}" ItemTemplate="{StaticResource InventoryItemTemplate}"
ItemsSource="{Binding InventoryItems}"> ItemsSource="{Binding InventoryItems}">
<ItemsRepeater.Layout> <ItemsRepeater.Layout>
<cwcont:WrapLayout HorizontalSpacing="12" VerticalSpacing="12"/> <shcl:WrapLayout HorizontalSpacing="12" VerticalSpacing="12"/>
</ItemsRepeater.Layout> </ItemsRepeater.Layout>
</ItemsRepeater> </ItemsRepeater>
</ScrollView> </ScrollView>

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