Compare commits

..

1 Commits

Author SHA1 Message Date
qhy040404
df7f685a3c prompt user dailynote auto-refresh is not effective while notify icon is disabled 2024-05-23 10:55:43 +08:00
138 changed files with 723 additions and 434 deletions

View File

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

View File

@@ -10,7 +10,7 @@ jobs:
- uses: actions/stale@v9
with:
any-of-labels: 'needs-more-info,需要更多信息'
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.'
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.'
days-before-stale: 7
days-before-close: 3
close-issue-reason: not_planned

View File

@@ -17,15 +17,7 @@ You can follow the instructions in the [Quick Start](https://hut.ao/en/quick-sta
## 本地化翻译 / 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)
[![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)
[![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)
Snap Hutao 使用 [Crowdin](https://translate.hut.ao/) 作为客户端文本翻译平台,在该平台上你可以为你熟悉的语言提交翻译文本。我们感谢每一个为 Snap Hutao 做出贡献的社区成员,并且欢迎更多的朋友能参与到这个项目中。
@@ -54,13 +46,13 @@ Snap Hutao uses [Crowdin](https://translate.hut.ao/) as a client text translatio
* [CommunityToolkit/dotnet](https://github.com/CommunityToolkit/dotnet)
* [CommunityToolkit/Labs-Windows](https://github.com/CommunityToolkit/Labs-Windows)
* [CommunityToolkit/Windows](https://github.com/CommunityToolkit/Windows)
* [dahall/taskscheduler](https://github.com/dahall/taskscheduler)
* [dotnet/efcore](https://github.com/dotnet/efcore)
* [dotnet/runtime](https://github.com/dotnet/runtime)
* [DotNetAnalyzers/StyleCopAnalyzers](https://github.com/DotNetAnalyzers/StyleCopAnalyzers)
* [microsoft/vs-validation](https://github.com/microsoft/vs-validation)
* [microsoft/WindowsAppSDK](https://github.com/microsoft/WindowsAppSDK)
* [microsoft/microsoft-ui-xaml](https://github.com/microsoft/microsoft-ui-xaml)
* [quartznet/quartznet](https://github.com/quartznet/quartznet)
### 支撑项目 / Supporter Project
@@ -72,9 +64,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.
| [![](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://www.digitalocean.com)|
|[![jetbrains](https://github.com/DGP-Studio/Snap.Hutao/assets/36357191/4105772a-728a-4a84-9c6e-d713a5698a20)](https://www.jetbrains.com/opensource/)|||
|:----------------------------------------------------------------------------------------------------:|:-----------------------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------------------------------:|
| [![](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) |
- Netlify provides document and home page hosting service for Snap Hutao
@@ -88,8 +80,6 @@ Snap Hutao is currently using sponsored software from the following service prov
- DigitalOcean provides reliable cloud database for Snap Hutao database backup
- Jetbrains provides powerful IDE for Snap Hutao infrastructure services coding
## 开发 / Development
![Snap.Hutao](https://repobeats.axiom.co/api/embed/f029553fbe0c60689b1710476ec8512452163fc9.svg)

View File

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

View File

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

View File

@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
@@ -47,14 +46,7 @@ public sealed class UnsafeRuntimeBehaviorTest
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
{

View File

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

View File

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

View File

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

View File

@@ -7,8 +7,6 @@ namespace Snap.Hutao.Control.Helper;
[SuppressMessage("", "SH001")]
[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
{
private static void OnSquareLengthChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
@@ -17,22 +15,4 @@ public sealed partial class FrameworkElementHelper
element.Width = (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,6 +1,8 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using Snap.Hutao.Control.Extension;
using Snap.Hutao.Core.Caching;
using Snap.Hutao.Core.ExceptionService;

View File

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

View File

@@ -8,13 +8,13 @@ namespace Snap.Hutao.Control.Layout;
internal sealed class WrapItem
{
public static Point EmptyPosition { get; } = new(float.NegativeInfinity, float.NegativeInfinity);
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;

View File

@@ -25,7 +25,10 @@ internal sealed class WrapLayoutState
public WrapItem GetItemAt(int index)
{
ArgumentOutOfRangeException.ThrowIfNegative(index);
if (index < 0)
{
throw new IndexOutOfRangeException();
}
if (index <= (items.Count - 1))
{

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,22 @@
// 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,8 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using System.Runtime.CompilerServices;
namespace Snap.Hutao.Core.ExceptionService;
internal sealed class HutaoException : Exception
@@ -13,13 +11,11 @@ internal sealed class HutaoException : Exception
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static HutaoException Throw(string message, Exception? innerException = default)
{
throw new HutaoException(message, innerException);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ThrowIf([DoesNotReturnIf(true)] bool condition, string message, Exception? innerException = default)
{
if (condition)
@@ -28,7 +24,6 @@ internal sealed class HutaoException : Exception
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ThrowIfNot([DoesNotReturnIf(false)] bool condition, string message, Exception? innerException = default)
{
if (!condition)
@@ -38,28 +33,18 @@ internal sealed class HutaoException : Exception
}
[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)
{
throw new HutaoException(SH.FormatServiceGachaStatisticsFactoryItemIdInvalid(id), innerException);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static HutaoException UserdataCorrupted(string message, Exception? innerException = default)
{
throw new HutaoException(message, innerException);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
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}'";
@@ -67,21 +52,18 @@ internal sealed class HutaoException : Exception
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static InvalidOperationException InvalidOperation(string message, Exception? innerException = default)
{
throw new InvalidOperationException(message, innerException);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static NotSupportedException NotSupported(string? message = default, Exception? innerException = default)
{
throw new NotSupportedException(message, innerException);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static OperationCanceledException OperationCanceled(string message, Exception? innerException = default)
{
throw new OperationCanceledException(message, innerException);

View File

@@ -0,0 +1,23 @@
// 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,6 +1,9 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Service.Game;
using Snap.Hutao.Service.Game.Package;
using System.IO;
using System.Runtime.CompilerServices;
namespace Snap.Hutao.Core.ExceptionService;
@@ -19,4 +22,92 @@ internal static class ThrowHelper
{
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

@@ -0,0 +1,22 @@
// 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))
{
response.EnsureSuccessStatusCode();
using (IMemoryOwner<byte> memoryOwner = MemoryPool<byte>.Shared.Rent(bufferSize))
using (IMemoryOwner<byte> memoryOwner = MemoryPool<byte>.Shared.Rent())
{
Memory<byte> buffer = memoryOwner.Memory;
using (Stream stream = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false))

View File

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

View File

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

View File

@@ -68,17 +68,12 @@ internal sealed partial class AppActivation : IAppActivation, IAppActivationActi
using (activateSemaphore.Enter())
{
// TODO: Introduced in 1.10.2, remove in later version
serviceProvider.GetRequiredService<IJumpListInterop>().ClearAsync().SafeForget();
serviceProvider.GetRequiredService<IScheduleTaskInterop>().UnregisterAllTasks();
serviceProvider.GetRequiredService<HotKeyOptions>().RegisterAll();
if (UnsafeLocalSetting.Get(SettingKeys.Major1Minor10Revision0GuideState, GuideState.Language) < GuideState.Completed)
{
return;
}
serviceProvider.GetRequiredService<HotKeyOptions>().RegisterAll();
if (serviceProvider.GetRequiredService<AppOptions>().IsNotifyIconEnabled)
{
XamlWindowLifetime.ApplicationLaunchedWithNotifyIcon = true;
@@ -86,6 +81,7 @@ internal sealed partial class AppActivation : IAppActivation, IAppActivationActi
_ = serviceProvider.GetRequiredService<NotifyIconController>();
}
serviceProvider.GetRequiredService<IScheduleTaskInterop>().UnregisterAllTasks();
serviceProvider.GetRequiredService<IQuartzService>().StartAsync(default).SafeForget();
}
}

View File

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

View File

@@ -83,10 +83,9 @@ internal static class LoggerExtension
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)
{
string? colorizedMessage = Colorize(message, args, out object?[] outArgs);
string colorizedMessage = Colorize(message, args, out object?[] outArgs)!;
logger.Log(logLevel, eventId, exception, colorizedMessage, outArgs);
}

View File

@@ -1,9 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Core.Shell;
internal interface IJumpListInterop
{
ValueTask ClearAsync();
}

View File

@@ -1,22 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Windows.UI.StartScreen;
namespace Snap.Hutao.Core.Shell;
[Injection(InjectAs.Transient, typeof(IJumpListInterop))]
internal sealed class JumpListInterop : IJumpListInterop
{
public async ValueTask ClearAsync()
{
if (JumpList.IsSupported())
{
JumpList list = await JumpList.LoadCurrentAsync();
list.Items.Clear();
await list.SaveAsync();
}
}
}

View File

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

View File

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

View File

@@ -0,0 +1,56 @@
// 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;
// https://github.com/microsoft/microsoft-ui-xaml/blob/winui3/release/1.5-stable/controls/dev/Materials/DesktopAcrylicBackdrop/DesktopAcrylicBackdrop.cpp
internal sealed partial class InputActiveDesktopAcrylicBackdrop : SystemBackdrop
internal sealed class InputActiveDesktopAcrylicBackdrop : SystemBackdrop
{
private readonly ConcurrentDictionary<ICompositionSupportsSystemBackdrop, DesktopAcrylicController> controllers = [];
@@ -18,10 +18,11 @@ internal sealed partial class InputActiveDesktopAcrylicBackdrop : SystemBackdrop
{
base.OnTargetConnected(target, xamlRoot);
DesktopAcrylicController newController = new();
SystemBackdropConfiguration configuration = GetDefaultSystemBackdropConfiguration(target, xamlRoot);
configuration.IsInputActive = true;
DesktopAcrylicController newController = new();
newController.AddSystemBackdropTarget(target);
newController.SetSystemBackdropConfiguration(configuration);
controllers.TryAdd(target, newController);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -11,25 +11,25 @@ namespace Snap.Hutao.Model.Intrinsic.Frozen;
[HighQuality]
internal static class IntrinsicFrozen
{
public static FrozenSet<string> AssociationTypes { get; } = NamesFromEnum<AssociationType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<string> AssociationTypes { get; } = Enum.GetValues<AssociationType>().Select(e => e.GetLocalizedDescriptionOrDefault()).OfType<string>().ToFrozenSet();
public static FrozenSet<NameValue<AssociationType>> AssociationTypeNameValues { get; } = NameValuesFromEnum<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<string> WeaponTypes { get; } = NamesFromEnum<WeaponType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<string> WeaponTypes { get; } = Enum.GetValues<WeaponType>().Select(e => e.GetLocalizedDescriptionOrDefault()).OfType<string>().ToFrozenSet();
public static FrozenSet<NameValue<WeaponType>> WeaponTypeNameValues { get; } = NameValuesFromEnum<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<string> ItemQualities { get; } = NamesFromEnum<QualityType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<string> ItemQualities { get; } = Enum.GetValues<QualityType>().Select(e => e.GetLocalizedDescriptionOrDefault()).OfType<string>().ToFrozenSet();
public static FrozenSet<NameValue<QualityType>> ItemQualityNameValues { get; } = NameValuesFromEnum<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<string> BodyTypes { get; } = NamesFromEnum<BodyType>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<string> BodyTypes { get; } = Enum.GetValues<BodyType>().Select(e => e.GetLocalizedDescriptionOrDefault()).OfType<string>().ToFrozenSet();
public static FrozenSet<NameValue<BodyType>> BodyTypeNameValues { get; } = NameValuesFromEnum<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<string> FightProperties { get; } = NamesFromEnum<FightProperty>(e => e.GetLocalizedDescriptionOrDefault());
public static FrozenSet<string> FightProperties { get; } = Enum.GetValues<FightProperty>().Select(e => e.GetLocalizedDescriptionOrDefault()).OfType<string>().ToFrozenSet();
public static FrozenSet<NameValue<FightProperty>> FightPropertyNameValues { get; } = NameValuesFromEnum<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<string> ElementNames { get; } = FrozenSet.ToFrozenSet(
[
@@ -63,50 +63,4 @@ internal static class IntrinsicFrozen
SH.ModelMetadataMaterialWeaponEnhancementMaterial,
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,7 +2,6 @@
// Licensed under the MIT license.
using Snap.Hutao.Control;
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Model.Intrinsic;
namespace Snap.Hutao.Model.Metadata.Converter;
@@ -22,7 +21,7 @@ internal sealed class AssociationTypeIconConverter : ValueConverter<AssociationT
AssociationType.ASSOC_TYPE_FONTAINE => "Fontaine",
AssociationType.ASSOC_TYPE_NATLAN => default,
AssociationType.ASSOC_TYPE_SNEZHNAYA => default,
_ => throw HutaoException.NotSupported(),
_ => throw Must.NeverHappen(),
};
return association is null

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1964,9 +1964,6 @@
<data name="ViewPageDailyNoteNotificationSetting" xml:space="preserve">
<value>通知设置</value>
</data>
<data name="ViewPageDailyNoteNotificationUnavailableHint" xml:space="preserve">
<value>胡桃的通知权限已被关闭</value>
</data>
<data name="ViewPageDailyNoteRefresh" xml:space="preserve">
<value>立即刷新</value>
</data>
@@ -1998,7 +1995,7 @@
<value>刷新</value>
</data>
<data name="ViewPageDailyNoteSettingRefreshNotifyIconDisabledHint" xml:space="preserve">
<value>未启用通知区域图标,关闭窗口后自动刷新将不会执行</value>
<value>未启用通知区域图标,自动刷新将不会执行</value>
</data>
<data name="ViewPageDailyNoteSlientModeDescription" xml:space="preserve">
<value>在我游玩原神时不通知我</value>

View File

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

View File

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

View File

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

View File

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

View File

@@ -48,9 +48,29 @@ internal sealed partial class DailyNoteNotificationOperation
return;
}
string attribution = entry.UserGameRole is not null
? entry.UserGameRole.ToString()
: await GetUserUidAsync(entry).ConfigureAwait(false);
string? attribution = SH.ServiceDailyNoteNotifierAttribution;
if (entry.UserGameRole is not null)
{
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()
.AddHeader(ToastHeaderIdArgument, SH.ServiceDailyNoteNotifierTitle, ToastHeaderIdArgument)
@@ -110,24 +130,4 @@ internal sealed partial class DailyNoteNotificationOperation
// Prevent notify when we are in game && silent mode.
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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -27,7 +27,7 @@ internal sealed partial class HutaoAsAService : IHutaoAsAService
{
RelayCommand<HutaoAnnouncement> dismissCommand = new(DismissAnnouncement);
ApplicationDataCompositeValue excludedIds = LocalSetting.Get(SettingKeys.ExcludedAnnouncementIds, []);
ApplicationDataCompositeValue excludedIds = LocalSetting.Get(SettingKeys.ExcludedAnnouncementIds, new ApplicationDataCompositeValue());
List<long> data = excludedIds.Select(kvp => long.Parse(kvp.Key, CultureInfo.InvariantCulture)).ToList();
Response<List<HutaoAnnouncement>> response;
@@ -56,7 +56,7 @@ internal sealed partial class HutaoAsAService : IHutaoAsAService
{
if (announcement is not null && announcements is not null)
{
ApplicationDataCompositeValue excludedIds = LocalSetting.Get(SettingKeys.ExcludedAnnouncementIds, []);
ApplicationDataCompositeValue excludedIds = LocalSetting.Get(SettingKeys.ExcludedAnnouncementIds, new ApplicationDataCompositeValue());
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))
{
Dictionary<AvatarId, Avatar> idAvatarMap = await GetIdAvatarMapExtendedAsync().ConfigureAwait(false);
List<Task> tasks =
[
List<Task> tasks = new(5)
{
AvatarAppearanceRankAsync(idAvatarMap),
AvatarUsageRanksAsync(idAvatarMap),
AvatarConstellationInfosAsync(idAvatarMap),
TeamAppearancesAsync(idAvatarMap),
OverviewAsync(),
];
};
await Task.WhenAll(tasks).ConfigureAwait(false);

View File

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

View File

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

View File

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

View File

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

View File

@@ -326,7 +326,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Validation" Version="17.8.8" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.26100.1" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.22621.3233" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.5.240428000" />
<PackageReference Include="QRCoder" Version="1.5.1" />
<PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.9.0" />
@@ -339,7 +339,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Snap.Hutao.SourceGeneration" Version="1.0.8">
<PackageReference Include="Snap.Hutao.SourceGeneration" Version="1.0.7">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

View File

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

View File

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

View File

@@ -545,7 +545,7 @@
</cwcont:HeaderedContentControl.Header>
<StackPanel Spacing="{StaticResource SettingsCardSpacing}">
<InfoBar
Title="{shcm:ResourceString Name=ViewPageDailyNoteNotificationUnavailableHint}"
Title="胡桃的通知权限已被关闭"
IsClosable="False"
IsOpen="True"
Severity="Warning"

View File

@@ -426,10 +426,8 @@
<cwc:SettingsCard
Description="{shcm:ResourceString Name=ViewPageSettingKeyShortcutAutoClickingDescription}"
Header="{shcm:ResourceString Name=ViewPageSettingKeyShortcutAutoClickingHeader}"
HeaderIcon="{shcm:FontIcon Glyph=&#xE92E;}"
IsEnabled="{Binding RuntimeOptions.IsElevated}">
HeaderIcon="{shcm:FontIcon Glyph=&#xE92E;}">
<StackPanel Orientation="Horizontal" Spacing="8">
<shvc:Elevation Margin="0,0,16,0" Visibility="{Binding RuntimeOptions.IsElevated, Converter={StaticResource BoolToVisibilityRevertConverter}}"/>
<Button
MinWidth="32"
MinHeight="32"
@@ -439,7 +437,7 @@
FontFamily="{ThemeResource SymbolThemeFontFamily}"
Style="{ThemeResource SettingButtonStyle}">
<Button.Flyout>
<Flyout FlyoutPresenterStyle="{ThemeResource FlyoutPresenterPadding16And10Style}" ShouldConstrainToRootBounds="False">
<Flyout FlyoutPresenterStyle="{ThemeResource FlyoutPresenterPadding16And10Style}">
<cwc:UniformGrid
ColumnSpacing="16"
Columns="2"
@@ -449,7 +447,7 @@
MinWidth="64"
VerticalAlignment="Center"
Content="Win"
IsEnabled="False"/>
IsChecked="{Binding HotKeyOptions.MouseClickRepeatForeverKeyCombination.ModifierHasWindows, Mode=TwoWay}"/>
<CheckBox
MinWidth="64"
VerticalAlignment="Center"

View File

@@ -98,6 +98,13 @@
Style="{ThemeResource SettingButtonStyle}"/>
</cwc:SettingsCard>
<cwc:SettingsCard Header="Test Windows.Graphics.Capture">
<Button
Command="{Binding TestWindowsGraphicsCaptureCommand}"
Content="Test"
Style="{ThemeResource SettingButtonStyle}"/>
</cwc:SettingsCard>
<cwc:SettingsCard Header="Suppress Metadata Initialization">
<ToggleSwitch IsOn="{Binding SuppressMetadataInitialization, Mode=TwoWay}"/>
</cwc:SettingsCard>

View File

@@ -179,7 +179,7 @@ internal sealed partial class AchievementViewModel : Abstraction.ViewModel, INav
dependencies.InfoBarService.Warning(SH.FormatViewModelAchievementArchiveAlreadyExists(name));
break;
default:
throw HutaoException.NotSupported();
throw Must.NeverHappen();
}
}
}

View File

@@ -7,7 +7,6 @@ using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Imaging;
using Snap.Hutao.Control.Extension;
using Snap.Hutao.Control.Media;
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Core.IO.DataTransfer;
using Snap.Hutao.Factory.ContentDialog;
using Snap.Hutao.Message;
@@ -311,7 +310,7 @@ internal sealed partial class AvatarPropertyViewModel : Abstraction.ViewModel, I
return CultivateCoreResult.SaveConsumptionFailed;
}
}
catch (HutaoException ex)
catch (Core.ExceptionService.UserdataCorruptedException ex)
{
infoBarService.Error(ex, SH.ViewModelCultivationAddWarning);
}

View File

@@ -15,6 +15,11 @@ namespace Snap.Hutao.ViewModel.Complex;
[HighQuality]
internal sealed class Team : List<AvatarView>
{
/// <summary>
/// 构造一个新的队伍
/// </summary>
/// <param name="team">队伍</param>
/// <param name="idAvatarMap">映射</param>
public Team(ItemRate<string, int> team, Dictionary<AvatarId, Avatar> idAvatarMap, int rank)
: base(4)
{

View File

@@ -2,7 +2,6 @@
// Licensed under the MIT license.
using Microsoft.UI.Xaml.Controls;
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Factory.ContentDialog;
using Snap.Hutao.Model.Entity;
using Snap.Hutao.Service.Cultivation;
@@ -100,7 +99,7 @@ internal sealed partial class CultivationViewModel : Abstraction.ViewModel
infoBarService.Information(SH.ViewModelCultivationProjectAlreadyExists);
break;
default:
throw HutaoException.NotSupported();
throw Must.NeverHappen();
}
}

View File

@@ -4,7 +4,6 @@
using Microsoft.UI.Xaml.Controls;
using Snap.Hutao.Control.Extension;
using Snap.Hutao.Core;
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Factory.ContentDialog;
using Snap.Hutao.Model.Entity;
using Snap.Hutao.Service;
@@ -32,7 +31,6 @@ internal sealed partial class DailyNoteViewModel : Abstraction.ViewModel
private readonly DailyNoteOptions dailyNoteOptions;
private readonly IMetadataService metadataService;
private readonly IInfoBarService infoBarService;
private readonly RuntimeOptions runtimeOptions;
private readonly ITaskContext taskContext;
private readonly IUserService userService;
private readonly AppOptions appOptions;
@@ -42,8 +40,6 @@ internal sealed partial class DailyNoteViewModel : Abstraction.ViewModel
public DailyNoteOptions DailyNoteOptions { get => dailyNoteOptions; }
public RuntimeOptions RuntimeOptions { get => runtimeOptions; }
public AppOptions AppOptions { get => appOptions; }
public IWebViewerSource VerifyUrlSource { get; } = new DailyNoteWebViewerSource();
@@ -73,7 +69,7 @@ internal sealed partial class DailyNoteViewModel : Abstraction.ViewModel
DailyNoteEntries = entries;
return true;
}
catch (HutaoException ex)
catch (Core.ExceptionService.UserdataCorruptedException ex)
{
infoBarService.Error(ex);
}

View File

@@ -1,7 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Model.Entity;
using Snap.Hutao.Service.DailyNote;
using Snap.Hutao.Service.Metadata;
@@ -49,7 +48,7 @@ internal sealed partial class DailyNoteViewModelSlim : Abstraction.ViewModelSlim
DailyNoteEntries = entryList;
IsInitialized = true;
}
catch (HutaoException ex)
catch (Core.ExceptionService.UserdataCorruptedException ex)
{
infoBarService.Error(ex);
return;

View File

@@ -179,7 +179,7 @@ internal sealed partial class GachaLogViewModel : Abstraction.ViewModel
{
authkeyValid = await gachaLogService.RefreshGachaLogAsync(query, strategy, progress, CancellationToken).ConfigureAwait(false);
}
catch (HutaoException ex)
catch (UserdataCorruptedException ex)
{
authkeyValid = false;
infoBarService.Error(ex);
@@ -349,7 +349,7 @@ internal sealed partial class GachaLogViewModel : Abstraction.ViewModel
Statistics = statistics;
IsInitialized = true;
}
catch (HutaoException ex)
catch (UserdataCorruptedException ex)
{
infoBarService.Error(ex);
}

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