Compare commits

..

1 Commits

Author SHA1 Message Date
qhy040404
23b95b1d13 fix #1633 2024-05-25 16:16:19 +08:00
225 changed files with 4067 additions and 6543 deletions

View File

@@ -45,55 +45,13 @@ jobs:
run: dotnet tool restore && dotnet cake
env:
VERSION_API_TOKEN: ${{ secrets.VERSION_API_TOKEN }}
CERTIFICATE: ${{ secrets.CERTIFICATE }}
PW: ${{ secrets.PW }}
- name: Upload signed msix
if: success() && github.event_name != 'pull_request'
uses: actions/upload-artifact@v4
with:
name: Snap.Hutao.Alpha-${{ steps.cake.outputs.version }}
path: ${{ github.workspace }}/src/output/Snap.Hutao.Alpha-${{ steps.cake.outputs.version }}.msix
- name: Add summary
if: success() && github.event_name != 'pull_request'
shell: pwsh
run: |
$summary = "
> [!WARNING]
> 该版本是由 CI 程序自动打包生成的 `Alpha` 测试版本,**仅供开发者测试使用**
> [!TIP]
> 普通用户请[点击这里](https://github.com/DGP-Studio/Snap.Hutao/releases/latest/)下载最新的稳定版本
> [!IMPORTANT]
> 请注意,从 Snap Hutao Alpha 2023.12.21.3 开始,我们将使用全新的 CI 证书,原有的 Snap.Hutao.CI.cer 将在几天后过期停止使用。
>
> 请安装 [DGP_Studio_CA.crt](https://github.com/DGP-Automation/Hutao-Auto-Release/releases/download/certificate-ca/DGP_Studio_CA.crt) 到 `受信任的根证书颁发机构` 以安装测试版安装包
"
echo $summary >> $Env:GITHUB_STEP_SUMMARY
fallback_build:
runs-on: windows-latest
needs: build
if: failure()
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0
- name: Cake
id: cake
shell: pwsh
run: dotnet tool restore && dotnet cake
env:
VERSION_API_TOKEN: ${{ secrets.VERSION_API_TOKEN }}
CERTIFICATE: ${{ secrets.CERTIFICATE }}
PW: ${{ secrets.PW }}
- name: Sign Msix
if: success() && github.event_name != 'pull_request'
shell: pwsh
run: |
[System.Convert]::FromBase64String("${{ secrets.CERTIFICATE }}") | Set-Content -AsByteStream temp.pfx
signtool.exe sign /debug /v /a /fd SHA256 /f temp.pfx /p ${{ secrets.PW }} ${{ github.workspace }}\src\output\Snap.Hutao.Alpha-${{ steps.cake.outputs.version }}.msix
- name: Upload signed msix
if: success() && github.event_name != 'pull_request'

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

@@ -11,9 +11,6 @@ var version = "version";
var repoDir = "repoDir";
var outputPath = "outputPath";
var pfxPath = "pfxPath";
var pw = "pw";
// Extension
static ProcessArgumentBuilder AppendIf(this ProcessArgumentBuilder builder, string text, bool condition)
@@ -65,11 +62,6 @@ if (GitHubActions.IsRunningOnGitHubActions)
}
);
var certificateBase64 = HasEnvironmentVariable("CERTIFICATE") ? EnvironmentVariable("CERTIFICATE") : throw new Exception("Cannot find CERTIFICATE");
pw = HasEnvironmentVariable("PW") ? EnvironmentVariable("PW") : throw new Exception("Cannot find PW");
pfxPath = System.IO.Path.Combine(repoDir, "temp.pfx");
System.IO.File.WriteAllBytes(pfxPath, System.Convert.FromBase64String(certificateBase64));
Information($"Version: {version}");
}
@@ -96,19 +88,10 @@ else // Local
Information($"Version: {version}");
}
// Windows SDK
var registry = new WindowsRegistry();
var winsdkRegistry = registry.LocalMachine.OpenKey(@"SOFTWARE\Microsoft\Windows Kits\Installed Roots");
var winsdkVersion = winsdkRegistry.GetSubKeyNames().MaxBy(key => int.Parse(key.Split(".")[2]));
var winsdkPath = (string)winsdkRegistry.GetValue("KitsRoot10");
var winsdkBinPath = System.IO.Path.Combine(winsdkPath, "bin", winsdkVersion, "x64");
Information($"Windows SDK: {winsdkPath}");
Task("Build")
.IsDependentOn("Build binary package")
.IsDependentOn("Copy files")
.IsDependentOn("Build MSIX")
.IsDependentOn("Sign");
.IsDependentOn("Build MSIX");
Task("NuGet Restore")
.Does(() =>
@@ -224,11 +207,8 @@ Task("Build MSIX")
{
arguments = "pack /d " + binPath + " /p " + System.IO.Path.Combine(outputPath, $"Snap.Hutao.Local-{version}.msix");
}
var makeappxPath = System.IO.Path.Combine(winsdkBinPath, "makeappx.exe");
var p = StartProcess(
makeappxPath,
"makeappx.exe",
new ProcessSettings
{
Arguments = arguments
@@ -236,46 +216,7 @@ Task("Build MSIX")
);
if (p != 0)
{
throw new InvalidOperationException("Build MSIX failed with exit code " + p);
}
});
Task("Sign")
.IsDependentOn("Build MSIX")
.Does(() =>
{
if (AppVeyor.IsRunningOnAppVeyor)
{
Information("Move to SignPath. Skip signing.");
return;
}
else if (GitHubActions.IsRunningOnGitHubActions)
{
if (GitHubActions.Environment.PullRequest.IsPullRequest)
{
Information("Is Pull Request. Skip signing.");
return;
}
var signPath = System.IO.Path.Combine(winsdkBinPath, "signtool.exe");
var arguments = $"sign /debug /v /a /fd SHA256 /f {pfxPath} /p {pw} {System.IO.Path.Combine(outputPath, $"Snap.Hutao.Alpha-{version}.msix")}";
var p = StartProcess(
signPath,
new ProcessSettings
{
Arguments = arguments
}
);
if (p != 0)
{
throw new InvalidOperationException("Sign failed with exit code " + p);
}
}
else
{
Information("Local configuration. Skip signing.");
return;
throw new InvalidOperationException("Build failed with exit code " + p);
}
});

View File

@@ -6,25 +6,14 @@ namespace Snap.Hutao.Test.IncomingFeature;
public class SpiralAbyssScheduleIdTest
{
private static readonly TimeSpan Utc8 = new(8, 0, 0);
private static readonly DateTimeOffset AcrobaticsBattleIntroducedTime = new(2024, 7, 1, 4, 0, 0, Utc8);
[TestMethod]
public void Test()
{
Console.WriteLine($"当前第 {GetForDateTimeOffset(DateTimeOffset.Now)} 期");
// 2020-07-01 04:00:00 为第 1 期
// 2024-06-16 04:00:00 为第 96 期
// 2024-07-01 04:00:00 为第 97 期
// 2024-07-16 04:00:00 为第 98 期
// 2024-08-01 04:00:00 为第 99 期
Console.WriteLine($"2020-07-01 04:00:00 为第 {GetForDateTimeOffset(new(2020, 07, 01, 4, 0, 0, Utc8))} 期");
Console.WriteLine($"2024-06-16 04:00:00 为第 {GetForDateTimeOffset(new(2024, 06, 16, 4, 0, 0, Utc8))} 期");
Console.WriteLine($"2024-07-01 04:00:00 为第 {GetForDateTimeOffset(new(2024, 07, 01, 4, 0, 0, Utc8))} 期");
Console.WriteLine($"2024-07-16 04:00:00 为第 {GetForDateTimeOffset(new(2024, 07, 16, 4, 0, 0, Utc8))} 期");
Console.WriteLine($"2024-08-01 04:00:00 为第 {GetForDateTimeOffset(new(2024, 08, 01, 4, 0, 0, Utc8))} 期");
Console.WriteLine($"2024-08-16 04:00:00 为第 {GetForDateTimeOffset(new(2024, 08, 16, 4, 0, 0, Utc8))} 期");
Console.WriteLine($"2024-09-01 04:00:00 为第 {GetForDateTimeOffset(new(2024, 09, 01, 4, 0, 0, Utc8))} 期");
DateTimeOffset dateTimeOffset = new(2020, 7, 1, 4, 0, 0, Utc8);
Console.WriteLine($"2020-07-01 04:00:00 为第 {GetForDateTimeOffset(dateTimeOffset)} 期");
}
public static int GetForDateTimeOffset(DateTimeOffset dateTimeOffset)
@@ -49,12 +38,6 @@ public class SpiralAbyssScheduleIdTest
periodNum--;
}
if (dateTimeOffset >= AcrobaticsBattleIntroducedTime)
{
// 当超过 96 期时,每一个月一期
periodNum = (4 * 12 * 2) + ((periodNum - (4 * 12 * 2)) / 2);
}
return periodNum;
}
}

View File

@@ -1,45 +0,0 @@
using System.Drawing;
using System.Net.Http;
using System.Net.Http.Json;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Snap.Hutao.Test.RuntimeBehavior;
[TestClass]
public sealed class HttpClientBehaviorTest
{
private const int MessageNotYetSent = 0;
[TestMethod]
public async Task RetrySendHttpRequestMessage()
{
using (HttpClient httpClient = new())
{
HttpRequestMessage requestMessage = new(HttpMethod.Post, "https://jsonplaceholder.typicode.com/posts");
JsonContent content = JsonContent.Create(new Point(12, 34));
requestMessage.Content = content;
using (requestMessage)
{
await httpClient.SendAsync(requestMessage).ConfigureAwait(false);
}
Interlocked.Exchange(ref GetPrivateSendStatus(requestMessage), MessageNotYetSent);
Volatile.Write(ref GetPrivateDisposed(content), false);
await httpClient.SendAsync(requestMessage).ConfigureAwait(false);
}
}
// private int _sendStatus
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_sendStatus")]
private static extern ref int GetPrivateSendStatus(HttpRequestMessage message);
// private bool _disposed
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_disposed")]
private static extern ref bool GetPrivateDisposed(HttpRequestMessage message);
// private bool _disposed
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_disposed")]
private static extern ref bool GetPrivateDisposed(HttpContent content);
}

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

@@ -13,9 +13,9 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.4.3" />
<PackageReference Include="MSTest.TestFramework" Version="3.4.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.3.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.3.1" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

View File

@@ -7,7 +7,6 @@
<ResourceDictionary.MergedDictionaries>
<XamlControlsResources/>
<ResourceDictionary Source="ms-appx:///CommunityToolkit.WinUI.Controls.SettingsControls/SettingsCard/SettingsCard.xaml"/>
<ResourceDictionary Source="ms-appx:///CommunityToolkit.WinUI.Controls.TokenizingTextBox/TokenizingTextBox.xaml"/>
<ResourceDictionary Source="ms-appx:///Control/Loading.xaml"/>
<ResourceDictionary Source="ms-appx:///Control/Image/CachedImage.xaml"/>
<ResourceDictionary Source="ms-appx:///Control/Theme/Card.xaml"/>
@@ -30,6 +29,7 @@
<ResourceDictionary Source="ms-appx:///Control/Theme/TransitionCollection.xaml"/>
<ResourceDictionary Source="ms-appx:///Control/Theme/Uri.xaml"/>
<ResourceDictionary Source="ms-appx:///Control/Theme/WindowOverride.xaml"/>
<ResourceDictionary Source="ms-appx:///Control/TokenizingTextBox/TokenizingTextBox.xaml"/>
<ResourceDictionary Source="ms-appx:///View/Card/Primitive/CardProgressBar.xaml"/>
</ResourceDictionary.MergedDictionaries>

View File

@@ -59,7 +59,7 @@ public sealed partial class App : Application
public new void Exit()
{
XamlLifetime.ApplicationExiting = true;
XamlWindowLifetime.ApplicationExiting = true;
base.Exit();
}
@@ -72,7 +72,6 @@ public sealed partial class App : Application
if (serviceProvider.GetRequiredService<PrivateNamedPipeClient>().TryRedirectActivationTo(activatedEventArgs))
{
logger.LogDebug("Application exiting on RedirectActivationTo");
Exit();
return;
}
@@ -81,19 +80,12 @@ public sealed partial class App : Application
LogDiagnosticInformation();
// Manually invoke
HutaoActivationArguments hutaoArgs = HutaoActivationArguments.FromAppActivationArguments(activatedEventArgs);
if (hutaoArgs.Kind is HutaoActivationKind.Toast)
{
Exit();
return;
}
activation.Activate(hutaoArgs);
activation.Activate(HutaoActivationArguments.FromAppActivationArguments(activatedEventArgs));
activation.PostInitialization();
}
catch (Exception ex)
{
logger.LogError(ex, "Application failed in App.OnLaunched");
Debug.WriteLine(ex);
Process.GetCurrentProcess().Kill();
}
}

View File

@@ -1,12 +1,10 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using CommunityToolkit.WinUI;
using CommunityToolkit.WinUI.Controls;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Snap.Hutao.Control.Extension;
using Snap.Hutao.Control.TokenizingTextBox;
using System.Collections;
namespace Snap.Hutao.Control.AutoSuggestBox;
@@ -14,33 +12,16 @@ namespace Snap.Hutao.Control.AutoSuggestBox;
[DependencyProperty("FilterCommand", typeof(ICommand))]
[DependencyProperty("FilterCommandParameter", typeof(object))]
[DependencyProperty("AvailableTokens", typeof(IReadOnlyDictionary<string, SearchToken>))]
internal sealed partial class AutoSuggestTokenBox : TokenizingTextBox
internal sealed partial class AutoSuggestTokenBox : TokenizingTextBox.TokenizingTextBox
{
public AutoSuggestTokenBox()
{
DefaultStyleKey = typeof(TokenizingTextBox);
DefaultStyleKey = typeof(TokenizingTextBox.TokenizingTextBox);
TextChanged += OnFilterSuggestionRequested;
QuerySubmitted += OnQuerySubmitted;
TokenItemAdding += OnTokenItemAdding;
TokenItemAdded += OnTokenItemCollectionChanged;
TokenItemRemoved += OnTokenItemCollectionChanged;
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
if (this.FindDescendant("SuggestionsPopup") is Popup { Child: Border { Child: ListView listView } border })
{
IAppResourceProvider appResourceProvider = this.ServiceProvider().GetRequiredService<IAppResourceProvider>();
listView.Background = null;
listView.Margin = appResourceProvider.GetResource<Thickness>("AutoSuggestListPadding");
border.Background = appResourceProvider.GetResource<Microsoft.UI.Xaml.Media.Brush>("AutoSuggestBoxSuggestionsListBackground");
CornerRadius overlayCornerRadius = appResourceProvider.GetResource<CornerRadius>("OverlayCornerRadius");
CornerRadiusFilterConverter cornerRadiusFilterConverter = new() { Filter = CornerRadiusFilterKind.Bottom };
border.CornerRadius = (CornerRadius)cornerRadiusFilterConverter.Convert(overlayCornerRadius, typeof(CornerRadius), default, default);
}
}
private void OnFilterSuggestionRequested(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
@@ -73,7 +54,7 @@ internal sealed partial class AutoSuggestTokenBox : TokenizingTextBox
CommandInvocation.TryExecute(FilterCommand, FilterCommandParameter);
}
private void OnTokenItemAdding(TokenizingTextBox sender, TokenItemAddingEventArgs args)
private void OnTokenItemAdding(TokenizingTextBox.TokenizingTextBox sender, TokenItemAddingEventArgs args)
{
if (string.IsNullOrWhiteSpace(args.TokenText))
{
@@ -90,7 +71,7 @@ internal sealed partial class AutoSuggestTokenBox : TokenizingTextBox
}
}
private void OnTokenItemCollectionChanged(TokenizingTextBox sender, object args)
private void OnTokenItemCollectionChanged(TokenizingTextBox.TokenizingTextBox sender, object args)
{
if (args is SearchToken { Kind: SearchTokenKind.None } token)
{

View File

@@ -0,0 +1,39 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Xaml.Controls;
using Windows.Foundation.Collections;
namespace Snap.Hutao.Control.Collection.Alternating;
[Obsolete("Use SettingsCard instead")]
[DependencyProperty("ItemAlternateBackground", typeof(Microsoft.UI.Xaml.Media.Brush))]
internal sealed partial class AlternatingItemsControl : ItemsControl
{
private readonly VectorChangedEventHandler<object> itemsVectorChangedEventHandler;
public AlternatingItemsControl()
{
itemsVectorChangedEventHandler = OnItemsVectorChanged;
Items.VectorChanged += itemsVectorChangedEventHandler;
}
private void OnItemsVectorChanged(IObservableVector<object> items, IVectorChangedEventArgs args)
{
if (args.CollectionChange is CollectionChange.Reset)
{
int index = (int)args.Index;
for (int i = index; i < items.Count; i++)
{
if (items[i] is IAlternatingItem item)
{
item.Background = i % 2 is 0 ? default : ItemAlternateBackground;
}
else
{
break;
}
}
}
}
}

View File

@@ -0,0 +1,10 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Control.Collection.Alternating;
[Obsolete("Use SettingsCard instead")]
internal interface IAlternatingItem
{
public Microsoft.UI.Xaml.Media.Brush? Background { get; set; }
}

View File

@@ -2,7 +2,6 @@
// Licensed under the MIT license.
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Markup;
namespace Snap.Hutao.Control;
@@ -37,18 +36,9 @@ internal class Loading : Microsoft.UI.Xaml.Controls.ContentControl
private static void IsLoadingPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Loading control = (Loading)d;
control.presenter ??= control.GetTemplateChild("ContentGrid") as FrameworkElement;
if ((bool)e.NewValue)
{
control.presenter ??= control.GetTemplateChild("ContentGrid") as FrameworkElement;
}
else if (control.presenter is not null)
{
XamlMarkupHelper.UnloadObject(control.presenter);
control.presenter = null;
}
control.Update();
control?.Update();
}
private void Update()

View File

@@ -23,8 +23,7 @@
<ContentPresenter
x:Name="ContentGrid"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
x:Load="False">
VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
<ContentPresenter.RenderTransform>
<CompositeTransform/>
</ContentPresenter.RenderTransform>
@@ -85,4 +84,4 @@
</Setter>
</Style>
</ResourceDictionary>
</ResourceDictionary>

View File

@@ -3,11 +3,8 @@
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Markup;
using Microsoft.UI.Xaml.Navigation;
using Snap.Hutao.Core.Abstraction;
using Snap.Hutao.Service.Navigation;
using Snap.Hutao.View.Helper;
using Snap.Hutao.ViewModel.Abstraction;
namespace Snap.Hutao.Control;
@@ -39,11 +36,6 @@ internal class ScopedPage : Page
extra.NotifyNavigationCompleted();
}
public virtual void UnloadObjectOverride(DependencyObject unloadableObject)
{
XamlMarkupHelper.UnloadObject(unloadableObject);
}
/// <summary>
/// 初始化
/// 应当在 InitializeComponent() 前调用
@@ -54,14 +46,8 @@ internal class ScopedPage : Page
{
try
{
TViewModel viewModel = pageScope.ServiceProvider.GetRequiredService<TViewModel>();
using (viewModel.DisposeLock.Enter())
{
viewModel.IsViewDisposed = false;
viewModel.CancellationToken = viewCancellationTokenSource.Token;
viewModel.DeferContentLoader = new DeferContentLoader(this);
}
IViewModel viewModel = pageScope.ServiceProvider.GetRequiredService<TViewModel>();
viewModel.CancellationToken = viewCancellationTokenSource.Token;
DataContext = viewModel;
}
catch (Exception ex)
@@ -110,9 +96,10 @@ internal class ScopedPage : Page
viewCancellationTokenSource.Cancel();
IViewModel viewModel = (IViewModel)DataContext;
using (viewModel.DisposeLock.Enter())
using (SemaphoreSlim locker = viewModel.DisposeLock)
{
// Wait to ensure viewmodel operation is completed
locker.Wait();
viewModel.IsViewDisposed = true;
// Dispose the scope

View File

@@ -52,12 +52,6 @@
<Thickness x:Key="InfoBarIconMargin">19,16,19,16</Thickness>
<Thickness x:Key="InfoBarContentRootPadding">0,0,0,0</Thickness>
<x:Double x:Key="InfoBarIconFontSize">20</x:Double>
<Thickness x:Key="InfoBarTitleHorizontalOrientationMargin">0,0,0,0</Thickness>
<Thickness x:Key="InfoBarMessageHorizontalOrientationMargin">12,0,0,0</Thickness>
<Thickness x:Key="InfoBarTitleVerticalOrientationMargin">0,16,0,0</Thickness>
<Thickness x:Key="InfoBarMessageVerticalOrientationMargin">0,6,0,0</Thickness>
<!-- TODO: When will DefaultInfoBarStyle added -->
<Style TargetType="InfoBar">
<Setter Property="shch:InfoBarHelper.IsTextSelectionEnabled" Value="False"/>
@@ -134,7 +128,6 @@
<InfoBarPanel
Grid.Column="1"
Margin="{StaticResource InfoBarPanelMargin}"
VerticalAlignment="Center"
HorizontalOrientationPadding="{StaticResource InfoBarPanelHorizontalOrientationPadding}"
VerticalOrientationPadding="{StaticResource InfoBarPanelVerticalOrientationPadding}">
<TextBlock
@@ -180,7 +173,6 @@
<Button
Name="CloseButton"
Grid.Column="2"
VerticalAlignment="Top"
Command="{TemplateBinding CloseButtonCommand}"
CommandParameter="{TemplateBinding CloseButtonCommandParameter}"
Style="{TemplateBinding CloseButtonStyle}">
@@ -244,14 +236,7 @@
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="SeverityLevels">
<VisualState x:Name="Informational">
<VisualState.Setters>
<Setter Target="ContentRoot.Background" Value="{ThemeResource InfoBarInformationalSeverityBackgroundBrush}"/>
<Setter Target="IconBackground.Foreground" Value="{ThemeResource InfoBarInformationalSeverityIconBackground}"/>
<Setter Target="StandardIcon.Text" Value="{StaticResource InfoBarInformationalIconGlyph}"/>
<Setter Target="StandardIcon.Foreground" Value="{ThemeResource InfoBarInformationalSeverityIconForeground}"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Informational"/>
<VisualState x:Name="Error">
<VisualState.Setters>
<Setter Target="ContentRoot.Background" Value="{ThemeResource InfoBarErrorSeverityBackgroundBrush}"/>

View File

@@ -1,4 +1,4 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TransitionCollection x:Key="ContentThemeTransitions">
<ContentThemeTransition/>
</TransitionCollection>
@@ -20,4 +20,4 @@
<TransitionCollection x:Key="NavigationThemeTransitions">
<NavigationThemeTransition/>
</TransitionCollection>
</ResourceDictionary>
</ResourceDictionary>

View File

@@ -0,0 +1,11 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Control.TokenizingTextBox;
internal interface ITokenStringContainer
{
string Text { get; set; }
bool IsLast { get; }
}

View File

@@ -0,0 +1,350 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using CommunityToolkit.WinUI.Helpers;
using System.Collections;
using System.Collections.Specialized;
namespace Snap.Hutao.Control.TokenizingTextBox;
internal sealed class InterspersedObservableCollection : IList, IEnumerable<object>, INotifyCollectionChanged
{
private readonly Dictionary<int?, object> interspersedObjects = [];
private bool isInsertingOriginal;
public InterspersedObservableCollection(object itemsSource)
{
if (itemsSource is not IList list)
{
throw new ArgumentException("The input items source must be assignable to the System.Collections.IList type.");
}
ItemsSource = list;
if (ItemsSource is INotifyCollectionChanged notifier)
{
WeakEventListener<InterspersedObservableCollection, object?, NotifyCollectionChangedEventArgs> weakPropertyChangedListener = new(this)
{
OnEventAction = static (instance, source, eventArgs) => instance.ItemsSource_CollectionChanged(source, eventArgs),
OnDetachAction = (weakEventListener) => notifier.CollectionChanged -= weakEventListener.OnEvent, // Use Local Reference Only
};
notifier.CollectionChanged += weakPropertyChangedListener.OnEvent;
}
}
public event NotifyCollectionChangedEventHandler? CollectionChanged;
public IList ItemsSource { get; private set; }
public bool IsFixedSize => false;
public bool IsReadOnly => false;
public int Count => ItemsSource.Count + interspersedObjects.Count;
public bool IsSynchronized => false;
public object SyncRoot => new();
public object? this[int index]
{
get
{
if (interspersedObjects.TryGetValue(index, out object? value))
{
return value;
}
// Find out the number of elements in our dictionary with keys below ours.
return ItemsSource[ToInnerIndex(index)];
}
set => throw new NotImplementedException();
}
public void Insert(int index, object? obj)
{
MoveKeysForward(index, 1); // Move existing keys at index over to make room for new item
ArgumentNullException.ThrowIfNull(obj);
interspersedObjects[index] = obj;
CollectionChanged?.Invoke(this, new(NotifyCollectionChangedAction.Add, obj, index));
}
public void InsertAt(int outerIndex, object obj)
{
// Find out our closest index based on interspersed keys
int index = outerIndex - interspersedObjects.Keys.Count(key => key!.Value < outerIndex); // Note: we exclude the = from ToInnerIndex here
// If we're inserting where we would normally, then just do that, otherwise we need extra room to not move other keys
if (index != outerIndex)
{
MoveKeysForward(outerIndex, 1); // Skip over until the current spot unlike normal
isInsertingOriginal = true; // Prevent Collection callback from moving keys forward on insert
}
// Insert into original collection
ItemsSource.Insert(index, obj);
// TODO: handle manipulation/notification if not observable
}
public IEnumerator<object> GetEnumerator()
{
int i = 0; // Index of our current 'virtual' position
int count = 0;
int realized = 0;
foreach (object element in ItemsSource)
{
while (interspersedObjects.TryGetValue(i++, out object? obj))
{
realized++; // Track interspersed items used
yield return obj;
}
count++; // Track original items used
yield return element;
}
// Add any remaining items in our interspersed collection past the index we reached in the original collection
if (realized < interspersedObjects.Count)
{
// Only select items past our current index, but make sure we've sorted them by their index as well.
foreach ((int? _, object value) in interspersedObjects.Where(kvp => kvp.Key >= i).OrderBy(kvp => kvp.Key))
{
yield return value;
}
}
}
public int Add(object? value)
{
ArgumentNullException.ThrowIfNull(value);
int index = ItemsSource.Add(value); //// TODO: If the collection isn't observable, we should do manipulations/notifications here...?
return ToOuterIndex(index);
}
public void Clear()
{
ItemsSource.Clear();
interspersedObjects.Clear();
}
public bool Contains(object? value)
{
ArgumentNullException.ThrowIfNull(value);
return interspersedObjects.ContainsValue(value) || ItemsSource.Contains(value);
}
public int IndexOf(object? value)
{
ArgumentNullException.ThrowIfNull(value);
(int? key, object _) = ItemKeySearch(value);
if (key is int k)
{
return k;
}
int index = ItemsSource.IndexOf(value);
// Find out the number of elements in our dictionary with keys below ours.
return index == -1 ? -1 : ToOuterIndex(index);
}
public void Remove(object? value)
{
ArgumentNullException.ThrowIfNull(value);
(int? key, object obj) = ItemKeySearch(value);
if (key is int k)
{
interspersedObjects.Remove(k);
MoveKeysBackward(k, 1); // Move other interspersed items back
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, obj, k));
}
else
{
ItemsSource.Remove(value); // TODO: If not observable, update indices?
}
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private void ItemsSource_CollectionChanged(object? source, NotifyCollectionChangedEventArgs eventArgs)
{
switch (eventArgs.Action)
{
case NotifyCollectionChangedAction.Add:
// Shift any existing interspersed items after the inserted item
ArgumentNullException.ThrowIfNull(eventArgs.NewItems);
int count = eventArgs.NewItems.Count;
if (count > 0)
{
if (!isInsertingOriginal)
{
MoveKeysForward(eventArgs.NewStartingIndex, count);
}
isInsertingOriginal = false;
CollectionChanged?.Invoke(this, new(NotifyCollectionChangedAction.Add, eventArgs.NewItems, ToOuterIndex(eventArgs.NewStartingIndex)));
}
break;
case NotifyCollectionChangedAction.Remove:
ArgumentNullException.ThrowIfNull(eventArgs.OldItems);
count = eventArgs.OldItems.Count;
if (count > 0)
{
int outerIndex = ToOuterIndexAfterRemoval(eventArgs.OldStartingIndex);
MoveKeysBackward(outerIndex, count);
CollectionChanged?.Invoke(this, new(NotifyCollectionChangedAction.Remove, eventArgs.OldItems, outerIndex));
}
break;
case NotifyCollectionChangedAction.Reset:
ReadjustKeys();
// TODO: ListView doesn't like this notification and throws a visual tree duplication exception...
// Not sure what to do with that yet...
CollectionChanged?.Invoke(this, eventArgs);
break;
}
}
private void MoveKeysForward(int pivot, int amount)
{
// Sort in reverse order to work from highest to lowest
foreach (int? key in interspersedObjects.Keys.OrderByDescending(v => v))
{
if (key < pivot) //// If it's the last item in the collection, we still want to move our last key, otherwise we'd use <=
{
break;
}
interspersedObjects[key + amount] = interspersedObjects[key];
interspersedObjects.Remove(key);
}
}
private void MoveKeysBackward(int pivot, int amount)
{
// Sort in regular order to work from the earliest indices onwards
foreach (int? key in interspersedObjects.Keys.OrderBy(v => v))
{
// Skip elements before the pivot point
if (key <= pivot) //// Include pivot point as that's the point where we start modifying beyond
{
continue;
}
interspersedObjects[key - amount] = interspersedObjects[key];
interspersedObjects.Remove(key);
}
}
private void ReadjustKeys()
{
int count = ItemsSource.Count;
int existing = 0;
foreach (int? key in interspersedObjects.Keys.OrderBy(v => v))
{
if (key <= count)
{
existing++;
continue;
}
interspersedObjects[count + existing++] = interspersedObjects[key];
interspersedObjects.Remove(key);
}
}
private int ToInnerIndex(int outerIndex)
{
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(outerIndex, Count);
if (interspersedObjects.ContainsKey(outerIndex))
{
throw new ArgumentException("The outer index can't be inserted as a key to the original collection.");
}
return outerIndex - interspersedObjects.Keys.Count(key => key!.Value <= outerIndex);
}
private int ToOuterIndex(int innerIndex)
{
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(innerIndex, ItemsSource.Count);
foreach ((int? key, object _) in interspersedObjects.OrderBy(v => v.Key))
{
if (innerIndex >= key)
{
innerIndex++;
}
else
{
break;
}
}
return innerIndex;
}
private int ToOuterIndexAfterRemoval(int innerIndexToProject)
{
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(innerIndexToProject, ItemsSource.Count + 1);
//// TODO: Deal with bounds (0 / Count)? Or is it the same?
foreach ((int? key, object _) in interspersedObjects.OrderBy(v => v.Key))
{
if (innerIndexToProject >= key)
{
innerIndexToProject++;
}
else
{
break;
}
}
return innerIndexToProject;
}
private KeyValuePair<int?, object> ItemKeySearch(object value)
{
if (value is null)
{
return interspersedObjects.FirstOrDefault(kvp => kvp.Value is null);
}
return interspersedObjects.FirstOrDefault(kvp => kvp.Value.Equals(value));
}
}

View File

@@ -0,0 +1,27 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Xaml;
namespace Snap.Hutao.Control.TokenizingTextBox;
[DependencyProperty("Text", typeof(string))]
internal sealed partial class PretokenStringContainer : DependencyObject, ITokenStringContainer
{
public PretokenStringContainer(bool isLast = false)
{
IsLast = isLast;
}
public PretokenStringContainer(string text)
{
Text = text;
}
public bool IsLast { get; private set; }
public override string ToString()
{
return Text;
}
}

View File

@@ -0,0 +1,18 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using CommunityToolkit.Common.Deferred;
namespace Snap.Hutao.Control.TokenizingTextBox;
internal sealed class TokenItemAddingEventArgs : DeferredCancelEventArgs
{
public TokenItemAddingEventArgs(string token)
{
TokenText = token;
}
public string TokenText { get; private set; }
public object? Item { get; set; }
}

View File

@@ -0,0 +1,19 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using CommunityToolkit.Common.Deferred;
namespace Snap.Hutao.Control.TokenizingTextBox;
internal sealed class TokenItemRemovingEventArgs : DeferredCancelEventArgs
{
public TokenItemRemovingEventArgs(object item, TokenizingTextBoxItem token)
{
Item = item;
Token = token;
}
public object Item { get; private set; }
public TokenizingTextBoxItem Token { get; private set; }
}

View File

@@ -0,0 +1,951 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using CommunityToolkit.WinUI;
using CommunityToolkit.WinUI.Deferred;
using CommunityToolkit.WinUI.Helpers;
using Microsoft.UI.Input;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Automation.Peers;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using System.Collections.ObjectModel;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.Foundation.Metadata;
using Windows.System;
using Windows.UI.Core;
using DispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue;
using DispatcherQueuePriority = Microsoft.UI.Dispatching.DispatcherQueuePriority;
namespace Snap.Hutao.Control.TokenizingTextBox;
[DependencyProperty("AutoSuggestBoxStyle", typeof(Style))]
[DependencyProperty("AutoSuggestBoxTextBoxStyle", typeof(Style))]
[DependencyProperty("MaximumTokens", typeof(int), -1, nameof(OnMaximumTokensChanged))]
[DependencyProperty("PlaceholderText", typeof(string))]
[DependencyProperty("QueryIcon", typeof(IconSource))]
[DependencyProperty("SuggestedItemsSource", typeof(object))]
[DependencyProperty("SuggestedItemTemplate", typeof(DataTemplate))]
[DependencyProperty("SuggestedItemTemplateSelector", typeof(DataTemplateSelector))]
[DependencyProperty("SuggestedItemContainerStyle", typeof(Style))]
[DependencyProperty("TabNavigateBackOnArrow", typeof(bool), false)]
[DependencyProperty("Text", typeof(string), default, nameof(TextPropertyChanged))]
[DependencyProperty("TextMemberPath", typeof(string))]
[DependencyProperty("TokenItemTemplate", typeof(DataTemplate))]
[DependencyProperty("TokenItemTemplateSelector", typeof(DataTemplateSelector))]
[DependencyProperty("TokenDelimiter", typeof(string), " ")]
[DependencyProperty("TokenSpacing", typeof(double))]
[TemplatePart(Name = NormalState, Type = typeof(VisualState))]
[TemplatePart(Name = PointerOverState, Type = typeof(VisualState))]
[TemplatePart(Name = FocusedState, Type = typeof(VisualState))]
[TemplatePart(Name = UnfocusedState, Type = typeof(VisualState))]
[TemplatePart(Name = MaxReachedState, Type = typeof(VisualState))]
[TemplatePart(Name = MaxUnreachedState, Type = typeof(VisualState))]
[SuppressMessage("", "SA1124")]
internal partial class TokenizingTextBox : ListViewBase
{
public const string NormalState = "Normal";
public const string PointerOverState = "PointerOver";
public const string FocusedState = "Focused";
public const string UnfocusedState = "Unfocused";
public const string MaxReachedState = "MaxReachedState";
public const string MaxUnreachedState = "MaxUnreachedState";
private DispatcherQueue dispatcherQueue;
private InterspersedObservableCollection innerItemsSource;
private ITokenStringContainer currentTextEdit; // Don't update this directly outside of initialization, use UpdateCurrentTextEdit Method
private ITokenStringContainer lastTextEdit;
public TokenizingTextBox()
{
// Setup our base state of our collection
innerItemsSource = new InterspersedObservableCollection(new ObservableCollection<object>()); // TODO: Test this still will let us bind to ItemsSource in XAML?
currentTextEdit = lastTextEdit = new PretokenStringContainer(true);
innerItemsSource.Insert(innerItemsSource.Count, currentTextEdit);
ItemsSource = innerItemsSource;
//// TODO: Consolidate with callback below for ItemsSourceProperty changed?
DefaultStyleKey = typeof(TokenizingTextBox);
// TODO: Do we want to support ItemsSource better? Need to investigate how that works with adding...
RegisterPropertyChangedCallback(ItemsSourceProperty, ItemsSource_PropertyChanged);
PreviewKeyDown += TokenizingTextBox_PreviewKeyDown;
PreviewKeyUp += TokenizingTextBox_PreviewKeyUp;
CharacterReceived += TokenizingTextBox_CharacterReceived;
ItemClick += TokenizingTextBox_ItemClick;
dispatcherQueue = DispatcherQueue;
}
public event TypedEventHandler<Microsoft.UI.Xaml.Controls.AutoSuggestBox, AutoSuggestBoxTextChangedEventArgs>? TextChanged;
public event TypedEventHandler<Microsoft.UI.Xaml.Controls.AutoSuggestBox, AutoSuggestBoxSuggestionChosenEventArgs>? SuggestionChosen;
public event TypedEventHandler<Microsoft.UI.Xaml.Controls.AutoSuggestBox, AutoSuggestBoxQuerySubmittedEventArgs>? QuerySubmitted;
public event TypedEventHandler<TokenizingTextBox, TokenItemAddingEventArgs>? TokenItemAdding;
public event TypedEventHandler<TokenizingTextBox, object>? TokenItemAdded;
public event TypedEventHandler<TokenizingTextBox, TokenItemRemovingEventArgs>? TokenItemRemoving;
public event TypedEventHandler<TokenizingTextBox, object>? TokenItemRemoved;
private enum MoveDirection
{
Next,
Previous,
}
public static bool IsShiftPressed => InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);
public static bool IsXamlRootAvailable { get; } = ApiInformation.IsPropertyPresent("Windows.UI.Xaml.UIElement", "XamlRoot");
public static bool IsControlPressed => InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
public bool PauseTokenClearOnFocus { get; set; }
public bool IsClearingForClick { get; set; }
public string SelectedTokenText
{
get => PrepareSelectionForClipboard();
}
public void RaiseQuerySubmitted(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
QuerySubmitted?.Invoke(sender, args);
}
public void RaiseSuggestionChosen(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
{
SuggestionChosen?.Invoke(sender, args);
}
public void RaiseTextChanged(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
TextChanged?.Invoke(sender, args);
}
public void AddTokenItem(object data, bool atEnd = false)
{
_ = AddTokenAsync(data, atEnd);
}
public async ValueTask ClearAsync()
{
while (innerItemsSource.Count > 1)
{
if (ContainerFromItem(innerItemsSource[0]) is TokenizingTextBoxItem container)
{
if (!await RemoveTokenAsync(container, innerItemsSource[0]).ConfigureAwait(true))
{
// if a removal operation fails then stop the clear process
break;
}
}
}
// Clear the active pretoken string.
// Setting the text property directly avoids a delay when setting the text in the autosuggest box.
Text = string.Empty;
}
public async Task AddTokenAsync(object data, bool? atEnd = default)
{
if (MaximumTokens >= 0 && MaximumTokens <= innerItemsSource.ItemsSource.Count)
{
// No tokens for you
return;
}
if (data is string str && TokenItemAdding is not null)
{
TokenItemAddingEventArgs tiaea = new(str);
await TokenItemAdding.InvokeAsync(this, tiaea).ConfigureAwait(true);
if (tiaea.Cancel)
{
return;
}
if (tiaea.Item is not null)
{
data = tiaea.Item; // Transformed by event implementor
}
}
// If we've been typing in the last box, just add this to the end of our collection
if (atEnd == true || currentTextEdit == lastTextEdit)
{
innerItemsSource.InsertAt(innerItemsSource.Count - 1, data);
}
else
{
// Otherwise, we'll insert before our current box
ITokenStringContainer edit = currentTextEdit;
int index = innerItemsSource.IndexOf(edit);
// Insert our new data item at the location of our textbox
innerItemsSource.InsertAt(index, data);
// Remove our textbox
innerItemsSource.Remove(edit);
}
// Focus back to our end box as Outlook does.
TokenizingTextBoxItem last = (TokenizingTextBoxItem)ContainerFromItem(lastTextEdit);
last?.AutoSuggestTextBox.Focus(FocusState.Keyboard);
TokenItemAdded?.Invoke(this, data);
GuardAgainstPlaceholderTextLayoutIssue();
}
public async ValueTask RemoveAllSelectedTokens()
{
while (SelectedItems.Count > 0)
{
if (ContainerFromItem(SelectedItems[0]) is TokenizingTextBoxItem container)
{
if (IndexFromContainer(container) != Items.Count - 1)
{
// if its a text box, remove any selected text, and if its then empty remove the container, unless its focused
if (SelectedItems[0] is ITokenStringContainer)
{
TextBox asb = container.AutoSuggestTextBox;
// grab any selected text
string tempStr = asb.SelectionStart == 0
? string.Empty
: asb.Text[..asb.SelectionStart];
tempStr +=
asb.SelectionStart +
asb.SelectionLength < asb.Text.Length
? asb.Text[(asb.SelectionStart + asb.SelectionLength)..]
: string.Empty;
if (tempStr.Length is 0)
{
// Need to be careful not to remove the last item in the list
await RemoveTokenAsync(container).ConfigureAwait(true);
}
else
{
asb.Text = tempStr;
}
}
else
{
// if the item is a token just remove it.
await RemoveTokenAsync(container).ConfigureAwait(true);
}
}
else
{
if (SelectedItems.Count == 1)
{
// at this point we have one selection and its the default textbox.
// stop the iteration here
break;
}
}
}
}
}
public bool SelectPreviousItem(TokenizingTextBoxItem item)
{
return SelectNewItem(item, -1, i => i > 0);
}
public bool SelectNextItem(TokenizingTextBoxItem item)
{
return SelectNewItem(item, 1, i => i < Items.Count - 1);
}
public void SelectAllTokensAndText()
{
void SelectAllTokensAndTextCore()
{
this.SelectAllSafe();
// need to synchronize the select all and the focus behavior on the text box
// because there is no way to identify that the focus has been set from this point
// to avoid instantly clearing the selection of tokens
PauseTokenClearOnFocus = true;
foreach (object? item in Items)
{
if (item is ITokenStringContainer)
{
// grab any selected text
if (ContainerFromItem(item) is TokenizingTextBoxItem pretoken)
{
pretoken.AutoSuggestTextBox.SelectionStart = 0;
pretoken.AutoSuggestTextBox.SelectionLength = pretoken.AutoSuggestTextBox.Text.Length;
}
}
}
if (ContainerFromIndex(Items.Count - 1) is TokenizingTextBoxItem container)
{
container.Focus(FocusState.Programmatic);
}
}
_ = dispatcherQueue.EnqueueAsync(SelectAllTokensAndTextCore, DispatcherQueuePriority.Normal);
}
public void DeselectAllTokensAndText(TokenizingTextBoxItem? ignoreItem = default)
{
this.DeselectAll();
ClearAllTextSelections(ignoreItem);
}
protected void UpdateCurrentTextEdit(ITokenStringContainer edit)
{
currentTextEdit = edit;
Text = edit.Text; // Update our text property.
}
protected override AutomationPeer OnCreateAutomationPeer()
{
return new TokenizingTextBoxAutomationPeer(this);
}
/// <inheritdoc/>
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
MenuFlyoutItem selectAllMenuItem = new()
{
Text = "Select all",
};
selectAllMenuItem.Click += (s, e) => SelectAllTokensAndText();
MenuFlyout menuFlyout = new();
menuFlyout.Items.Add(selectAllMenuItem);
if (IsXamlRootAvailable && XamlRoot is not null)
{
menuFlyout.XamlRoot = XamlRoot;
}
ContextFlyout = menuFlyout;
}
/// <inheritdoc/>
protected override DependencyObject GetContainerForItemOverride()
{
return new TokenizingTextBoxItem();
}
/// <inheritdoc/>
protected override bool IsItemItsOwnContainerOverride(object item)
{
return item is TokenizingTextBoxItem;
}
/// <inheritdoc/>
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
if (element is TokenizingTextBoxItem tokenitem)
{
tokenitem.Owner = this;
tokenitem.ContentTemplateSelector = TokenItemTemplateSelector;
tokenitem.ContentTemplate = TokenItemTemplate;
tokenitem.ClearClicked -= TokenizingTextBoxItem_ClearClicked;
tokenitem.ClearClicked += TokenizingTextBoxItem_ClearClicked;
tokenitem.ClearAllAction -= TokenizingTextBoxItem_ClearAllAction;
tokenitem.ClearAllAction += TokenizingTextBoxItem_ClearAllAction;
tokenitem.GotFocus -= TokenizingTextBoxItem_GotFocus;
tokenitem.GotFocus += TokenizingTextBoxItem_GotFocus;
tokenitem.LostFocus -= TokenizingTextBoxItem_LostFocus;
tokenitem.LostFocus += TokenizingTextBoxItem_LostFocus;
MenuFlyout menuFlyout = new();
MenuFlyoutItem removeMenuItem = new()
{
Text = "Remove",
};
removeMenuItem.Click += (s, e) => TokenizingTextBoxItem_ClearClicked(tokenitem, default);
menuFlyout.Items.Add(removeMenuItem);
if (IsXamlRootAvailable && XamlRoot is not null)
{
menuFlyout.XamlRoot = XamlRoot;
}
MenuFlyoutItem selectAllMenuItem = new()
{
Text = "Select all",
};
selectAllMenuItem.Click += (s, e) => SelectAllTokensAndText();
menuFlyout.Items.Add(selectAllMenuItem);
tokenitem.ContextFlyout = menuFlyout;
}
}
private static void TextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TokenizingTextBox { currentTextEdit: { } } ttb)
{
if (e.NewValue is string newValue)
{
ttb.currentTextEdit.Text = newValue;
// Notify inner container of text change, see issue #4749
TokenizingTextBoxItem item = (TokenizingTextBoxItem)ttb.ContainerFromItem(ttb.currentTextEdit);
item?.UpdateText(ttb.currentTextEdit.Text);
}
}
}
private static void OnMaximumTokensChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TokenizingTextBox { MaximumTokens: >= 0 } ttb && e.NewValue is int newMaxTokens)
{
int tokenCount = ttb.innerItemsSource.ItemsSource.Count;
if (tokenCount > 0 && tokenCount > newMaxTokens)
{
int tokensToRemove = tokenCount - Math.Max(newMaxTokens, 0);
// Start at the end, remove any extra tokens.
for (int i = tokenCount; i > tokenCount - tokensToRemove; --i)
{
object? token = ttb.innerItemsSource.ItemsSource[i - 1];
if (token is not null)
{
// Force remove the items. No warning and no option to cancel.
ttb.innerItemsSource.Remove(token);
ttb.TokenItemRemoved?.Invoke(ttb, token);
}
}
}
}
}
private void ItemsSource_PropertyChanged(DependencyObject sender, DependencyProperty dp)
{
// If we're given a different ItemsSource, we need to wrap that collection in our helper class.
if (ItemsSource is { } and not InterspersedObservableCollection)
{
innerItemsSource = new(ItemsSource);
if (MaximumTokens >= 0 && innerItemsSource.ItemsSource.Count >= MaximumTokens)
{
// Reduce down to below the max as necessary.
int endCount = MaximumTokens > 0 ? MaximumTokens : 0;
for (int i = innerItemsSource.ItemsSource.Count - 1; i >= endCount; --i)
{
innerItemsSource.Remove(innerItemsSource[i]);
}
}
// Add our text box at the end of items and set its default value to our initial text, fix for #4749
currentTextEdit = lastTextEdit = new PretokenStringContainer(true) { Text = Text };
innerItemsSource.Insert(innerItemsSource.Count, currentTextEdit);
ItemsSource = innerItemsSource;
}
}
private void TokenizingTextBox_ItemClick(object sender, ItemClickEventArgs e)
{
// If the user taps an item in the list, make sure to clear any text selection as required
// Note, token selection is cleared by the listview default behavior
if (!IsControlPressed)
{
// Set class state flag to prevent click item being immediately deselected
IsClearingForClick = true;
ClearAllTextSelections(default);
}
}
private void TokenizingTextBox_PreviewKeyUp(object sender, KeyRoutedEventArgs e)
{
switch (e.Key)
{
case VirtualKey.Escape:
// Clear any selection and place the focus back into the text box
DeselectAllTokensAndText();
FocusPrimaryAutoSuggestBox();
break;
}
}
private void FocusPrimaryAutoSuggestBox()
{
if (Items?.Count > 0)
{
if (ContainerFromIndex(Items.Count - 1) is TokenizingTextBoxItem container)
{
container.Focus(FocusState.Programmatic);
}
}
}
private async void TokenizingTextBox_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
{
switch (e.Key)
{
case VirtualKey.C:
if (IsControlPressed)
{
CopySelectedToClipboard();
e.Handled = true;
return;
}
break;
case VirtualKey.X:
if (IsControlPressed)
{
CopySelectedToClipboard();
// now clear all selected tokens and text, or all if none are selected
await RemoveAllSelectedTokens().ConfigureAwait(false);
}
break;
// For moving between tokens
case VirtualKey.Left:
e.Handled = MoveFocusAndSelection(MoveDirection.Previous);
return;
case VirtualKey.Right:
e.Handled = MoveFocusAndSelection(MoveDirection.Next);
return;
case VirtualKey.A:
// modify the select-all behavior to ensure the text in the edit box gets selected.
if (IsControlPressed)
{
SelectAllTokensAndText();
e.Handled = true;
return;
}
break;
}
}
private async void TokenizingTextBox_CharacterReceived(UIElement sender, CharacterReceivedRoutedEventArgs args)
{
TokenizingTextBoxItem container = (TokenizingTextBoxItem)ContainerFromItem(currentTextEdit);
if (container is not null && !(GetFocusedElement().Equals(container.AutoSuggestTextBox) || char.IsControl(args.Character)))
{
if (SelectedItems.Count > 0)
{
int index = innerItemsSource.IndexOf(SelectedItems.First());
await RemoveAllSelectedTokens().ConfigureAwait(false);
void RemoveOldItems()
{
// If we're before the last textbox and it's empty, redirect focus to that one instead
if (index == innerItemsSource.Count - 1 && string.IsNullOrWhiteSpace(lastTextEdit.Text))
{
if (ContainerFromItem(lastTextEdit) is TokenizingTextBoxItem lastContainer)
{
lastContainer.UseCharacterAsUser = true; // Make sure we trigger a refresh of suggested items.
lastTextEdit.Text = string.Empty + args.Character;
UpdateCurrentTextEdit(lastTextEdit);
lastContainer.AutoSuggestTextBox.SelectionStart = 1; // Set position to after our new character inserted
lastContainer.AutoSuggestTextBox.Focus(FocusState.Keyboard);
}
}
else
{
//// Otherwise, create a new textbox for this text.
UpdateCurrentTextEdit(new PretokenStringContainer((string.Empty + args.Character).Trim())); // Trim so that 'space' isn't inserted and can be used to insert a new box.
innerItemsSource.Insert(index, currentTextEdit);
void Containerization()
{
if (ContainerFromIndex(index) is TokenizingTextBoxItem newContainer) // Should be our last text box
{
newContainer.UseCharacterAsUser = true; // Make sure we trigger a refresh of suggested items.
void WaitForLoad(object s, RoutedEventArgs eargs)
{
if (newContainer.AutoSuggestTextBox is not null)
{
newContainer.AutoSuggestTextBox.SelectionStart = 1; // Set position to after our new character inserted
newContainer.AutoSuggestTextBox.Focus(FocusState.Keyboard);
}
newContainer.Loaded -= WaitForLoad;
}
newContainer.AutoSuggestTextBoxLoaded += WaitForLoad;
}
}
// Need to wait for containerization
_ = DispatcherQueue.EnqueueAsync(Containerization, DispatcherQueuePriority.Normal);
}
}
// Wait for removal of old items
_ = DispatcherQueue.EnqueueAsync(RemoveOldItems, DispatcherQueuePriority.Normal);
}
else
{
// If no items are selected, send input to the last active string container.
// This code is only fires during an edgecase where an item is in the process of being deleted and the user inputs a character before the focus has been redirected to a string container.
if (innerItemsSource[^1] is ITokenStringContainer textToken)
{
if (ContainerFromIndex(Items.Count - 1) is TokenizingTextBoxItem last) // Should be our last text box
{
string text = last.AutoSuggestTextBox.Text;
int selectionStart = last.AutoSuggestTextBox.SelectionStart;
int position = selectionStart > text.Length ? text.Length : selectionStart;
textToken.Text = text[..position] + args.Character + text[position..];
last.AutoSuggestTextBox.SelectionStart = position + 1; // Set position to after our new character inserted
last.AutoSuggestTextBox.Focus(FocusState.Keyboard);
}
}
}
}
}
private object GetFocusedElement()
{
if (IsXamlRootAvailable && XamlRoot is not null)
{
return FocusManager.GetFocusedElement(XamlRoot);
}
else
{
return FocusManager.GetFocusedElement();
}
}
private void TokenizingTextBoxItem_GotFocus(object sender, RoutedEventArgs e)
{
// Keep track of our currently focused textbox
if (sender is TokenizingTextBoxItem { Content: ITokenStringContainer text })
{
UpdateCurrentTextEdit(text);
}
}
private void TokenizingTextBoxItem_LostFocus(object sender, RoutedEventArgs e)
{
// Keep track of our currently focused textbox
if (sender is TokenizingTextBoxItem { Content: ITokenStringContainer text } &&
string.IsNullOrWhiteSpace(text.Text) && text != lastTextEdit)
{
// We're leaving an inner textbox that's blank, so we'll remove it
innerItemsSource.Remove(text);
UpdateCurrentTextEdit(lastTextEdit);
GuardAgainstPlaceholderTextLayoutIssue();
}
}
private async ValueTask<bool> RemoveTokenAsync(TokenizingTextBoxItem item, object? data = null)
{
data ??= ItemFromContainer(item);
if (TokenItemRemoving is not null)
{
TokenItemRemovingEventArgs tirea = new(data, item);
await TokenItemRemoving.InvokeAsync(this, tirea).ConfigureAwait(true);
if (tirea.Cancel)
{
return false;
}
}
innerItemsSource.Remove(data);
TokenItemRemoved?.Invoke(this, data);
GuardAgainstPlaceholderTextLayoutIssue();
return true;
}
private void GuardAgainstPlaceholderTextLayoutIssue()
{
// If the *PlaceholderText is visible* on the last AutoSuggestBox, it can incorrectly layout itself
// when the *ASB has focus*. We think this is an optimization in the platform, but haven't been able to
// isolate a straight-reproduction of this issue outside of this control (though we have eliminated
// most Toolkit influences like ASB/TextBox Style, the InterspersedObservableCollection, etc...).
// The only Toolkit component involved here should be WrapPanel (which is a straight-forward Panel).
// We also know the ASB itself is adjusting it's size correctly, it's the inner component.
//
// To combat this issue:
// We toggle the visibility of the Placeholder ContentControl in order to force it's layout to update properly
FrameworkElement? placeholder = ContainerFromItem(lastTextEdit)?.FindDescendant("PlaceholderTextContentPresenter");
if (placeholder?.Visibility == Visibility.Visible)
{
placeholder.Visibility = Visibility.Collapsed;
// After we ensure we've hid the control, make it visible again (this is imperceptible to the user).
_ = CompositionTargetHelper.ExecuteAfterCompositionRenderingAsync(() =>
{
placeholder.Visibility = Visibility.Visible;
});
}
}
private bool MoveFocusAndSelection(MoveDirection direction)
{
bool retVal = false;
if (GetCurrentContainerItem() is { } currentContainerItem)
{
object? currentItem = ItemFromContainer(currentContainerItem);
int previousIndex = Items.IndexOf(currentItem);
int index = previousIndex;
if (direction == MoveDirection.Previous)
{
if (previousIndex > 0)
{
index -= 1;
}
else
{
if (TabNavigateBackOnArrow)
{
FocusManager.TryMoveFocus(FocusNavigationDirection.Previous, new FindNextElementOptions
{
SearchRoot = XamlRoot.Content,
});
}
retVal = true;
}
}
else if (direction == MoveDirection.Next)
{
if (previousIndex < Items.Count - 1)
{
index += 1;
}
}
// Only do stuff if the index is actually changing
if (index != previousIndex)
{
if (ContainerFromIndex(index) is TokenizingTextBoxItem newItem)
{
// Check for the new item being a text control.
// this must happen before focus is set to avoid seeing the caret
// jump in come cases
if (Items[index] is ITokenStringContainer && !IsShiftPressed)
{
newItem.AutoSuggestTextBox.SelectionLength = 0;
newItem.AutoSuggestTextBox.SelectionStart = direction == MoveDirection.Next
? 0
: newItem.AutoSuggestTextBox.Text.Length;
}
newItem.Focus(FocusState.Keyboard);
// if no control keys are selected then the selection also becomes just this item
if (IsShiftPressed)
{
// What we do here depends on where the selection started
// if the previous item is between the start and new position then we add the new item to the selected range
// if the new item is between the start and the previous position then we remove the previous position
int newDistance = Math.Abs(SelectedIndex - index);
int oldDistance = Math.Abs(SelectedIndex - previousIndex);
if (newDistance > oldDistance)
{
SelectedItems.Add(Items[index]);
}
else
{
SelectedItems.Remove(Items[previousIndex]);
}
}
else if (!IsControlPressed)
{
SelectedIndex = index;
// This looks like a bug in the underlying ListViewBase control.
// Might need to be reviewed if the base behavior is fixed
// When two consecutive items are selected and the navigation moves between them,
// the first time that happens the old focused item is not unselected
if (SelectedItems.Count > 1)
{
SelectedItems.Clear();
SelectedIndex = index;
}
}
retVal = true;
}
}
}
return retVal;
}
private TokenizingTextBoxItem? GetCurrentContainerItem()
{
if (IsXamlRootAvailable && XamlRoot is not null)
{
return (TokenizingTextBoxItem)FocusManager.GetFocusedElement(XamlRoot);
}
else
{
return (TokenizingTextBoxItem)FocusManager.GetFocusedElement();
}
}
private void ClearAllTextSelections(TokenizingTextBoxItem? ignoreItem)
{
// Clear any selection in the text box
foreach (object? item in Items)
{
if (item is ITokenStringContainer)
{
if (ContainerFromItem(item) is TokenizingTextBoxItem container)
{
if (container != ignoreItem)
{
container.AutoSuggestTextBox.SelectionLength = 0;
}
}
}
}
}
private bool SelectNewItem(TokenizingTextBoxItem item, int increment, Func<int, bool> testFunc)
{
// find the item in the list
int currentIndex = IndexFromContainer(item);
// Select previous token item (if there is one).
if (testFunc(currentIndex))
{
if (ContainerFromItem(Items[currentIndex + increment]) is ListViewItem newItem)
{
newItem.Focus(FocusState.Keyboard);
SelectedItems.Add(Items[currentIndex + increment]);
return true;
}
}
return false;
}
private async void TokenizingTextBoxItem_ClearAllAction(TokenizingTextBoxItem sender, RoutedEventArgs args)
{
// find the first item selected
int newSelectedIndex = -1;
if (SelectedRanges.Count > 0)
{
newSelectedIndex = SelectedRanges[0].FirstIndex - 1;
}
await RemoveAllSelectedTokens().ConfigureAwait(true);
SelectedIndex = newSelectedIndex;
if (newSelectedIndex is -1)
{
newSelectedIndex = Items.Count - 1;
}
// focus the item prior to the first selected item
if (ContainerFromIndex(newSelectedIndex) is TokenizingTextBoxItem container)
{
container.Focus(FocusState.Keyboard);
}
}
private async void TokenizingTextBoxItem_ClearClicked(TokenizingTextBoxItem sender, RoutedEventArgs? args)
{
await RemoveTokenAsync(sender).ConfigureAwait(true);
}
private void CopySelectedToClipboard()
{
DataPackage dataPackage = new()
{
RequestedOperation = DataPackageOperation.Copy,
};
string tokenString = PrepareSelectionForClipboard();
if (!string.IsNullOrEmpty(tokenString))
{
dataPackage.SetText(tokenString);
Clipboard.SetContent(dataPackage);
}
}
private string PrepareSelectionForClipboard()
{
string tokenString = string.Empty;
bool addSeparator = false;
// Copy all items if none selected (and no text selected)
foreach (object? item in SelectedItems.Count > 0 ? SelectedItems : Items)
{
if (addSeparator)
{
tokenString += TokenDelimiter;
}
else
{
addSeparator = true;
}
if (item is ITokenStringContainer)
{
// grab any selected text
if (ContainerFromItem(item) is TokenizingTextBoxItem { AutoSuggestTextBox: { } textBox })
{
tokenString += textBox.Text.Substring(
textBox.SelectionStart,
textBox.SelectionLength);
}
}
else
{
tokenString += item.ToString();
}
}
return tokenString;
}
}

View File

@@ -0,0 +1,172 @@
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cw="using:CommunityToolkit.WinUI"
xmlns:cwc="using:CommunityToolkit.WinUI.Controls"
xmlns:shct="using:Snap.Hutao.Control.TokenizingTextBox"
xmlns:win="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ms-appx:///Control/TokenizingTextBox/TokenizingTextBoxItem.xaml"/>
</ResourceDictionary.MergedDictionaries>
<!-- Resources for TokenizingTextBox -->
<Thickness x:Key="TokenizingTextBoxPadding">3,2,3,2</Thickness>
<Thickness x:Key="TokenizingTextBoxPresenterMargin">0,0,6,0</Thickness>
<x:Double x:Key="TokenizingTextBoxTokenSpacing">2</x:Double>
<shct:TokenizingTextBoxStyleSelector
x:Key="TokenizingTextBoxStyleSelector"
TextStyle="{StaticResource TokenizingTextBoxItemTextStyle}"
TokenStyle="{StaticResource TokenizingTextBoxItemTokenStyle}"/>
<!-- Default style for TokenizingTextBox -->
<Style BasedOn="{StaticResource DefaultTokenizingTextBoxStyle}" TargetType="shct:TokenizingTextBox"/>
<Style x:Key="DefaultTokenizingTextBoxStyle" TargetType="shct:TokenizingTextBox">
<Setter Property="AutoSuggestBoxTextBoxStyle" Value="{StaticResource TokenizingTextBoxTextBoxStyle}"/>
<Setter Property="Foreground" Value="{ThemeResource TextControlForeground}"/>
<Setter Property="Background" Value="{ThemeResource TextControlBackground}"/>
<Setter Property="BorderBrush" Value="{ThemeResource TextControlBorderBrush}"/>
<Setter Property="BorderThickness" Value="{StaticResource TextControlBorderThemeThickness}"/>
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="TabNavigation" Value="Once"/>
<win:Setter Property="IsSwipeEnabled" Value="False"/>
<Setter Property="CornerRadius" Value="{ThemeResource ControlCornerRadius}"/>
<Setter Property="Padding" Value="{StaticResource TokenizingTextBoxPadding}"/>
<Setter Property="SelectionMode" Value="Extended"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
<Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled"/>
<win:Setter Property="ScrollViewer.IsHorizontalRailEnabled" Value="True"/>
<Setter Property="ScrollViewer.VerticalScrollMode" Value="Enabled"/>
<win:Setter Property="ScrollViewer.IsVerticalRailEnabled" Value="True"/>
<Setter Property="ScrollViewer.ZoomMode" Value="Disabled"/>
<win:Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>
<Setter Property="ScrollViewer.BringIntoViewOnFocusChange" Value="True"/>
<Setter Property="TokenSpacing" Value="{StaticResource TokenizingTextBoxTokenSpacing}"/>
<Setter Property="UseSystemFocusVisuals" Value="{StaticResource UseSystemFocusVisuals}"/>
<Setter Property="IsItemClickEnabled" Value="True"/>
<win:Setter Property="ItemContainerTransitions">
<Setter.Value>
<TransitionCollection/>
</Setter.Value>
</win:Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<cwc:WrapPanel
cw:FrameworkElementExtensions.AncestorType="shct:TokenizingTextBox"
HorizontalSpacing="{Binding (cw:FrameworkElementExtensions.Ancestor).TokenSpacing, RelativeSource={RelativeSource Self}}"
StretchChild="Last"
VerticalSpacing="{Binding (cw:FrameworkElementExtensions.Ancestor).TokenSpacing, RelativeSource={RelativeSource Self}}"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemContainerStyleSelector" Value="{StaticResource TokenizingTextBoxStyleSelector}"/>
<Setter Property="Template" Value="{StaticResource TokenizingTextBoxTemplate}"/>
</Style>
<ControlTemplate x:Key="TokenizingTextBoxTemplate" TargetType="shct:TokenizingTextBox">
<Grid Name="RootPanel">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ContentPresenter
Margin="{ThemeResource TextBoxTopHeaderMargin}"
VerticalAlignment="Top"
Content="{TemplateBinding Header}"
ContentTemplate="{TemplateBinding HeaderTemplate}"
FontWeight="Normal"
Foreground="{ThemeResource TextControlHeaderForeground}"
TextWrapping="Wrap"
Transitions="{TemplateBinding HeaderTransitions}"/>
<Border
x:Name="BackgroundVisual"
Grid.Row="1"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}"/>
<Border
x:Name="FocusVisual"
Grid.Row="1"
Background="{ThemeResource TextControlBackgroundFocused}"
BorderBrush="{ThemeResource TextControlBorderBrushFocused}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}"
Opacity="0"/>
<!-- Background in WinUI is TextControlBackgroundFocused, but that uses a different resource in WinUI than system -->
<ScrollViewer
x:Name="ScrollViewer"
Grid.Row="1"
win:AutomationProperties.AccessibilityView="Raw"
win:IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}"
win:IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}"
win:IsHorizontalScrollChainingEnabled="{TemplateBinding ScrollViewer.IsHorizontalScrollChainingEnabled}"
win:IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}"
win:IsVerticalScrollChainingEnabled="{TemplateBinding ScrollViewer.IsVerticalScrollChainingEnabled}"
BringIntoViewOnFocusChange="{TemplateBinding ScrollViewer.BringIntoViewOnFocusChange}"
HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}"
HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}"
TabNavigation="{TemplateBinding TabNavigation}"
VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}"
VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}"
ZoomMode="{TemplateBinding ScrollViewer.ZoomMode}">
<ItemsPresenter Margin="{StaticResource TokenizingTextBoxPresenterMargin}" Padding="{TemplateBinding Padding}"/>
</ScrollViewer>
<ContentPresenter
Grid.Row="2"
VerticalAlignment="Top"
Content="{TemplateBinding Footer}"
ContentTemplate="{TemplateBinding FooterTemplate}"
FontWeight="Normal"
TextWrapping="Wrap"
Transitions="{TemplateBinding FooterTransitions}"/>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Disabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundVisual" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundVisual" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushDisabled}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Normal"/>
<VisualState x:Name="PointerOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundVisual" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushPointerOver}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundVisual" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundPointerOver}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused">
<VisualState.Setters>
<Setter Target="BackgroundVisual.BorderBrush" Value="Transparent"/>
<Setter Target="FocusVisual.BorderThickness" Value="{ThemeResource TextControlBorderThemeThicknessFocused}"/>
<Setter Target="FocusVisual.Opacity" Value="1"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Unfocused"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</ControlTemplate>
</ResourceDictionary>

View File

@@ -0,0 +1,84 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Xaml.Automation;
using Microsoft.UI.Xaml.Automation.Peers;
using Microsoft.UI.Xaml.Automation.Provider;
using Microsoft.UI.Xaml.Controls;
namespace Snap.Hutao.Control.TokenizingTextBox;
internal class TokenizingTextBoxAutomationPeer : ListViewBaseAutomationPeer, IValueProvider
{
public TokenizingTextBoxAutomationPeer(TokenizingTextBox owner)
: base(owner)
{
}
public bool IsReadOnly => !OwningTokenizingTextBox.IsEnabled;
public string Value => OwningTokenizingTextBox.Text;
private TokenizingTextBox OwningTokenizingTextBox
{
get => (TokenizingTextBox)Owner;
}
public void SetValue(string value)
{
if (IsReadOnly)
{
throw new ElementNotEnabledException($"Could not set the value of the {nameof(TokenizingTextBox)} ");
}
OwningTokenizingTextBox.Text = value;
}
protected override string GetClassNameCore()
{
return Owner.GetType().Name;
}
protected override string GetNameCore()
{
string name = OwningTokenizingTextBox.Name;
if (!string.IsNullOrWhiteSpace(name))
{
return name;
}
name = AutomationProperties.GetName(OwningTokenizingTextBox);
return !string.IsNullOrWhiteSpace(name) ? name : base.GetNameCore();
}
protected override object GetPatternCore(PatternInterface patternInterface)
{
return patternInterface switch
{
PatternInterface.Value => this,
_ => base.GetPatternCore(patternInterface),
};
}
protected override IList<AutomationPeer> GetChildrenCore()
{
TokenizingTextBox owner = OwningTokenizingTextBox;
ItemCollection items = owner.Items;
if (items.Count <= 0)
{
return default!;
}
List<AutomationPeer> peers = new(items.Count);
for (int i = 0; i < items.Count; i++)
{
if (owner.ContainerFromIndex(i) is TokenizingTextBoxItem element)
{
peers.Add(FromElement(element) ?? CreatePeerForElement(element));
}
}
return peers;
}
}

View File

@@ -0,0 +1,480 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using CommunityToolkit.WinUI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Windows.Foundation;
using Windows.System;
namespace Snap.Hutao.Control.TokenizingTextBox;
[DependencyProperty("ClearButtonStyle", typeof(Style))]
[DependencyProperty("Owner", typeof(TokenizingTextBox))]
[TemplatePart(Name = PART_ClearButton, Type = typeof(ButtonBase))] //// Token case
[TemplatePart(Name = PART_AutoSuggestBox, Type = typeof(Microsoft.UI.Xaml.Controls.AutoSuggestBox))] //// String case
[TemplatePart(Name = PART_TokensCounter, Type = typeof(TextBlock))]
[SuppressMessage("", "SA1124")]
internal partial class TokenizingTextBoxItem : ListViewItem
{
private const string PART_ClearButton = "PART_RemoveButton";
private const string PART_AutoSuggestBox = "PART_AutoSuggestBox";
private const string PART_TokensCounter = "PART_TokensCounter";
private const string QueryButton = "QueryButton";
private Microsoft.UI.Xaml.Controls.AutoSuggestBox autoSuggestBox;
private TextBox autoSuggestTextBox;
private Button clearButton;
private bool isSelectedFocusOnFirstCharacter;
private bool isSelectedFocusOnLastCharacter;
public TokenizingTextBoxItem()
{
DefaultStyleKey = typeof(TokenizingTextBoxItem);
// TODO: only add these if token?
RightTapped += TokenizingTextBoxItem_RightTapped;
KeyDown += TokenizingTextBoxItem_KeyDown;
}
public event TypedEventHandler<TokenizingTextBoxItem, RoutedEventArgs>? AutoSuggestTextBoxLoaded;
public event TypedEventHandler<TokenizingTextBoxItem, RoutedEventArgs>? ClearClicked;
public event TypedEventHandler<TokenizingTextBoxItem, RoutedEventArgs>? ClearAllAction;
public TextBox AutoSuggestTextBox { get => autoSuggestTextBox; }
public bool UseCharacterAsUser { get; set; }
private bool IsCaretAtStart
{
get => autoSuggestTextBox?.SelectionStart is 0;
}
private bool IsCaretAtEnd
{
get => autoSuggestTextBox?.SelectionStart == autoSuggestTextBox?.Text.Length || autoSuggestTextBox?.SelectionStart + autoSuggestTextBox?.SelectionLength == autoSuggestTextBox?.Text.Length;
}
private bool IsAllSelected
{
get => autoSuggestTextBox?.SelectedText == autoSuggestTextBox?.Text && !string.IsNullOrEmpty(autoSuggestTextBox?.Text);
}
// Called to update text by link:TokenizingTextBox.Properties.cs:TextPropertyChanged
public void UpdateText(string text)
{
if (autoSuggestBox is not null)
{
autoSuggestBox.Text = text;
}
else
{
void WaitForLoad(object s, RoutedEventArgs eargs)
{
if (autoSuggestTextBox is not null)
{
autoSuggestTextBox.Text = text;
}
AutoSuggestTextBoxLoaded -= WaitForLoad;
}
AutoSuggestTextBoxLoaded += WaitForLoad;
}
}
/// <inheritdoc/>
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (GetTemplateChild(PART_AutoSuggestBox) is Microsoft.UI.Xaml.Controls.AutoSuggestBox suggestbox)
{
OnApplyTemplateAutoSuggestBox(suggestbox);
}
if (clearButton is not null)
{
clearButton.Click -= ClearButton_Click;
}
clearButton = (Button)GetTemplateChild(PART_ClearButton);
if (clearButton is not null)
{
clearButton.Click += ClearButton_Click;
}
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
ClearClicked?.Invoke(this, e);
}
private void TokenizingTextBoxItem_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
ContextFlyout.ShowAt(this);
}
private void TokenizingTextBoxItem_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (Content is not ITokenStringContainer)
{
// We only want to 'remove' our token if we're not a textbox.
switch (e.Key)
{
case VirtualKey.Back:
case VirtualKey.Delete:
{
ClearAllAction?.Invoke(this, e);
break;
}
}
}
}
/// Called from <see cref="OnApplyTemplate"/>
private void OnApplyTemplateAutoSuggestBox(Microsoft.UI.Xaml.Controls.AutoSuggestBox auto)
{
if (autoSuggestBox is not null)
{
autoSuggestBox.Loaded -= OnASBLoaded;
autoSuggestBox.QuerySubmitted -= AutoSuggestBox_QuerySubmitted;
autoSuggestBox.SuggestionChosen -= AutoSuggestBox_SuggestionChosen;
autoSuggestBox.TextChanged -= AutoSuggestBox_TextChanged;
autoSuggestBox.PointerEntered -= AutoSuggestBox_PointerEntered;
autoSuggestBox.PointerExited -= AutoSuggestBox_PointerExited;
autoSuggestBox.PointerCanceled -= AutoSuggestBox_PointerExited;
autoSuggestBox.PointerCaptureLost -= AutoSuggestBox_PointerExited;
autoSuggestBox.GotFocus -= AutoSuggestBox_GotFocus;
autoSuggestBox.LostFocus -= AutoSuggestBox_LostFocus;
// Remove any previous QueryIcon
autoSuggestBox.QueryIcon = default;
}
autoSuggestBox = auto;
if (autoSuggestBox is not null)
{
autoSuggestBox.Loaded += OnASBLoaded;
autoSuggestBox.QuerySubmitted += AutoSuggestBox_QuerySubmitted;
autoSuggestBox.SuggestionChosen += AutoSuggestBox_SuggestionChosen;
autoSuggestBox.TextChanged += AutoSuggestBox_TextChanged;
autoSuggestBox.PointerEntered += AutoSuggestBox_PointerEntered;
autoSuggestBox.PointerExited += AutoSuggestBox_PointerExited;
autoSuggestBox.PointerCanceled += AutoSuggestBox_PointerExited;
autoSuggestBox.PointerCaptureLost += AutoSuggestBox_PointerExited;
autoSuggestBox.GotFocus += AutoSuggestBox_GotFocus;
autoSuggestBox.LostFocus += AutoSuggestBox_LostFocus;
// Setup a binding to the QueryIcon of the Parent if we're the last box.
if (Content is ITokenStringContainer str)
{
// We need to set our initial text in all cases.
autoSuggestBox.Text = str.Text;
// We only set/bind some properties on the last textbox to mimic the autosuggestbox look
if (str.IsLast)
{
// Workaround for https://github.com/microsoft/microsoft-ui-xaml/issues/2568
if (Owner.QueryIcon is FontIconSource fis &&
fis.ReadLocalValue(FontIconSource.FontSizeProperty) == DependencyProperty.UnsetValue)
{
// This can be expensive, could we optimize?
// Also, this is changing the FontSize on the IconSource (which could be shared?)
fis.FontSize = Owner.TryFindResource("TokenizingTextBoxIconFontSize") as double? ?? 16;
}
Binding iconBinding = new()
{
Source = Owner,
Path = new PropertyPath(nameof(Owner.QueryIcon)),
RelativeSource = new()
{
Mode = RelativeSourceMode.TemplatedParent,
},
};
IconSourceElement iconSourceElement = new();
iconSourceElement.SetBinding(IconSourceElement.IconSourceProperty, iconBinding);
autoSuggestBox.QueryIcon = iconSourceElement;
}
}
}
}
private async void AutoSuggestBox_QuerySubmitted(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
Owner.RaiseQuerySubmitted(sender, args);
object? chosenItem = default;
if (args.ChosenSuggestion is not null)
{
chosenItem = args.ChosenSuggestion;
}
else if (!string.IsNullOrWhiteSpace(args.QueryText))
{
chosenItem = args.QueryText;
}
if (chosenItem is not null)
{
await Owner.AddTokenAsync(chosenItem).ConfigureAwait(true); // TODO: Need to pass index?
sender.Text = string.Empty;
Owner.Text = string.Empty;
sender.Focus(FocusState.Programmatic);
}
}
private void AutoSuggestBox_SuggestionChosen(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
{
Owner.RaiseSuggestionChosen(sender, args);
}
private void AutoSuggestBox_TextChanged(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
if (sender.Text is null)
{
return;
}
if (!EqualityComparer<string>.Default.Equals(sender.Text, Owner.Text))
{
Owner.Text = sender.Text; // Update parent text property, if different
}
// Override our programmatic manipulation as we're redirecting input for the user
if (UseCharacterAsUser)
{
UseCharacterAsUser = false;
args.Reason = AutoSuggestionBoxTextChangeReason.UserInput;
}
Owner.RaiseTextChanged(sender, args);
string t = sender.Text?.Trim() ?? string.Empty;
// Look for Token Delimiters to create new tokens when text changes.
if (!string.IsNullOrEmpty(Owner.TokenDelimiter) && t.Contains(Owner.TokenDelimiter, StringComparison.OrdinalIgnoreCase))
{
bool lastDelimited = t[^1] == Owner.TokenDelimiter[0];
string[] tokens = t.Split(Owner.TokenDelimiter);
int numberToProcess = lastDelimited ? tokens.Length : tokens.Length - 1;
for (int position = 0; position < numberToProcess; position++)
{
string token = tokens[position];
token = token.Trim();
if (token.Length > 0)
{
_ = Owner.AddTokenAsync(token); //// TODO: Pass Index?
}
}
if (lastDelimited)
{
sender.Text = string.Empty;
}
else
{
sender.Text = tokens[^1].Trim();
}
}
}
private void AutoSuggestBox_PointerEntered(object sender, PointerRoutedEventArgs e)
{
VisualStateManager.GoToState(Owner, TokenizingTextBox.PointerOverState, true);
}
private void AutoSuggestBox_PointerExited(object sender, PointerRoutedEventArgs e)
{
VisualStateManager.GoToState(Owner, TokenizingTextBox.NormalState, true);
}
private void AutoSuggestBox_LostFocus(object sender, RoutedEventArgs e)
{
VisualStateManager.GoToState(Owner, TokenizingTextBox.UnfocusedState, true);
}
private void AutoSuggestBox_GotFocus(object sender, RoutedEventArgs e)
{
// Verify if the usual behavior of clearing token selection is required
if (Owner.PauseTokenClearOnFocus == false && !TokenizingTextBox.IsShiftPressed)
{
// Clear any selected tokens
Owner.DeselectAll();
}
Owner.PauseTokenClearOnFocus = false;
VisualStateManager.GoToState(Owner, TokenizingTextBox.FocusedState, true);
}
private void OnASBLoaded(object sender, RoutedEventArgs e)
{
if (autoSuggestTextBox is not null)
{
autoSuggestTextBox.PreviewKeyDown -= AutoSuggestTextBox_PreviewKeyDown;
autoSuggestTextBox.TextChanging -= AutoSuggestTextBox_TextChangingAsync;
autoSuggestTextBox.SelectionChanged -= AutoSuggestTextBox_SelectionChanged;
autoSuggestTextBox.SelectionChanging -= AutoSuggestTextBox_SelectionChanging;
}
autoSuggestTextBox ??= autoSuggestBox.FindDescendant<TextBox>()!;
UpdateQueryIconVisibility();
UpdateTokensCounter(this);
// Local function for Selection changed
void AutoSuggestTextBox_SelectionChanged(object box, RoutedEventArgs args)
{
if (!(IsAllSelected || TokenizingTextBox.IsShiftPressed || Owner.IsClearingForClick))
{
Owner.DeselectAllTokensAndText(this);
}
// Ensure flag is always reset
Owner.IsClearingForClick = false;
}
// local function for clearing selection on interaction with text box
async void AutoSuggestTextBox_TextChangingAsync(TextBox o, TextBoxTextChangingEventArgs args)
{
// remove any selected tokens.
if (Owner.SelectedItems.Count > 1)
{
await Owner.RemoveAllSelectedTokens().ConfigureAwait(true);
}
}
if (autoSuggestTextBox is not null)
{
autoSuggestTextBox.PreviewKeyDown += AutoSuggestTextBox_PreviewKeyDown;
autoSuggestTextBox.TextChanging += AutoSuggestTextBox_TextChangingAsync;
autoSuggestTextBox.SelectionChanged += AutoSuggestTextBox_SelectionChanged;
autoSuggestTextBox.SelectionChanging += AutoSuggestTextBox_SelectionChanging;
AutoSuggestTextBoxLoaded?.Invoke(this, e);
}
}
private void AutoSuggestTextBox_SelectionChanging(TextBox sender, TextBoxSelectionChangingEventArgs args)
{
isSelectedFocusOnFirstCharacter = args.SelectionLength > 0 && args.SelectionStart is 0 && autoSuggestTextBox.SelectionStart > 0;
isSelectedFocusOnLastCharacter =
//// see if we are NOW on the last character.
//// test if the new selection includes the last character, and the current selection doesn't
(args.SelectionStart + args.SelectionLength == autoSuggestTextBox.Text.Length) &&
(autoSuggestTextBox.SelectionStart + autoSuggestTextBox.SelectionLength != autoSuggestTextBox.Text.Length);
}
private void AutoSuggestTextBox_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
{
if (IsCaretAtStart &&
(e.Key is VirtualKey.Back ||
e.Key is VirtualKey.Left))
{
// if the back key is pressed and there is any selection in the text box then the text box can handle it
if ((e.Key is VirtualKey.Left && isSelectedFocusOnFirstCharacter) ||
autoSuggestTextBox.SelectionLength is 0)
{
if (Owner.SelectPreviousItem(this))
{
if (!TokenizingTextBox.IsShiftPressed)
{
// Clear any text box selection
autoSuggestTextBox.SelectionLength = 0;
}
e.Handled = true;
}
}
}
else if (IsCaretAtEnd && e.Key is VirtualKey.Right)
{
// if the back key is pressed and there is any selection in the text box then the text box can handle it
if (isSelectedFocusOnLastCharacter || autoSuggestTextBox.SelectionLength is 0)
{
if (Owner.SelectNextItem(this))
{
if (!TokenizingTextBox.IsShiftPressed)
{
// Clear any text box selection
autoSuggestTextBox.SelectionLength = 0;
}
e.Handled = true;
}
}
}
else if (e.Key is VirtualKey.A && TokenizingTextBox.IsControlPressed)
{
// Need to provide this shortcut from the textbox only, as ListViewBase will do it for us on token.
Owner.SelectAllTokensAndText();
}
}
private void UpdateTokensCounter(TokenizingTextBoxItem ttbi)
{
if (autoSuggestBox?.FindDescendant(PART_TokensCounter) is TextBlock maxTokensCounter)
{
void OnTokenCountChanged(TokenizingTextBox ttb, object? value = default)
{
if (ttb.ItemsSource is InterspersedObservableCollection itemsSource)
{
int currentTokens = itemsSource.ItemsSource.Count;
int maxTokens = ttb.MaximumTokens;
maxTokensCounter.Text = $"{currentTokens}/{maxTokens}";
maxTokensCounter.Visibility = Visibility.Visible;
string targetState = (currentTokens >= maxTokens)
? TokenizingTextBox.MaxReachedState
: TokenizingTextBox.MaxUnreachedState;
VisualStateManager.GoToState(autoSuggestTextBox, targetState, true);
}
}
ttbi.Owner.TokenItemAdded -= OnTokenCountChanged;
ttbi.Owner.TokenItemRemoved -= OnTokenCountChanged;
if (Content is ITokenStringContainer { IsLast: true } str && ttbi is { Owner.MaximumTokens: >= 0 })
{
ttbi.Owner.TokenItemAdded += OnTokenCountChanged;
ttbi.Owner.TokenItemRemoved += OnTokenCountChanged;
OnTokenCountChanged(ttbi.Owner);
}
else
{
maxTokensCounter.Visibility = Visibility.Collapsed;
maxTokensCounter.Text = string.Empty;
}
}
}
private void UpdateQueryIconVisibility()
{
if (autoSuggestBox.FindDescendant(QueryButton) is Button queryButton)
{
if (Owner.QueryIcon is not null)
{
queryButton.Visibility = Visibility.Visible;
}
else
{
queryButton.Visibility = Visibility.Collapsed;
}
}
}
}

View File

@@ -0,0 +1,837 @@
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
xmlns:shct="using:Snap.Hutao.Control.TokenizingTextBox"
xmlns:win="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
<StaticResource x:Key="TokenItemBackground" ResourceKey="ControlFillColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBackgroundPointerOver" ResourceKey="ControlFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBackgroundPressed" ResourceKey="ControlFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBackgroundSelected" ResourceKey="AccentFillColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBackgroundPointerOverSelected" ResourceKey="AccentFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBackgroundPressedSelected" ResourceKey="AccentFillColorTertiaryBrush"/>
<StaticResource x:Key="TokenItemBorderBrush" ResourceKey="ControlStrokeColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPointerOver" ResourceKey="ControlStrokeColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPressed" ResourceKey="ControlStrokeColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushSelected" ResourceKey="AccentFillColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPointerOverSelected" ResourceKey="AccentFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPressedSelected" ResourceKey="AccentFillColorTertiaryBrush"/>
<StaticResource x:Key="TokenItemForeground" ResourceKey="TextFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPointerOver" ResourceKey="TextFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPressed" ResourceKey="TextFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemForegroundSelected" ResourceKey="TextOnAccentFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPointerOverSelected" ResourceKey="TextOnAccentFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPressedSelected" ResourceKey="TextOnAccentFillColorSecondaryBrush"/>
<Thickness x:Key="TokenItemBorderThickness">1</Thickness>
</ResourceDictionary>
<ResourceDictionary x:Key="Light">
<StaticResource x:Key="TokenItemBackground" ResourceKey="ControlFillColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBackgroundPointerOver" ResourceKey="ControlFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBackgroundPressed" ResourceKey="ControlFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBackgroundSelected" ResourceKey="AccentFillColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBackgroundPointerOverSelected" ResourceKey="AccentFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBackgroundPressedSelected" ResourceKey="AccentFillColorTertiaryBrush"/>
<StaticResource x:Key="TokenItemBorderBrush" ResourceKey="ControlStrokeColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPointerOver" ResourceKey="ControlStrokeColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPressed" ResourceKey="ControlStrokeColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushSelected" ResourceKey="AccentFillColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPointerOverSelected" ResourceKey="AccentFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPressedSelected" ResourceKey="AccentFillColorTertiaryBrush"/>
<StaticResource x:Key="TokenItemForeground" ResourceKey="TextFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPointerOver" ResourceKey="TextFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPressed" ResourceKey="TextFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemForegroundSelected" ResourceKey="TextOnAccentFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPointerOverSelected" ResourceKey="TextOnAccentFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPressedSelected" ResourceKey="TextOnAccentFillColorSecondaryBrush"/>
<Thickness x:Key="TokenItemBorderThickness">1</Thickness>
</ResourceDictionary>
<ResourceDictionary x:Key="HighContrast">
<StaticResource x:Key="TokenItemBackground" ResourceKey="ControlFillColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBackgroundPointerOver" ResourceKey="ControlFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBackgroundPressed" ResourceKey="ControlFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBackgroundSelected" ResourceKey="AccentFillColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBackgroundPointerOverSelected" ResourceKey="AccentFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBackgroundPressedSelected" ResourceKey="AccentFillColorTertiaryBrush"/>
<StaticResource x:Key="TokenItemBorderBrush" ResourceKey="ControlStrokeColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPointerOver" ResourceKey="ControlStrokeColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPressed" ResourceKey="ControlStrokeColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushSelected" ResourceKey="AccentFillColorDefaultBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPointerOverSelected" ResourceKey="AccentFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemBorderBrushPressedSelected" ResourceKey="AccentFillColorTertiaryBrush"/>
<StaticResource x:Key="TokenItemForeground" ResourceKey="TextFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPointerOver" ResourceKey="TextFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPressed" ResourceKey="TextFillColorSecondaryBrush"/>
<StaticResource x:Key="TokenItemForegroundSelected" ResourceKey="TextOnAccentFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPointerOverSelected" ResourceKey="TextOnAccentFillColorPrimaryBrush"/>
<StaticResource x:Key="TokenItemForegroundPressedSelected" ResourceKey="TextOnAccentFillColorSecondaryBrush"/>
<Thickness x:Key="TokenItemBorderThickness">1</Thickness>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
<!--<Thickness x:Key="ButtonPadding">8,4,8,5</Thickness> Not sure if we'll also need this later-->
<Thickness x:Key="TextControlThemePadding">10,3,6,6</Thickness>
<!-- Need local copy of this, as including WinUI overrides this to something that adds too much padding for our inner box -->
<x:Double x:Key="TokenizingTextBoxIconFontSize">10</x:Double>
<Thickness x:Key="TokenItemPadding">8,4,4,4</Thickness>
<Thickness x:Key="TokenizingTextBoxItemPresenterMargin">0,-2,0,1</Thickness>
<HorizontalAlignment x:Key="TokenizingTextBoxItemHorizontalContentAlignment">Center</HorizontalAlignment>
<VerticalAlignment x:Key="TokenizingTextBoxItemVerticalContentAlignment">Center</VerticalAlignment>
<CornerRadius x:Key="PopupOverlayCornerRadius">0,0,0,8</CornerRadius>
<Style x:Key="TokenizingTextBoxDeleteButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid
x:Name="ButtonLayoutGrid"
Margin="{StaticResource AutoSuggestBoxDeleteButtonMargin}"
Background="{ThemeResource TextControlButtonBackground}"
BorderBrush="{ThemeResource TextControlButtonBorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{ThemeResource ControlCornerRadius}">
<!-- FontSize is ignored here, see https://github.com/microsoft/microsoft-ui-xaml/issues/2568 -->
<!-- Set in code-behind link:TokenizingTextBoxItem.AutoSuggestBox.cs#L104 -->
<TextBlock
x:Name="GlyphElement"
HorizontalAlignment="Center"
VerticalAlignment="Center"
win:AutomationProperties.AccessibilityView="Raw"
FontFamily="{ThemeResource SymbolThemeFontFamily}"
FontSize="{ThemeResource TokenizingTextBoxIconFontSize}"
FontStyle="Normal"
Foreground="{ThemeResource TextControlButtonForeground}"
Text="&#xE894;"/>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="PointerOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBackgroundPointerOver}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBorderBrushPointerOver}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="GlyphElement" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonForegroundPointerOver}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBackgroundPressed}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBorderBrushPressed}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="GlyphElement" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonForegroundPressed}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Disabled">
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="ButtonLayoutGrid"
Storyboard.TargetProperty="Opacity"
To="0"
Duration="0"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Name="TokenizingTextBoxQueryButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<ContentPresenter
x:Name="ContentPresenter"
Margin="{ThemeResource AutoSuggestBoxInnerButtonMargin}"
Padding="{TemplateBinding Padding}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
muxc:AnimatedIcon.State="Normal"
win:AutomationProperties.AccessibilityView="Raw"
Background="{ThemeResource TextControlButtonBackground}"
BackgroundSizing="{TemplateBinding BackgroundSizing}"
BorderBrush="{ThemeResource TextControlButtonBorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
ContentTransitions="{TemplateBinding ContentTransitions}"
CornerRadius="{TemplateBinding CornerRadius}"
FontSize="{TemplateBinding FontSize}">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="PointerOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBackgroundPointerOver}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBorderBrushPointerOver}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonForegroundPointerOver}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
<VisualState.Setters>
<Setter Target="ContentPresenter.(muxc:AnimatedIcon.State)" Value="PointerOver"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBackgroundPressed}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBorderBrushPressed}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonForegroundPressed}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
<VisualState.Setters>
<Setter Target="ContentPresenter.(muxc:AnimatedIcon.State)" Value="Pressed"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Disabled">
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="ContentPresenter"
Storyboard.TargetProperty="Opacity"
To="0"
Duration="0"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</ContentPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Inner TextBox Style with removed borders to look like part of the outer textbox facade we've setup -->
<Style
x:Key="TokenizingTextBoxTextBoxStyle"
BasedOn="{StaticResource AutoSuggestBoxTextBoxStyle}"
TargetType="TextBox">
<Setter Property="MinWidth" Value="{ThemeResource TextControlThemeMinWidth}"/>
<Setter Property="Foreground" Value="{ThemeResource TextControlForeground}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="SelectionHighlightColor" Value="{ThemeResource TextControlSelectionHighlightColor}"/>
<Setter Property="BorderThickness" Value="0"/>
<!-- Override -->
<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
<Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
<Setter Property="ScrollViewer.HorizontalScrollMode" Value="Auto"/>
<Setter Property="ScrollViewer.VerticalScrollMode" Value="Auto"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Hidden"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Hidden"/>
<win:Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>
<Setter Property="Padding" Value="8,5,6,6"/>
<Setter Property="CornerRadius" Value="{ThemeResource ControlCornerRadius}"/>
<Setter Property="MinHeight" Value="28"/>
<!-- Override -->
<win:Setter Property="SelectionHighlightColorWhenNotFocused" Value="{ThemeResource TextControlSelectionHighlightColor}"/>
<!-- Override -->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Grid ColumnSpacing="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border
x:Name="BorderElement"
Grid.Row="1"
Grid.RowSpan="1"
Grid.ColumnSpan="3"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"/>
<ContentPresenter
x:Name="HeaderContentPresenter"
Grid.Row="0"
Grid.ColumnSpan="3"
Margin="{ThemeResource AutoSuggestBoxTopHeaderMargin}"
x:DeferLoadStrategy="Lazy"
Content="{TemplateBinding Header}"
ContentTemplate="{TemplateBinding HeaderTemplate}"
FontWeight="Normal"
Foreground="{ThemeResource TextControlHeaderForeground}"
TextWrapping="Wrap"
Visibility="Collapsed"/>
<ScrollViewer
x:Name="ContentElement"
Grid.Row="1"
Margin="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}"
win:AutomationProperties.AccessibilityView="Raw"
win:IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}"
win:IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}"
win:IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}"
HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}"
HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}"
IsTabStop="False"
VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}"
VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}"
ZoomMode="Disabled"/>
<ContentControl
x:Name="PlaceholderTextContentPresenter"
Grid.Row="1"
Grid.ColumnSpan="2"
Padding="{TemplateBinding Padding}"
VerticalContentAlignment="Center"
Content="{TemplateBinding PlaceholderText}"
Foreground="{ThemeResource TextControlPlaceholderForeground}"
IsHitTestVisible="False"
IsTabStop="False"/>
<Button
x:Name="DeleteButton"
Grid.Row="1"
Grid.Column="1"
Width="32"
Height="28"
Padding="{ThemeResource HelperButtonThemePadding}"
VerticalAlignment="Stretch"
win:AutomationProperties.AccessibilityView="Raw"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}"
FontSize="{TemplateBinding FontSize}"
IsTabStop="False"
Style="{StaticResource TokenizingTextBoxDeleteButtonStyle}"
Visibility="Collapsed"/>
<TextBlock
Name="PART_TokensCounter"
Grid.Row="1"
Grid.Column="2"
Margin="2,0,0,2"
VerticalAlignment="Center"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
Style="{StaticResource CaptionTextBlockStyle}"/>
<Button
x:Name="QueryButton"
Grid.Row="1"
Grid.Column="3"
Width="32"
Height="28"
Margin="0,0,2,0"
Padding="0"
VerticalAlignment="Stretch"
win:AutomationProperties.AccessibilityView="Raw"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}"
FontSize="{TemplateBinding FontSize}"
IsTabStop="False"
Style="{StaticResource TokenizingTextBoxQueryButtonStyle}"/>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Disabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="HeaderContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlHeaderForegroundDisabled}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundDisabled}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundDisabled}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Normal"/>
<VisualState x:Name="PointerOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundPointerOver}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundPointerOver}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Focused">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundFocused}"/>
<!-- WinUI override -->
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundFocused}"/>
<!-- WinUI override -->
</ObjectAnimationUsingKeyFrames>
<!--<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement"
Storyboard.TargetProperty="RequestedTheme">
<DiscreteObjectKeyFrame KeyTime="0"
Value="Light" />
</ObjectAnimationUsingKeyFrames>-->
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="QueryButton" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonForeground}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="ButtonStates">
<VisualState x:Name="ButtonVisible">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="DeleteButton" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<Visibility>Visible</Visibility>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="ButtonCollapsed"/>
</VisualStateGroup>
<VisualStateGroup x:Name="TokensCounterStates">
<VisualState x:Name="MaxReachedState">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="PART_TokensCounter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemFillColorCriticalBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="MaxUnreachedState"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="TokenizingTextBoxItemTextStyle" TargetType="shct:TokenizingTextBoxItem">
<Setter Property="Background" Value="{ThemeResource SystemControlBackgroundChromeMediumLowBrush}"/>
<Setter Property="BorderBrush" Value="{ThemeResource SystemControlTransparentBrush}"/>
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="UseSystemFocusVisuals" Value="False"/>
<Setter Property="MinWidth" Value="128"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="shct:TokenizingTextBoxItem">
<AutoSuggestBox
Name="PART_AutoSuggestBox"
DisplayMemberPath="{Binding Path=Owner.DisplayMemberPath, RelativeSource={RelativeSource Mode=TemplatedParent}}"
ItemTemplate="{Binding Path=Owner.SuggestedItemTemplate, RelativeSource={RelativeSource Mode=TemplatedParent}}"
ItemsSource="{Binding Path=Owner.SuggestedItemsSource, RelativeSource={RelativeSource Mode=TemplatedParent}}"
PlaceholderText="{Binding Path=Owner.PlaceholderText, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Style="{StaticResource SystemAutoSuggestBoxStyle}"
Text="{Binding Text, Mode=TwoWay}"
TextBoxStyle="{StaticResource TokenizingTextBoxTextBoxStyle}"
TextMemberPath="{Binding Path=Owner.TextMemberPath, RelativeSource={RelativeSource Mode=TemplatedParent}}"
UpdateTextOnSelect="False"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Copy of System Style from 18362 to try and workaround WinUI Styles -->
<Style x:Key="SystemAutoSuggestBoxStyle" TargetType="AutoSuggestBox">
<Setter Property="VerticalAlignment" Value="Top"/>
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="TextBoxStyle" Value="{StaticResource AutoSuggestBoxTextBoxStyle}"/>
<Setter Property="UseSystemFocusVisuals" Value="{ThemeResource IsApplicationFocusVisualKindReveal}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="AutoSuggestBox">
<Grid x:Name="LayoutRoot">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBox
x:Name="TextBox"
Width="{TemplateBinding Width}"
Margin="0"
win:DesiredCandidateWindowAlignment="BottomEdge"
Canvas.ZIndex="0"
CornerRadius="4"
Header="{TemplateBinding Header}"
PlaceholderText="{TemplateBinding PlaceholderText}"
ScrollViewer.BringIntoViewOnFocusChange="False"
Style="{TemplateBinding TextBoxStyle}"
UseSystemFocusVisuals="{TemplateBinding UseSystemFocusVisuals}"/>
<Popup x:Name="SuggestionsPopup">
<Border
x:Name="SuggestionsContainer"
Background="{ThemeResource AutoSuggestBoxSuggestionsListBackground}"
CornerRadius="{StaticResource PopupOverlayCornerRadius}">
<ListView
x:Name="SuggestionsList"
MaxHeight="{ThemeResource AutoSuggestListMaxHeight}"
Margin="{ThemeResource AutoSuggestListPadding}"
Padding="{ThemeResource AutoSuggestListPadding}"
BorderBrush="{ThemeResource AutoSuggestBoxSuggestionsListBorderBrush}"
BorderThickness="{ThemeResource AutoSuggestListBorderThemeThickness}"
DisplayMemberPath="{TemplateBinding DisplayMemberPath}"
IsItemClickEnabled="True"
ItemContainerStyle="{TemplateBinding ItemContainerStyle}"
ItemTemplate="{TemplateBinding ItemTemplate}"
ItemTemplateSelector="{TemplateBinding ItemTemplateSelector}"/>
</Border>
</Popup>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="Orientation">
<VisualState x:Name="Landscape"/>
<VisualState x:Name="Portrait"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="TokenizingTextBoxItemTokenStyle" TargetType="shct:TokenizingTextBoxItem">
<Setter Property="ClearButtonStyle" Value="{StaticResource SubtleButtonStyle}"/>
<Setter Property="HorizontalContentAlignment" Value="{StaticResource TokenizingTextBoxItemHorizontalContentAlignment}"/>
<Setter Property="VerticalContentAlignment" Value="{StaticResource TokenizingTextBoxItemVerticalContentAlignment}"/>
<!--<Setter Property="HorizontalAlignment" Value="Center" />-->
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
<Setter Property="Background" Value="{ThemeResource TokenItemBackground}"/>
<Setter Property="BorderBrush" Value="{ThemeResource TokenItemBorderBrush}"/>
<Setter Property="BorderThickness" Value="{ThemeResource TokenItemBorderThickness}"/>
<Setter Property="CornerRadius" Value="2"/>
<Setter Property="Padding" Value="{ThemeResource TokenItemPadding}"/>
<Setter Property="IsTabStop" Value="True"/>
<Setter Property="TabNavigation" Value="Local"/>
<Setter Property="Foreground" Value="{ThemeResource TokenItemForeground}"/>
<Setter Property="FontWeight" Value="Normal"/>
<Setter Property="UseSystemFocusVisuals" Value="True"/>
<Setter Property="FocusVisualMargin" Value="-3"/>
<Setter Property="BackgroundSizing" Value="InnerBorderEdge"/>
<Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="shct:TokenizingTextBoxItem">
<Grid
x:Name="PART_RootGrid"
Height="{TemplateBinding Height}"
Padding="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
VerticalAlignment="{TemplateBinding VerticalAlignment}"
Background="{TemplateBinding Background}"
BackgroundSizing="{TemplateBinding BackgroundSizing}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
ColumnSpacing="8"
Control.IsTemplateFocusTarget="True"
CornerRadius="{TemplateBinding CornerRadius}">
<win:Grid.BackgroundTransition>
<win:BrushTransition Duration="0:0:0.083"/>
</win:Grid.BackgroundTransition>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<!-- Content -->
<ContentPresenter
x:Name="PART_ContentPresenter"
Margin="0,-1,0,0"
VerticalAlignment="Center"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
win:OpticalMarginAlignment="TrimSideBearings"
BackgroundSizing="{TemplateBinding BackgroundSizing}"
Content="{TemplateBinding Content}"
ContentTransitions="{TemplateBinding ContentTransitions}"
FontWeight="{TemplateBinding FontWeight}"
Foreground="{TemplateBinding Foreground}"/>
<Button
x:Name="PART_RemoveButton"
Grid.Row="1"
Grid.Column="1"
Width="20"
Height="20"
MinWidth="0"
MinHeight="0"
Margin="0,0,0,-2"
Padding="2"
VerticalAlignment="Center"
CornerRadius="99"
IsTabStop="False"
Style="{TemplateBinding ClearButtonStyle}">
<FontIcon FontSize="12" Glyph="&#xE894;"/>
</Button>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="PointerOver">
<VisualState.Setters>
<Setter Target="PART_RootGrid.Background" Value="{ThemeResource TokenItemBackgroundPointerOver}"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Pressed">
<VisualState.Setters>
<Setter Target="PART_RootGrid.Background" Value="{ThemeResource TokenItemBackgroundPressed}"/>
<Setter Target="PART_RootGrid.BorderBrush" Value="{ThemeResource TokenItemBorderBrushPointerOver}"/>
<Setter Target="PART_ContentPresenter.Foreground" Value="{ThemeResource TokenItemForegroundPointerOver}"/>
<Setter Target="PART_RemoveButton.Foreground" Value="{ThemeResource TokenItemForegroundPointerOver}"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Selected">
<VisualState.Setters>
<Setter Target="PART_RootGrid.Background" Value="{ThemeResource TokenItemBackgroundSelected}"/>
<Setter Target="PART_RootGrid.BorderBrush" Value="{ThemeResource TokenItemBorderBrushSelected}"/>
<Setter Target="PART_ContentPresenter.Foreground" Value="{ThemeResource TokenItemForegroundSelected}"/>
<Setter Target="PART_RemoveButton.Style" Value="{ThemeResource SubtleAccentButtonStyle}"/>
<Setter Target="PART_RootGrid.BackgroundSizing" Value="OuterBorderEdge"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="PointerOverSelected">
<VisualState.Setters>
<Setter Target="PART_RootGrid.Background" Value="{ThemeResource TokenItemBackgroundPointerOverSelected}"/>
<Setter Target="PART_RootGrid.BorderBrush" Value="{ThemeResource TokenItemBorderBrushPointerOverSelected}"/>
<Setter Target="PART_ContentPresenter.Foreground" Value="{ThemeResource TokenItemForegroundPointerOverSelected}"/>
<Setter Target="PART_RemoveButton.Style" Value="{ThemeResource SubtleAccentButtonStyle}"/>
<Setter Target="PART_RootGrid.BackgroundSizing" Value="OuterBorderEdge"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="PressedSelected">
<VisualState.Setters>
<Setter Target="PART_RootGrid.Background" Value="{ThemeResource TokenItemBackgroundPressedSelected}"/>
<Setter Target="PART_RootGrid.BorderBrush" Value="{ThemeResource TokenItemBorderBrushPressedSelected}"/>
<Setter Target="PART_ContentPresenter.Foreground" Value="{ThemeResource TokenItemForegroundPressedSelected}"/>
<Setter Target="PART_RemoveButton.Style" Value="{ThemeResource SubtleAccentButtonStyle}"/>
<Setter Target="PART_RootGrid.BackgroundSizing" Value="OuterBorderEdge"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="DisabledStates">
<VisualState x:Name="Enabled"/>
<VisualState x:Name="Disabled">
<VisualState.Setters>
<Setter Target="PART_ContentPresenter.Opacity" Value="{ThemeResource ListViewItemDisabledThemeOpacity}"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Default style for TokenizingTextBoxItem -->
<Style BasedOn="{StaticResource TokenizingTextBoxItemTokenStyle}" TargetType="shct:TokenizingTextBoxItem"/>
<Style x:Key="SubtleButtonStyle" TargetType="Button">
<Setter Property="Background" Value="{ThemeResource SubtleFillColorTransparent}"/>
<Setter Property="BackgroundSizing" Value="InnerBorderEdge"/>
<Setter Property="Foreground" Value="{ThemeResource TextFillColorPrimary}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="{StaticResource ButtonPadding}"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
<Setter Property="FontWeight" Value="Normal"/>
<Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
<Setter Property="UseSystemFocusVisuals" Value="{StaticResource UseSystemFocusVisuals}"/>
<Setter Property="FocusVisualMargin" Value="-3"/>
<Setter Property="CornerRadius" Value="{ThemeResource ControlCornerRadius}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<ContentPresenter
x:Name="ContentPresenter"
Padding="{TemplateBinding Padding}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
muxc:AnimatedIcon.State="Normal"
win:AutomationProperties.AccessibilityView="Raw"
Background="{TemplateBinding Background}"
BackgroundSizing="{TemplateBinding BackgroundSizing}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
ContentTransitions="{TemplateBinding ContentTransitions}"
CornerRadius="{TemplateBinding CornerRadius}">
<win:ContentPresenter.BackgroundTransition>
<win:BrushTransition Duration="0:0:0.083"/>
</win:ContentPresenter.BackgroundTransition>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="PointerOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SubtleFillColorSecondary}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextFillColorPrimary}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
<VisualState.Setters>
<Setter Target="ContentPresenter.(muxc:AnimatedIcon.State)" Value="PointerOver"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SubtleFillColorTertiary}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextFillColorSecondary}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
<VisualState.Setters>
<Setter Target="ContentPresenter.(muxc:AnimatedIcon.State)" Value="Pressed"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Disabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ControlFillColorDisabled}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextFillColorDisabled}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
<VisualState.Setters>
<!-- DisabledVisual Should be handled by the control, not the animated icon. -->
<Setter Target="ContentPresenter.(muxc:AnimatedIcon.State)" Value="Normal"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</ContentPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="SubtleAccentButtonStyle" TargetType="Button">
<Setter Property="Background" Value="{ThemeResource SubtleFillColorTransparent}"/>
<Setter Property="BackgroundSizing" Value="InnerBorderEdge"/>
<Setter Property="Foreground" Value="{ThemeResource TextOnAccentFillColorPrimaryBrush}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="{StaticResource ButtonPadding}"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
<Setter Property="FontWeight" Value="Normal"/>
<Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
<Setter Property="UseSystemFocusVisuals" Value="{StaticResource UseSystemFocusVisuals}"/>
<Setter Property="FocusVisualMargin" Value="-3"/>
<Setter Property="CornerRadius" Value="{ThemeResource ControlCornerRadius}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<ContentPresenter
x:Name="ContentPresenter"
Padding="{TemplateBinding Padding}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
muxc:AnimatedIcon.State="Normal"
win:AutomationProperties.AccessibilityView="Raw"
Background="{TemplateBinding Background}"
BackgroundSizing="{TemplateBinding BackgroundSizing}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
ContentTransitions="{TemplateBinding ContentTransitions}"
CornerRadius="{TemplateBinding CornerRadius}">
<win:ContentPresenter.BackgroundTransition>
<win:BrushTransition Duration="0:0:0.083"/>
</win:ContentPresenter.BackgroundTransition>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="PointerOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SubtleFillColorSecondary}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextOnAccentFillColorPrimaryBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
<VisualState.Setters>
<Setter Target="ContentPresenter.(muxc:AnimatedIcon.State)" Value="PointerOver"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SubtleFillColorTertiary}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextOnAccentFillColorSecondaryBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
<VisualState.Setters>
<Setter Target="ContentPresenter.(muxc:AnimatedIcon.State)" Value="Pressed"/>
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Disabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ControlFillColorTransparentBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
<!-- Should be TextOnAccentFillColorDisabledBrush, but doesn't seem to work? This is the same visual effect -->
<DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ControlFillColorDefaultBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
<VisualState.Setters>
<Setter Target="ContentPresenter.(muxc:AnimatedIcon.State)" Value="Normal"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</ContentPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

View File

@@ -0,0 +1,25 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
namespace Snap.Hutao.Control.TokenizingTextBox;
internal class TokenizingTextBoxStyleSelector : StyleSelector
{
public Style TokenStyle { get; set; } = default!;
public Style TextStyle { get; set; } = default!;
/// <inheritdoc/>
protected override Style SelectStyleCore(object item, DependencyObject container)
{
if (item is ITokenStringContainer)
{
return TextStyle;
}
return TokenStyle;
}
}

View File

@@ -5,5 +5,5 @@ namespace Snap.Hutao.Core.Abstraction;
internal interface IPinnable<TData>
{
ref TData GetPinnableReference();
ref readonly TData GetPinnableReference();
}

View File

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

View File

@@ -11,13 +11,16 @@ using Snap.Hutao.Web.Request.Builder;
using Snap.Hutao.Web.Request.Builder.Abstraction;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
namespace Snap.Hutao.Core.Caching;
/// <summary>
/// Provides methods and tools to cache files in a folder
/// The class's name will become the cache folder's name
/// </summary>
[HighQuality]
[ConstructorGenerated]
[Injection(InjectAs.Singleton, typeof(IImageCache))]
@@ -25,9 +28,10 @@ namespace Snap.Hutao.Core.Caching;
[PrimaryHttpMessageHandler(MaxConnectionsPerServer = 8)]
internal sealed partial class ImageCache : IImageCache, IImageCacheFilePathOperation
{
private const string CacheFolderName = nameof(ImageCache);
private const string CacheFailedDownloadTasksName = $"{nameof(ImageCache)}.FailedDownloadTasks";
private static readonly FrozenDictionary<int, TimeSpan> DelayFromRetryCount = FrozenDictionary.ToFrozenDictionary(
private readonly FrozenDictionary<int, TimeSpan> retryCountToDelay = FrozenDictionary.ToFrozenDictionary(
[
KeyValuePair.Create(0, TimeSpan.FromSeconds(4)),
KeyValuePair.Create(1, TimeSpan.FromSeconds(16)),
@@ -42,13 +46,16 @@ internal sealed partial class ImageCache : IImageCache, IImageCacheFilePathOpera
private readonly ILogger<ImageCache> logger;
private readonly IMemoryCache memoryCache;
private string? baseFolder;
private string? cacheFolder;
private string CacheFolder
{
get => LazyInitializer.EnsureInitialized(ref cacheFolder, () =>
{
return serviceProvider.GetRequiredService<RuntimeOptions>().GetLocalCacheImageCacheFolder();
baseFolder ??= serviceProvider.GetRequiredService<RuntimeOptions>().LocalCache;
DirectoryInfo info = Directory.CreateDirectory(Path.Combine(baseFolder, CacheFolderName));
return info.FullName;
});
}
@@ -142,7 +149,8 @@ internal sealed partial class ImageCache : IImageCache, IImageCacheFilePathOpera
return treatNullFileAsInvalid;
}
return new FileInfo(file).Length == 0;
FileInfo fileInfo = new(file);
return fileInfo.Length == 0;
}
private void RemoveCore(IEnumerable<string> filePaths)
@@ -164,76 +172,80 @@ internal sealed partial class ImageCache : IImageCache, IImageCacheFilePathOpera
[SuppressMessage("", "SH003")]
private async Task DownloadFileAsync(Uri uri, string baseFile)
{
using (HttpClient httpClient = httpClientFactory.CreateClient(nameof(ImageCache)))
int retryCount = 0;
HttpClient httpClient = httpClientFactory.CreateClient(nameof(ImageCache));
while (retryCount < 3)
{
int retryCount = 0;
HttpRequestMessageBuilder requestMessageBuilder = httpRequestMessageBuilderFactory
.Create()
.SetRequestUri(uri)
.SetStaticResourceControlHeadersIf(uri.Host.Contains("api.snapgenshin.com", StringComparison.OrdinalIgnoreCase)) // These headers are only available for our own api
// These headers are only available for our own api
.SetStaticResourceControlHeadersIf(uri.Host.Contains("api.snapgenshin.com", StringComparison.OrdinalIgnoreCase))
.Get();
while (retryCount < 3)
using (HttpRequestMessage requestMessage = requestMessageBuilder.HttpRequestMessage)
{
requestMessageBuilder.Resurrect();
using (HttpRequestMessage requestMessage = requestMessageBuilder.HttpRequestMessage)
using (HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
{
using (HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
if (responseMessage.RequestMessage is { RequestUri: { } target } && target != uri)
{
// Redirect detection
if (responseMessage.RequestMessage is { RequestUri: { } target } && target != uri)
logger.LogDebug("The Request '{Source}' has been redirected to '{Target}'", uri, target);
}
if (responseMessage.IsSuccessStatusCode)
{
if (responseMessage.Content.Headers.ContentType?.MediaType is "application/json")
{
logger.LogDebug("The Request '{Source}' has been redirected to '{Target}'", uri, target);
#if DEBUG
DebugTrack(uri);
#endif
string raw = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
logger.LogColorizedCritical("Failed to download '{Uri}' with unexpected body '{Raw}'", (uri, ConsoleColor.Red), (raw, ConsoleColor.DarkYellow));
return;
}
if (responseMessage.IsSuccessStatusCode)
using (Stream httpStream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
if (responseMessage.Content.Headers.ContentType?.MediaType is "application/json")
using (FileStream fileStream = File.Create(baseFile))
{
DebugTrackFailedUri(uri);
string raw = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
logger.LogColorizedCritical("Failed to download '{Uri}' with unexpected body '{Raw}'", (uri, ConsoleColor.Red), (raw, ConsoleColor.DarkYellow));
await httpStream.CopyToAsync(fileStream).ConfigureAwait(false);
return;
}
}
}
using (Stream httpStream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false))
switch (responseMessage.StatusCode)
{
case HttpStatusCode.TooManyRequests:
{
using (FileStream fileStream = File.Create(baseFile))
{
await httpStream.CopyToAsync(fileStream).ConfigureAwait(false);
return;
}
retryCount++;
TimeSpan delay = responseMessage.Headers.RetryAfter?.Delta ?? retryCountToDelay[retryCount];
logger.LogInformation("Retry download '{Uri}' after {Delay}.", uri, delay);
await Task.Delay(delay).ConfigureAwait(false);
break;
}
}
switch (responseMessage.StatusCode)
{
case HttpStatusCode.TooManyRequests:
{
retryCount++;
TimeSpan delay = responseMessage.Headers.RetryAfter?.Delta ?? DelayFromRetryCount[retryCount];
logger.LogInformation("Retry download '{Uri}' after {Delay}.", uri, delay);
await Task.Delay(delay).ConfigureAwait(false);
break;
}
default:
DebugTrackFailedUri(uri);
logger.LogColorizedCritical("Failed to download '{Uri}' with status code '{StatusCode}'", (uri, ConsoleColor.Red), (responseMessage.StatusCode, ConsoleColor.DarkYellow));
return;
}
default:
#if DEBUG
DebugTrack(uri);
#endif
logger.LogColorizedCritical("Failed to download '{Uri}' with status code '{StatusCode}'", (uri, ConsoleColor.Red), (responseMessage.StatusCode, ConsoleColor.DarkYellow));
return;
}
}
}
}
}
}
[Conditional("DEBUG")]
private void DebugTrackFailedUri(Uri uri)
#if DEBUG
internal partial class ImageCache
{
private void DebugTrack(Uri uri)
{
HashSet<string>? set = memoryCache.GetOrCreate(CacheFailedDownloadTasksName, entry => new HashSet<string>());
HashSet<string>? set = memoryCache.GetOrCreate(CacheFailedDownloadTasksName, entry => entry.Value ??= new HashSet<string>()) as HashSet<string>;
set?.Add(uri.ToString());
}
}
}
#endif

View File

@@ -70,7 +70,7 @@ internal sealed class ObservableReorderableDbCollection<TEntity> : ObservableCol
[SuppressMessage("", "SA1402")]
internal sealed class ObservableReorderableDbCollection<TEntityOnly, TEntity> : ObservableCollection<TEntityOnly>
where TEntityOnly : class, IEntityAccess<TEntity>
where TEntityOnly : class, IEntityOnly<TEntity>
where TEntity : class, IReorderable
{
private readonly IServiceProvider serviceProvider;

View File

@@ -73,7 +73,7 @@ internal sealed partial class ScopedDbCurrent<TEntity, TMessage>
[ConstructorGenerated]
internal sealed partial class ScopedDbCurrent<TEntityOnly, TEntity, TMessage>
where TEntityOnly : class, IEntityAccess<TEntity>
where TEntityOnly : class, IEntityOnly<TEntity>
where TEntity : class, ISelectable
where TMessage : Message.ValueChangedMessage<TEntityOnly>, new()
{

View File

@@ -41,7 +41,7 @@ internal static class DependencyInjection
.AddJsonOptions()
.AddDatabase()
.AddInjections()
.AddConfiguredHttpClients()
.AddAllHttpClients()
// Discrete services
.AddSingleton<IMessenger, WeakReferenceMessenger>()

View File

@@ -34,27 +34,27 @@ internal static class IocConfiguration
.AddTransient(typeof(Database.ScopedDbCurrent<,>))
.AddTransient(typeof(Database.ScopedDbCurrent<,,>))
.AddDbContextPool<AppDbContext>(AddDbContextCore);
}
static void AddDbContextCore(IServiceProvider serviceProvider, DbContextOptionsBuilder builder)
private static void AddDbContextCore(IServiceProvider serviceProvider, DbContextOptionsBuilder builder)
{
RuntimeOptions runtimeOptions = serviceProvider.GetRequiredService<RuntimeOptions>();
string dbFile = System.IO.Path.Combine(runtimeOptions.DataFolder, "Userdata.db");
string sqlConnectionString = $"Data Source={dbFile}";
// Temporarily create a context
using (AppDbContext context = AppDbContext.Create(serviceProvider, sqlConnectionString))
{
RuntimeOptions runtimeOptions = serviceProvider.GetRequiredService<RuntimeOptions>();
string dbFile = System.IO.Path.Combine(runtimeOptions.DataFolder, "Userdata.db");
string sqlConnectionString = $"Data Source={dbFile}";
// Temporarily create a context
using (AppDbContext context = AppDbContext.Create(serviceProvider, sqlConnectionString))
if (context.Database.GetPendingMigrations().Any())
{
if (context.Database.GetPendingMigrations().Any())
{
System.Diagnostics.Debug.WriteLine("[Database] Performing AppDbContext Migrations");
context.Database.Migrate();
}
System.Diagnostics.Debug.WriteLine("[Database] Performing AppDbContext Migrations");
context.Database.Migrate();
}
builder
.EnableSensitiveDataLogging()
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
.UseSqlite(sqlConnectionString);
}
builder
.EnableSensitiveDataLogging()
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
.UseSqlite(sqlConnectionString);
}
}

View File

@@ -15,7 +15,7 @@ internal static partial class IocHttpClientConfiguration
{
private const string ApplicationJson = "application/json";
public static IServiceCollection AddConfiguredHttpClients(this IServiceCollection services)
public static IServiceCollection AddAllHttpClients(this IServiceCollection services)
{
services
.ConfigureHttpClientDefaults(clientBuilder =>
@@ -27,7 +27,7 @@ internal static partial class IocHttpClientConfiguration
HttpClientHandler clientHandler = (HttpClientHandler)handler;
clientHandler.AllowAutoRedirect = true;
clientHandler.UseProxy = true;
clientHandler.Proxy = provider.GetRequiredService<HttpProxyUsingSystemProxy>();
clientHandler.Proxy = provider.GetRequiredService<DynamicHttpProxy>();
});
})
.AddHttpClients();

View File

@@ -0,0 +1,22 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using System.Runtime.CompilerServices;
namespace Snap.Hutao.Core.ExceptionService;
/// <summary>
/// 帮助更好的抛出异常
/// </summary>
[HighQuality]
[System.Diagnostics.StackTraceHidden]
[Obsolete("Use HutaoException instead")]
internal static class ThrowHelper
{
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
public static ArgumentException Argument(string message, string? paramName)
{
throw new ArgumentException(message, paramName);
}
}

View File

@@ -2,12 +2,7 @@
// Licensed under the MIT license.
using Microsoft.VisualBasic.FileIO;
using Snap.Hutao.Win32.System.Com;
using Snap.Hutao.Win32.UI.Shell;
using System.IO;
using static Snap.Hutao.Win32.Macros;
using static Snap.Hutao.Win32.Ole32;
using static Snap.Hutao.Win32.Shell32;
namespace Snap.Hutao.Core.IO;
@@ -23,29 +18,4 @@ internal static class DirectoryOperation
FileSystem.MoveDirectory(sourceDirName, destDirName, true);
return true;
}
public static unsafe bool UnsafeRename(string path, string name, FILEOPERATION_FLAGS flags = FILEOPERATION_FLAGS.FOF_ALLOWUNDO | FILEOPERATION_FLAGS.FOF_NOCONFIRMMKDIR)
{
bool result = false;
if (SUCCEEDED(CoCreateInstance(in Win32.UI.Shell.FileOperation.CLSID, default, CLSCTX.CLSCTX_INPROC_SERVER, in IFileOperation.IID, out IFileOperation* pFileOperation)))
{
if (SUCCEEDED(SHCreateItemFromParsingName(path, default, in IShellItem.IID, out IShellItem* pShellItem)))
{
pFileOperation->SetOperationFlags(flags);
pFileOperation->RenameItem(pShellItem, name, default);
if (SUCCEEDED(pFileOperation->PerformOperations()))
{
result = true;
}
IUnknownMarshal.Release(pShellItem);
}
IUnknownMarshal.Release(pFileOperation);
}
return result;
}
}

View File

@@ -45,30 +45,6 @@ internal static class FileOperation
return true;
}
public static unsafe bool UnsafeDelete(string path)
{
bool result = false;
if (SUCCEEDED(CoCreateInstance(in Win32.UI.Shell.FileOperation.CLSID, default, CLSCTX.CLSCTX_INPROC_SERVER, in IFileOperation.IID, out IFileOperation* pFileOperation)))
{
if (SUCCEEDED(SHCreateItemFromParsingName(path, default, in IShellItem.IID, out IShellItem* pShellItem)))
{
pFileOperation->DeleteItem(pShellItem, default);
if (SUCCEEDED(pFileOperation->PerformOperations()))
{
result = true;
}
IUnknownMarshal.Release(pShellItem);
}
IUnknownMarshal.Release(pFileOperation);
}
return result;
}
public static unsafe bool UnsafeMove(string sourceFileName, string destFileName)
{
bool result = false;
@@ -97,4 +73,28 @@ internal static class FileOperation
return result;
}
public static unsafe bool UnsafeDelete(string path)
{
bool result = false;
if (SUCCEEDED(CoCreateInstance(in Win32.UI.Shell.FileOperation.CLSID, default, CLSCTX.CLSCTX_INPROC_SERVER, in IFileOperation.IID, out IFileOperation* pFileOperation)))
{
if (SUCCEEDED(SHCreateItemFromParsingName(path, default, in IShellItem.IID, out IShellItem* pShellItem)))
{
pFileOperation->DeleteItem(pShellItem, default);
if (SUCCEEDED(pFileOperation->PerformOperations()))
{
result = true;
}
IUnknownMarshal.Release(pShellItem);
}
IUnknownMarshal.Release(pFileOperation);
}
return result;
}
}

View File

@@ -6,9 +6,6 @@ using System.Text;
namespace Snap.Hutao.Core.IO.Hashing;
#if NET9_0_OR_GREATER
[Obsolete]
#endif
internal static class Hash
{
public static unsafe string SHA1HexString(string input)

View File

@@ -3,14 +3,13 @@
using CommunityToolkit.Mvvm.ComponentModel;
using Snap.Hutao.Win32.Registry;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
namespace Snap.Hutao.Core.IO.Http.Proxy;
[Injection(InjectAs.Singleton)]
internal sealed partial class HttpProxyUsingSystemProxy : ObservableObject, IWebProxy, IDisposable
internal sealed partial class DynamicHttpProxy : ObservableObject, IWebProxy, IDisposable
{
private const string ProxySettingPath = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections";
@@ -21,7 +20,7 @@ internal sealed partial class HttpProxyUsingSystemProxy : ObservableObject, IWeb
private IWebProxy innerProxy = default!;
public HttpProxyUsingSystemProxy(IServiceProvider serviceProvider)
public DynamicHttpProxy(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
UpdateInnerProxy();

View File

@@ -50,6 +50,13 @@ internal sealed partial class AppActivation : IAppActivation, IAppActivationActi
/// <inheritdoc/>
public void Activate(HutaoActivationArguments args)
{
// Before activate, we try to redirect to the opened process in App,
// And we check if it's a toast activation.
if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated())
{
return;
}
HandleActivationAsync(args).SafeForget();
}
@@ -61,24 +68,20 @@ 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)
{
XamlLifetime.ApplicationLaunchedWithNotifyIcon = true;
XamlWindowLifetime.ApplicationLaunchedWithNotifyIcon = true;
serviceProvider.GetRequiredService<App>().DispatcherShutdownMode = DispatcherShutdownMode.OnExplicitShutdown;
_ = serviceProvider.GetRequiredService<NotifyIconController>();
}
serviceProvider.GetRequiredService<IScheduleTaskInterop>().UnregisterAllTasks();
serviceProvider.GetRequiredService<IQuartzService>().StartAsync(default).SafeForget();
}
}
@@ -96,31 +99,25 @@ internal sealed partial class AppActivation : IAppActivation, IAppActivationActi
await taskContext.SwitchToMainThreadAsync();
switch (currentWindowReference.Window)
if (currentWindowReference.Window is null)
{
case null:
LaunchGameWindow launchGameWindow = serviceProvider.GetRequiredService<LaunchGameWindow>();
currentWindowReference.Window = launchGameWindow;
currentWindowReference.Window = serviceProvider.GetRequiredService<LaunchGameWindow>();
return;
}
launchGameWindow.SwitchTo();
launchGameWindow.BringToForeground();
return;
if (currentWindowReference.Window is MainWindow)
{
await serviceProvider
.GetRequiredService<INavigationService>()
.NavigateAsync<View.Page.LaunchGamePage>(INavigationAwaiter.Default, true)
.ConfigureAwait(false);
case MainWindow:
await serviceProvider
.GetRequiredService<INavigationService>()
.NavigateAsync<View.Page.LaunchGamePage>(INavigationAwaiter.Default, true)
.ConfigureAwait(false);
return;
case LaunchGameWindow currentLaunchGameWindow:
currentLaunchGameWindow.SwitchTo();
currentLaunchGameWindow.BringToForeground();
return;
default:
Process.GetCurrentProcess().Kill();
return;
return;
}
else
{
// We have a non-Main Window, just exit current process anyway
Process.GetCurrentProcess().Kill();
}
}
@@ -163,61 +160,48 @@ internal sealed partial class AppActivation : IAppActivation, IAppActivationActi
{
default:
{
await HandleNormalLaunchActionAsync(args.IsRedirectTo).ConfigureAwait(false);
await HandleNormalLaunchActionAsync().ConfigureAwait(false);
break;
}
}
}
}
private async ValueTask HandleNormalLaunchActionAsync(bool isRedirectTo)
private async ValueTask HandleNormalLaunchActionAsync()
{
if (!isRedirectTo)
// Increase launch times
LocalSetting.Update(SettingKeys.LaunchTimes, 0, x => unchecked(x + 1));
// If the guide is completed, we check if there's any unfulfilled resource category present.
if (UnsafeLocalSetting.Get(SettingKeys.Major1Minor10Revision0GuideState, GuideState.Language) >= GuideState.StaticResourceBegin)
{
// Increase launch times
LocalSetting.Update(SettingKeys.LaunchTimes, 0, x => unchecked(x + 1));
// If the guide is completed, we check if there's any unfulfilled resource category present.
if (UnsafeLocalSetting.Get(SettingKeys.Major1Minor10Revision0GuideState, GuideState.Language) >= GuideState.StaticResourceBegin)
if (StaticResource.IsAnyUnfulfilledCategoryPresent())
{
if (StaticResource.IsAnyUnfulfilledCategoryPresent())
{
UnsafeLocalSetting.Set(SettingKeys.Major1Minor10Revision0GuideState, GuideState.StaticResourceBegin);
}
}
if (UnsafeLocalSetting.Get(SettingKeys.Major1Minor10Revision0GuideState, GuideState.Language) < GuideState.Completed)
{
await taskContext.SwitchToMainThreadAsync();
GuideWindow guideWindow = serviceProvider.GetRequiredService<GuideWindow>();
currentWindowReference.Window = guideWindow;
guideWindow.SwitchTo();
guideWindow.BringToForeground();
return;
UnsafeLocalSetting.Set(SettingKeys.Major1Minor10Revision0GuideState, GuideState.StaticResourceBegin);
}
}
await WaitMainWindowOrCurrentAsync().ConfigureAwait(false);
if (UnsafeLocalSetting.Get(SettingKeys.Major1Minor10Revision0GuideState, GuideState.Language) < GuideState.Completed)
{
await taskContext.SwitchToMainThreadAsync();
currentWindowReference.Window = serviceProvider.GetRequiredService<GuideWindow>();
}
else
{
await WaitMainWindowAsync().ConfigureAwait(false);
}
}
private async ValueTask WaitMainWindowOrCurrentAsync()
private async ValueTask WaitMainWindowAsync()
{
if (currentWindowReference.Window is { } window)
if (currentWindowReference.Window is not null)
{
window.SwitchTo();
window.BringToForeground();
return;
}
await taskContext.SwitchToMainThreadAsync();
MainWindow mainWindow = serviceProvider.GetRequiredService<MainWindow>();
currentWindowReference.Window = mainWindow;
mainWindow.SwitchTo();
mainWindow.BringToForeground();
currentWindowReference.Window = serviceProvider.GetRequiredService<MainWindow>();
await taskContext.SwitchToBackgroundAsync();
@@ -246,7 +230,7 @@ internal sealed partial class AppActivation : IAppActivation, IAppActivationActi
{
case CategoryAchievement:
{
await WaitMainWindowOrCurrentAsync().ConfigureAwait(false);
await WaitMainWindowAsync().ConfigureAwait(false);
await HandleAchievementActionAsync(action, parameter, isRedirectTo).ConfigureAwait(false);
break;
}
@@ -259,7 +243,7 @@ internal sealed partial class AppActivation : IAppActivation, IAppActivationActi
default:
{
await HandleNormalLaunchActionAsync(isRedirectTo).ConfigureAwait(false);
await HandleNormalLaunchActionAsync().ConfigureAwait(false);
break;
}
}

View File

@@ -1,7 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.Extensions.Primitives;
using Microsoft.Windows.AppLifecycle;
namespace Snap.Hutao.Core.LifeCycle;
@@ -10,8 +9,6 @@ internal sealed class HutaoActivationArguments
{
public bool IsRedirectTo { get; set; }
public bool IsToastActivated { get; set; }
public HutaoActivationKind Kind { get; set; }
public Uri? ProtocolActivatedUri { get; set; }
@@ -33,15 +30,6 @@ internal sealed class HutaoActivationArguments
if (args.TryGetLaunchActivatedArguments(out string? arguments))
{
result.LaunchActivatedArguments = arguments;
foreach (StringSegment segment in new StringTokenizer(arguments, [' ']))
{
if (segment.AsSpan().SequenceEqual("-ToastActivated"))
{
result.Kind = HutaoActivationKind.Toast;
break;
}
}
}
break;

View File

@@ -7,6 +7,5 @@ internal enum HutaoActivationKind
{
None,
Launch,
Toast,
Protocol,
}

View File

@@ -1,14 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Core.LifeCycle.InterProcess.Model;
internal sealed class ElevationStatusResponse
{
public ElevationStatusResponse(bool isElevated)
{
IsElevated = isElevated;
}
public bool IsElevated { get; set; }
}

View File

@@ -6,9 +6,6 @@ namespace Snap.Hutao.Core.LifeCycle.InterProcess;
internal enum PipePacketCommand : byte
{
None = 0,
Exit = 1,
RedirectActivation = 10,
RequestElevationStatus = 11,
ResponseElevationStatus = 12,
}

View File

@@ -8,5 +8,5 @@ internal enum PipePacketType : byte
None = 0,
Request = 1,
Response = 2,
SessionTermination = 3,
Termination = 3,
}

View File

@@ -1,84 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Core.ExceptionService;
using System.Buffers;
using System.IO.Hashing;
using System.IO.Pipes;
using System.Runtime.CompilerServices;
namespace Snap.Hutao.Core.LifeCycle.InterProcess;
internal static class PipeStreamExtension
{
public static TData? ReadJsonContent<TData>(this PipeStream stream, ref readonly PipePacketHeader header)
{
using (IMemoryOwner<byte> memoryOwner = MemoryPool<byte>.Shared.Rent(header.ContentLength))
{
Span<byte> content = memoryOwner.Memory.Span[..header.ContentLength];
stream.ReadExactly(content);
HutaoException.ThrowIf(XxHash64.HashToUInt64(content) != header.Checksum, "PipePacket Content Hash incorrect");
return JsonSerializer.Deserialize<TData>(content);
}
}
public static unsafe void ReadPacket<TData>(this PipeStream stream, out PipePacketHeader header, out TData? data)
where TData : class
{
data = default;
stream.ReadPacket(out header);
if (header.ContentType is PipePacketContentType.Json)
{
data = stream.ReadJsonContent<TData>(in header);
}
}
[SkipLocalsInit]
public static unsafe void ReadPacket(this PipeStream stream, out PipePacketHeader header)
{
fixed (PipePacketHeader* pHeader = &header)
{
stream.ReadExactly(new(pHeader, sizeof(PipePacketHeader)));
}
}
public static unsafe void WritePacketWithJsonContent<TData>(this PipeStream stream, byte version, PipePacketType type, PipePacketCommand command, TData data)
{
PipePacketHeader header = default;
header.Version = version;
header.Type = type;
header.Command = command;
header.ContentType = PipePacketContentType.Json;
stream.WritePacket(ref header, JsonSerializer.SerializeToUtf8Bytes(data));
}
public static unsafe void WritePacket(this PipeStream stream, ref PipePacketHeader header, byte[] content)
{
header.ContentLength = content.Length;
header.Checksum = XxHash64.HashToUInt64(content);
stream.WritePacket(in header);
stream.Write(content);
}
public static unsafe void WritePacket(this PipeStream stream, byte version, PipePacketType type, PipePacketCommand command)
{
PipePacketHeader header = default;
header.Version = version;
header.Type = type;
header.Command = command;
stream.WritePacket(in header);
}
public static unsafe void WritePacket(this PipeStream stream, ref readonly PipePacketHeader header)
{
fixed (PipePacketHeader* pHeader = &header)
{
stream.Write(new(pHeader, sizeof(PipePacketHeader)));
}
}
}

View File

@@ -1,10 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Core.LifeCycle.InterProcess;
internal static class PrivateNamedPipe
{
public const int Version = 1;
public const string Name = "Snap.Hutao.PrivateNamedPipe";
}

View File

@@ -2,39 +2,45 @@
// Licensed under the MIT license.
using Microsoft.Windows.AppLifecycle;
using Snap.Hutao.Core.LifeCycle.InterProcess.Model;
using System.IO.Hashing;
using System.IO.Pipes;
namespace Snap.Hutao.Core.LifeCycle.InterProcess;
[Injection(InjectAs.Singleton)]
[ConstructorGenerated]
internal sealed partial class PrivateNamedPipeClient : IDisposable
internal sealed class PrivateNamedPipeClient : IDisposable
{
private readonly NamedPipeClientStream clientStream = new(".", PrivateNamedPipe.Name, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough);
private readonly RuntimeOptions runtimeOptions;
private readonly NamedPipeClientStream clientStream = new(".", "Snap.Hutao.PrivateNamedPipe", PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough);
public unsafe bool TryRedirectActivationTo(AppActivationArguments args)
{
if (clientStream.TryConnectOnce())
{
clientStream.WritePacket(PrivateNamedPipe.Version, PipePacketType.Request, PipePacketCommand.RequestElevationStatus);
clientStream.ReadPacket(out PipePacketHeader header, out ElevationStatusResponse? response);
ArgumentNullException.ThrowIfNull(response);
// Prefer elevated instance
if (runtimeOptions.IsElevated && !response.IsElevated)
{
// Notify previous instance to exit
clientStream.WritePacket(PrivateNamedPipe.Version, PipePacketType.SessionTermination, PipePacketCommand.Exit);
clientStream.Flush();
return false;
PipePacketHeader redirectActivationPacket = default;
redirectActivationPacket.Version = 1;
redirectActivationPacket.Type = PipePacketType.Request;
redirectActivationPacket.Command = PipePacketCommand.RedirectActivation;
redirectActivationPacket.ContentType = PipePacketContentType.Json;
HutaoActivationArguments hutaoArgs = HutaoActivationArguments.FromAppActivationArguments(args, isRedirected: true);
byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(hutaoArgs);
redirectActivationPacket.ContentLength = jsonBytes.Length;
redirectActivationPacket.Checksum = XxHash64.HashToUInt64(jsonBytes);
clientStream.Write(new(&redirectActivationPacket, sizeof(PipePacketHeader)));
clientStream.Write(jsonBytes);
}
{
PipePacketHeader terminationPacket = default;
terminationPacket.Version = 1;
terminationPacket.Type = PipePacketType.Termination;
clientStream.Write(new(&terminationPacket, sizeof(PipePacketHeader)));
}
// Redirect to previous instance
HutaoActivationArguments hutaoArgs = HutaoActivationArguments.FromAppActivationArguments(args, isRedirected: true);
clientStream.WritePacketWithJsonContent(PrivateNamedPipe.Version, PipePacketType.Request, PipePacketCommand.RedirectActivation, hutaoArgs);
clientStream.WritePacket(PrivateNamedPipe.Version, PipePacketType.SessionTermination, PipePacketCommand.None);
clientStream.Flush();
return true;
}

View File

@@ -18,11 +18,4 @@ internal sealed partial class PrivateNamedPipeMessageDispatcher
serviceProvider.GetRequiredService<IAppActivation>().Activate(args);
}
public void ExitApplication()
{
ITaskContext taskContext = serviceProvider.GetRequiredService<ITaskContext>();
App app = serviceProvider.GetRequiredService<App>();
taskContext.BeginInvokeOnMainThread(app.Exit);
}
}

View File

@@ -1,50 +1,22 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Core.LifeCycle.InterProcess.Model;
using Snap.Hutao.Core.ExceptionService;
using System.IO.Hashing;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;
namespace Snap.Hutao.Core.LifeCycle.InterProcess;
[Injection(InjectAs.Singleton)]
[ConstructorGenerated]
internal sealed partial class PrivateNamedPipeServer : IDisposable
{
private readonly PrivateNamedPipeMessageDispatcher messageDispatcher;
private readonly RuntimeOptions runtimeOptions;
private readonly NamedPipeServerStream serverStream = new("Snap.Hutao.PrivateNamedPipe", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough);
private readonly CancellationTokenSource serverTokenSource = new();
private readonly SemaphoreSlim serverSemaphore = new(1);
private readonly NamedPipeServerStream serverStream;
public PrivateNamedPipeServer(IServiceProvider serviceProvider)
{
messageDispatcher = serviceProvider.GetRequiredService<PrivateNamedPipeMessageDispatcher>();
runtimeOptions = serviceProvider.GetRequiredService<RuntimeOptions>();
PipeSecurity? pipeSecurity = default;
if (runtimeOptions.IsElevated)
{
SecurityIdentifier everyOne = new(WellKnownSidType.WorldSid, null);
pipeSecurity = new();
pipeSecurity.AddAccessRule(new PipeAccessRule(everyOne, PipeAccessRights.FullControl, AccessControlType.Allow));
}
serverStream = NamedPipeServerStreamAcl.Create(
PrivateNamedPipe.Name,
PipeDirection.InOut,
NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.WriteThrough,
0,
0,
pipeSecurity);
}
public void Dispose()
{
serverTokenSource.Cancel();
@@ -73,30 +45,36 @@ internal sealed partial class PrivateNamedPipeServer : IDisposable
}
}
private static unsafe byte[] GetValidatedContent(NamedPipeServerStream serverStream, PipePacketHeader* header)
{
byte[] content = new byte[header->ContentLength];
serverStream.ReadAtLeast(content, header->ContentLength, false);
HutaoException.ThrowIf(XxHash64.HashToUInt64(content) != header->Checksum, "PipePacket Content Hash incorrect");
return content;
}
private unsafe void RunPacketSession(NamedPipeServerStream serverStream, CancellationToken token)
{
while (serverStream.IsConnected && !token.IsCancellationRequested)
Span<byte> headerSpan = stackalloc byte[sizeof(PipePacketHeader)];
bool sessionTerminated = false;
while (serverStream.IsConnected && !sessionTerminated && !token.IsCancellationRequested)
{
serverStream.ReadPacket(out PipePacketHeader header);
switch ((header.Type, header.Command))
serverStream.ReadExactly(headerSpan);
fixed (byte* pHeader = headerSpan)
{
case (PipePacketType.Request, PipePacketCommand.RequestElevationStatus):
ElevationStatusResponse resp = new(runtimeOptions.IsElevated);
serverStream.WritePacketWithJsonContent(PrivateNamedPipe.Version, PipePacketType.Response, PipePacketCommand.ResponseElevationStatus, resp);
serverStream.Flush();
break;
case (PipePacketType.Request, PipePacketCommand.RedirectActivation):
HutaoActivationArguments? hutaoArgs = serverStream.ReadJsonContent<HutaoActivationArguments>(in header);
messageDispatcher.RedirectActivation(hutaoArgs);
break;
case (PipePacketType.SessionTermination, _):
serverStream.Disconnect();
if (header.Command is PipePacketCommand.Exit)
{
messageDispatcher.ExitApplication();
}
PipePacketHeader* header = (PipePacketHeader*)pHeader;
return;
switch ((header->Type, header->Command, header->ContentType))
{
case (PipePacketType.Request, PipePacketCommand.RedirectActivation, PipePacketContentType.Json):
ReadOnlySpan<byte> content = GetValidatedContent(serverStream, header);
messageDispatcher.RedirectActivation(JsonSerializer.Deserialize<HutaoActivationArguments>(content));
break;
case (PipePacketType.Termination, _, _):
serverStream.Disconnect();
sessionTerminated = true;
return;
}
}
}
}

View File

@@ -27,11 +27,4 @@ internal static class RuntimeOptionsExtension
Directory.CreateDirectory(directory);
return directory;
}
public static string GetLocalCacheImageCacheFolder(this RuntimeOptions options)
{
string directory = Path.Combine(options.LocalCache, "ImageCache");
Directory.CreateDirectory(directory);
return directory;
}
}

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

@@ -67,7 +67,7 @@ internal sealed partial class ShellLinkInterop : IShellLinkInterop
IUnknownMarshal.Release(pPersistFile);
}
IUnknownMarshal.Release(pShellLink);
uint value = IUnknownMarshal.Release(pShellLink);
}
return result;

View File

@@ -7,22 +7,22 @@ namespace Snap.Hutao.Core.Threading;
internal static class SpinWaitPolyfill
{
public static unsafe void SpinUntil<T>(ref readonly T state, delegate*<ref readonly T, bool> condition)
public static unsafe void SpinUntil<T>(ref T state, delegate*<ref readonly T, bool> condition)
{
SpinWait spinner = default;
while (!condition(in state))
while (!condition(ref state))
{
spinner.SpinOnce();
}
}
[SuppressMessage("", "SH002")]
public static unsafe bool SpinUntil<T>(ref readonly T state, delegate*<ref readonly T, bool> condition, TimeSpan timeout)
public static unsafe bool SpinUntil<T>(ref T state, delegate*<ref readonly T, bool> condition, TimeSpan timeout)
{
long startTime = Stopwatch.GetTimestamp();
SpinWait spinner = default;
while (!condition(in state))
while (!condition(ref state))
{
spinner.SpinOnce();

View File

@@ -103,7 +103,7 @@ internal static class TypeNameHelper
if (builder is null)
{
if (options.NestedTypeDelimiter is not DefaultNestedTypeDelimiter)
if (options.NestedTypeDelimiter != DefaultNestedTypeDelimiter)
{
return name.Replace(DefaultNestedTypeDelimiter, options.NestedTypeDelimiter);
}
@@ -112,7 +112,7 @@ internal static class TypeNameHelper
}
builder.Append(name);
if (options.NestedTypeDelimiter is not DefaultNestedTypeDelimiter)
if (options.NestedTypeDelimiter != DefaultNestedTypeDelimiter)
{
builder.Replace(DefaultNestedTypeDelimiter, options.NestedTypeDelimiter, builder.Length - name.Length, name.Length);
}

View File

@@ -8,6 +8,4 @@ namespace Snap.Hutao.Core.Windowing.Abstraction;
internal interface IXamlWindowHasInitSize
{
SizeInt32 InitSize { get; }
SizeInt32 MinSize { get; }
}

View File

@@ -1,18 +1,19 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using System.Runtime.CompilerServices;
using Windows.Graphics;
namespace Snap.Hutao.Core.Windowing;
internal readonly struct RectInt16
internal readonly struct CompactRect
{
private readonly short x;
private readonly short y;
private readonly short width;
private readonly short height;
private RectInt16(int x, int y, int width, int height)
private CompactRect(int x, int y, int width, int height)
{
this.x = (short)x;
this.y = (short)y;
@@ -20,22 +21,24 @@ internal readonly struct RectInt16
this.height = (short)height;
}
public static implicit operator RectInt32(RectInt16 rect)
public static implicit operator RectInt32(CompactRect rect)
{
return new(rect.x, rect.y, rect.width, rect.height);
}
public static explicit operator RectInt16(RectInt32 rect)
public static explicit operator CompactRect(RectInt32 rect)
{
return new(rect.X, rect.Y, rect.Width, rect.Height);
}
public static unsafe explicit operator RectInt16(ulong value)
public static unsafe explicit operator CompactRect(ulong value)
{
return *(RectInt16*)&value;
Unsafe.SkipInit(out CompactRect rect);
*(ulong*)&rect = value;
return rect;
}
public static unsafe implicit operator ulong(RectInt16 rect)
public static unsafe implicit operator ulong(CompactRect rect)
{
return *(ulong*)&rect;
}

View File

@@ -2,7 +2,6 @@
// Licensed under the MIT license.
using Microsoft.UI.Xaml.Controls;
using Snap.Hutao.Control.Extension;
using Snap.Hutao.ViewModel;
namespace Snap.Hutao.Core.Windowing.NotifyIcon;
@@ -13,6 +12,6 @@ internal sealed partial class NotifyIconContextMenu : Flyout
{
AllowFocusOnInteraction = false;
InitializeComponent();
Root.InitializeDataContext<NotifyIconViewModel>(serviceProvider);
Root.DataContext = serviceProvider.GetRequiredService<NotifyIconViewModel>();
}
}

View File

@@ -37,7 +37,6 @@ internal sealed class NotifyIconController : IDisposable
{
TaskbarCreated = OnRecreateNotifyIconRequested,
ContextMenuRequested = OnContextMenuRequested,
IconSelected = OnContextMenuRequested,
};
CreateNotifyIcon();

View File

@@ -62,8 +62,6 @@ internal sealed class NotifyIconMessageWindow : IDisposable
public Action<NotifyIconMessageWindow, PointUInt16>? ContextMenuRequested { get; set; }
public Action<NotifyIconMessageWindow, PointUInt16>? IconSelected { get; set; }
public HWND HWND { get; }
public void Dispose()
@@ -118,7 +116,6 @@ internal sealed class NotifyIconMessageWindow : IDisposable
break;
case NIN_SELECT:
// X: wParam2.X Y: wParam2.Y Low: NIN_SELECT
window.IconSelected?.Invoke(window, wParam2);
break;
case NIN_POPUPOPEN:
// X: wParam2.X Y: 0? Low: NIN_POPUPOPEN

View File

@@ -63,8 +63,7 @@ internal static class WindowExtension
{
ShowWindow(hwnd, SHOW_WINDOW_CMD.SW_SHOW);
}
if (IsIconic(hwnd))
else if (IsIconic(hwnd))
{
ShowWindow(hwnd, SHOW_WINDOW_CMD.SW_RESTORE);
}

View File

@@ -99,12 +99,14 @@ internal sealed class XamlWindowController
private void OnWindowClosed(object sender, WindowEventArgs args)
{
if (XamlLifetime.ApplicationLaunchedWithNotifyIcon && !XamlLifetime.ApplicationExiting)
if (XamlWindowLifetime.ApplicationLaunchedWithNotifyIcon && !XamlWindowLifetime.ApplicationExiting)
{
args.Handled = true;
window.Hide();
if (!IsNotifyIconVisible())
RECT iconRect = serviceProvider.GetRequiredService<NotifyIconController>().GetRect();
RECT primaryRect = StructMarshal.RECT(DisplayArea.Primary.OuterBounds);
if (!IntersectRect(out _, in primaryRect, in iconRect))
{
new ToastContentBuilder()
.AddText(SH.CoreWindowingNotifyIconPromotedHint)
@@ -131,35 +133,6 @@ internal sealed class XamlWindowController
}
}
private bool IsNotifyIconVisible()
{
// Shell_NotifyIconGetRect returns E_FAIL when Shell_TrayWnd is not present,
// We pre-check it to avoid the exception.
HWND shellTrayWnd = FindWindowExW(default, default, "Shell_TrayWnd", default);
if (shellTrayWnd == default)
{
return false;
}
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 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
private void OnOptionsPropertyChanged(object? sender, PropertyChangedEventArgs e)
@@ -237,18 +210,15 @@ internal sealed class XamlWindowController
private void RecoverOrInitWindowSize(IXamlWindowHasInitSize xamlWindow)
{
double scale = window.GetRasterizationScale();
RectInt32 rect = StructMarshal.RectInt32(xamlWindow.InitSize.Scale(scale));
SizeInt32 scaledSize = xamlWindow.InitSize.Scale(scale);
RectInt32 rect = StructMarshal.RectInt32(scaledSize);
if (window is IXamlWindowRectPersisted rectPersisted)
{
RectInt32 nonDpiPersistedRect = (RectInt16)LocalSetting.Get(rectPersisted.PersistRectKey, (RectInt16)rect);
RectInt32 persistedRect = nonDpiPersistedRect.Scale(scale);
// If the persisted size is less than min size, we want to reset to the init size.
// So we only recover the size when it's greater than or equal to the min size.
if (persistedRect.Size() >= xamlWindow.MinSize.Size())
RectInt32 persistedRect = (CompactRect)LocalSetting.Get(rectPersisted.PersistRectKey, (CompactRect)rect);
if (persistedRect.Size() >= xamlWindow.InitSize.Size())
{
rect = persistedRect;
rect = persistedRect.Scale(scale);
}
}
@@ -264,9 +234,8 @@ internal sealed class XamlWindowController
// prevent save value when we are maximized.
if (!windowPlacement.ShowCmd.HasFlag(SHOW_WINDOW_CMD.SW_SHOWMAXIMIZED))
{
// We save the non-dpi rect here
double scale = 1.0 / window.GetRasterizationScale();
LocalSetting.Set(rectPersisted.PersistRectKey, (RectInt16)window.AppWindow.GetRect().Scale(scale));
LocalSetting.Set(rectPersisted.PersistRectKey, (CompactRect)window.AppWindow.GetRect().Scale(scale));
}
}
#endregion

View File

@@ -3,7 +3,7 @@
namespace Snap.Hutao.Core.Windowing;
internal static class XamlLifetime
internal static class XamlWindowLifetime
{
public static bool ApplicationLaunchedWithNotifyIcon { get; set; }

View File

@@ -96,7 +96,7 @@ internal sealed class XamlWindowSubclass : IDisposable
}
}
if (XamlLifetime.ApplicationExiting)
if (XamlWindowLifetime.ApplicationExiting)
{
return default;
}

View File

@@ -3,8 +3,6 @@
namespace Snap.Hutao.Core;
// See %PROGRAMFILES(X86)%\Windows Kits\10\Platforms\UAP\
// Windows.Foundation.UniversalApiContract
internal enum WindowsVersion : ushort
{
/// <summary>

View File

@@ -104,7 +104,7 @@ internal static partial class EnumerableExtension
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ObservableReorderableDbCollection<TEntityOnly, TEntity> ToObservableReorderableDbCollection<TEntityOnly, TEntity>(this IEnumerable<TEntityOnly> source, IServiceProvider serviceProvider)
where TEntityOnly : class, IEntityAccess<TEntity>
where TEntityOnly : class, IEntityOnly<TEntity>
where TEntity : class, IReorderable
{
return source is List<TEntityOnly> list

View File

@@ -1,7 +1,6 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Snap.Hutao.Core.Setting;
using Snap.Hutao.Core.Windowing;
@@ -29,12 +28,6 @@ internal sealed partial class GuideWindow : Window,
public GuideWindow(IServiceProvider serviceProvider)
{
InitializeComponent();
if (AppWindow.Presenter is OverlappedPresenter presenter)
{
presenter.IsMaximizable = false;
}
this.InitializeController(serviceProvider);
}
@@ -44,8 +37,6 @@ internal sealed partial class GuideWindow : Window,
public SizeInt32 InitSize { get; } = new(MinWidth, MinHeight);
public SizeInt32 MinSize { get; } = new(MinWidth, MinHeight);
public unsafe void HandleMinMaxInfo(ref MINMAXINFO info, double scalingFactor)
{
info.ptMinTrackSize.x = (int)Math.Max(MinWidth * scalingFactor, info.ptMinTrackSize.x);

View File

@@ -47,8 +47,6 @@ internal sealed partial class LaunchGameWindow : Window,
public SizeInt32 InitSize { get; } = new(MaxWidth, MaxHeight);
public SizeInt32 MinSize { get; } = new(MinWidth, MinHeight);
/// <inheritdoc/>
public void Dispose()
{

View File

@@ -39,8 +39,6 @@ internal sealed partial class MainWindow : Window,
public SizeInt32 InitSize { get; } = new(1200, 741);
public SizeInt32 MinSize { get; } = new(MinWidth, MinHeight);
/// <inheritdoc/>
public unsafe void HandleMinMaxInfo(ref MINMAXINFO pInfo, double scalingFactor)
{

View File

@@ -1,14 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Model;
internal interface IEntityAccessWithMetadata<out TEntity, out TMetadata> : IEntityAccess<TEntity>
{
TMetadata Inner { get; }
}
internal interface IEntityAccess<out TEntity>
{
TEntity Entity { get; }
}

View File

@@ -0,0 +1,26 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Model;
/// <summary>
/// 实体与元数据
/// </summary>
/// <typeparam name="TEntity">实体</typeparam>
/// <typeparam name="TMetadata">元数据</typeparam>
[HighQuality]
internal interface IEntityWithMetadata<out TEntity, out TMetadata> : IEntityOnly<TEntity>
{
/// <summary>
/// 元数据
/// </summary>
TMetadata Inner { get; }
}
internal interface IEntityOnly<out TEntity>
{
/// <summary>
/// 实体
/// </summary>
TEntity Entity { get; }
}

View File

@@ -97,11 +97,6 @@ internal static class AvatarIds
public static readonly AvatarId Navia = 10000091;
public static readonly AvatarId Gaming = 10000092;
public static readonly AvatarId Xianyun = 10000093;
public static readonly AvatarId Chiori = 10000094;
public static readonly AvatarId Sigewinne = 10000095;
public static readonly AvatarId Arlecchino = 10000096;
public static readonly AvatarId Sethos = 10000097;
public static readonly AvatarId Clorinde = 10000098;
/// <summary>
/// 检查该角色是否为主角

View File

@@ -75,7 +75,7 @@ internal sealed class Material : DisplayItem
DayOfWeek.Monday or DayOfWeek.Thursday => Materials.MondayThursdayItems.Contains(Id),
DayOfWeek.Tuesday or DayOfWeek.Friday => Materials.TuesdayFridayItems.Contains(Id),
DayOfWeek.Wednesday or DayOfWeek.Saturday => Materials.WednesdaySaturdayItems.Contains(Id),
_ => treatSundayAsTrue && (Materials.MondayThursdayItems.Contains(Id) || Materials.TuesdayFridayItems.Contains(Id) || Materials.WednesdaySaturdayItems.Contains(Id)),
_ => treatSundayAsTrue,
};
}

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>
@@ -46,12 +46,12 @@
</uap:VisualElements>
<Extensions>
<desktop:Extension Category="windows.toastNotificationActivation">
<desktop:ToastNotificationActivation ToastActivatorCLSID="5760EC4D-F7E8-4666-A965-9886D7DFFE7D"/>
<desktop:ToastNotificationActivation ToastActivatorCLSID="5760ec4d-f7e8-4666-a965-9886d7dffe7d"/>
</desktop:Extension>
<com:Extension Category="windows.comServer">
<com:ComServer>
<com:ExeServer Executable="Snap.Hutao.exe" Arguments="-ToastActivated" DisplayName="Snap Hutao Toast Activator">
<com:Class Id="5760EC4D-F7E8-4666-A965-9886D7DFFE7D" DisplayName="Snap Hutao Toast Activator"/>
<com:Class Id="5760ec4d-f7e8-4666-a965-9886d7dffe7d" DisplayName="Snap Hutao Toast Activator"/>
</com:ExeServer>
</com:ComServer>
</com:Extension>

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>
@@ -46,12 +46,12 @@
</uap:VisualElements>
<Extensions>
<desktop:Extension Category="windows.toastNotificationActivation">
<desktop:ToastNotificationActivation ToastActivatorCLSID="F32B561D-752E-472B-A22C-85824D421E1A"/>
<desktop:ToastNotificationActivation ToastActivatorCLSID="5760ec4d-f7e8-4666-a965-9886d7dffe7d"/>
</desktop:Extension>
<com:Extension Category="windows.comServer">
<com:ComServer>
<com:ExeServer Executable="Snap.Hutao.exe" Arguments="-ToastActivated" DisplayName="Snap Hutao Dev Toast Activator">
<com:Class Id="F32B561D-752E-472B-A22C-85824D421E1A" DisplayName="Snap Hutao Dev Toast Activator"/>
<com:Class Id="5760ec4d-f7e8-4666-a965-9886d7dffe7d" DisplayName="Snap Hutao Dev Toast Activator"/>
</com:ExeServer>
</com:ComServer>
</com:Extension>

View File

@@ -192,18 +192,6 @@
<data name="CoreWindowHotkeyCombinationRegisterFailed" xml:space="preserve">
<value>Register [{0}] hotkey [{1}] failed</value>
</data>
<data name="CoreWindowingNotifyIconExitLabel" xml:space="preserve">
<value>退出</value>
</data>
<data name="CoreWindowingNotifyIconLaunchGameLabel" xml:space="preserve">
<value>Launch</value>
</data>
<data name="CoreWindowingNotifyIconPromotedHint" xml:space="preserve">
<value>胡桃已进入后台运行</value>
</data>
<data name="CoreWindowingNotifyIconViewLabel" xml:space="preserve">
<value>窗口</value>
</data>
<data name="CoreWindowThemeDark" xml:space="preserve">
<value>Dark</value>
</data>
@@ -1568,12 +1556,6 @@
<data name="ViewModelCultivationProjectInvalidName" xml:space="preserve">
<value>Can't add plan with invalid name</value>
</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">
<value>Realtime Note Webhook URL successfully configured</value>
</data>
@@ -1964,9 +1946,6 @@
<data name="ViewPageDailyNoteNotificationSetting" xml:space="preserve">
<value>Notification Settings</value>
</data>
<data name="ViewPageDailyNoteNotificationUnavailableHint" xml:space="preserve">
<value>胡桃的通知权限已被关闭</value>
</data>
<data name="ViewPageDailyNoteRefresh" xml:space="preserve">
<value>Refresh</value>
</data>
@@ -1997,9 +1976,6 @@
<data name="ViewPageDailyNoteSettingRefreshHeader" xml:space="preserve">
<value>Refresh</value>
</data>
<data name="ViewPageDailyNoteSettingRefreshNotifyIconDisabledHint" xml:space="preserve">
<value>未启用通知区域图标,关闭窗口后自动刷新将不会执行</value>
</data>
<data name="ViewPageDailyNoteSlientModeDescription" xml:space="preserve">
<value>Do not disturb during Genshin gaming</value>
</data>
@@ -2678,12 +2654,6 @@
<data name="ViewPageSettingKeyShortcutHeader" xml:space="preserve">
<value>Shortcut Keys</value>
</data>
<data name="ViewPageSettingNotifyIconDescription" xml:space="preserve">
<value>在通知区域显示图标,以允许执行后台任务,重启后生效</value>
</data>
<data name="ViewPageSettingNotifyIconHeader" xml:space="preserve">
<value>通知区域图标</value>
</data>
<data name="ViewPageSettingOfficialSiteNavigate" xml:space="preserve">
<value>Official Website</value>
</data>
@@ -3036,7 +3006,7 @@
<value>Weapon WIKI</value>
</data>
<data name="WebAnnouncementMatchPermanentActivityTime" xml:space="preserve">
<value>(?:(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)|&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;)后永久开放</value>
<value>(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)后永久开放</value>
</data>
<data name="WebAnnouncementMatchPersistentActivityTime" xml:space="preserve">
<value>〓活动时间〓.*?(\d\.\d)版本期间持续开放</value>
@@ -3074,9 +3044,6 @@
<data name="WebBridgeShareCopyToClipboardSuccess" xml:space="preserve">
<value>Copied to clipboard</value>
</data>
<data name="WebDailyNoteArchonQuestChapterFinished" xml:space="preserve">
<value>All Archon Quest Completed</value>
</data>
<data name="WebDailyNoteArchonQuestStatusFinished" xml:space="preserve">
<value>Completed</value>
</data>
@@ -3257,9 +3224,6 @@
<data name="WebResponseRequestExceptionFormat" xml:space="preserve">
<value>[{1}] network request exception in [{0}] please try again later</value>
</data>
<data name="WebResponseSignInErrorHint" xml:space="preserve">
<value>登录失败,请前往 HoYoLAB 初始化账号,原始消息:{0}</value>
</data>
<data name="WindowIdentifyMonitorHeader" xml:space="preserve">
<value>Monitor ID</value>
</data>

View File

@@ -192,18 +192,6 @@
<data name="CoreWindowHotkeyCombinationRegisterFailed" xml:space="preserve">
<value>Échec de l'enregistrement de [{0}] en touche de raccourci [{1}]</value>
</data>
<data name="CoreWindowingNotifyIconExitLabel" xml:space="preserve">
<value>退出</value>
</data>
<data name="CoreWindowingNotifyIconLaunchGameLabel" xml:space="preserve">
<value>Lanceur de jeu</value>
</data>
<data name="CoreWindowingNotifyIconPromotedHint" xml:space="preserve">
<value>胡桃已进入后台运行</value>
</data>
<data name="CoreWindowingNotifyIconViewLabel" xml:space="preserve">
<value>窗口</value>
</data>
<data name="CoreWindowThemeDark" xml:space="preserve">
<value>Sombre</value>
</data>
@@ -421,7 +409,7 @@
<comment>Need EXACT same string in game</comment>
</data>
<data name="ModelMetadataAvatarPlayerName" xml:space="preserve">
<value>Voyageur</value>
<value>旅行者</value>
</data>
<data name="ModelMetadataFetterInfoBirthdayFormat" xml:space="preserve">
<value>{0} 月 {1} 日</value>
@@ -1485,7 +1473,7 @@
<value>有新的通知</value>
</data>
<data name="ViewLaunchGameHeader" xml:space="preserve">
<value>Lanceur de jeu</value>
<value>启动游戏</value>
</data>
<data name="ViewListViewDragElevatedHint" xml:space="preserve">
<value>管理员模式下无法拖动排序</value>
@@ -1568,12 +1556,6 @@
<data name="ViewModelCultivationProjectInvalidName" xml:space="preserve">
<value>不能添加名称无效的计划</value>
</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">
<value>实时便笺 Webhook Url 配置成功</value>
</data>
@@ -1665,7 +1647,7 @@
<value>我已阅读并同意上方的条款</value>
</data>
<data name="ViewModelGuideActionComplete" xml:space="preserve">
<value>Terminer</value>
<value>完成</value>
</data>
<data name="ViewModelGuideActionNext" xml:space="preserve">
<value>下一步</value>
@@ -1791,7 +1773,7 @@
<value>下载完成</value>
</data>
<data name="ViewModelWelcomeDownloadSummaryComplete" xml:space="preserve">
<value>Terminer</value>
<value>完成</value>
</data>
<data name="ViewModelWelcomeDownloadSummaryContentTypeNotMatch" xml:space="preserve">
<value>响应内容不是有效的文件字节流</value>
@@ -1809,7 +1791,7 @@
<value>创建新存档以继续</value>
</data>
<data name="ViewPageAchievementExportLabel" xml:space="preserve">
<value>Exporter</value>
<value>导出</value>
</data>
<data name="ViewPageAchievementImportFromClipboard" xml:space="preserve">
<value>从剪贴板导入</value>
@@ -1818,7 +1800,7 @@
<value>从 UIAF 文件导入</value>
</data>
<data name="ViewPageAchievementImportLabel" xml:space="preserve">
<value>Importer</value>
<value>导入</value>
</data>
<data name="ViewPageAchievementRemoveArchive" xml:space="preserve">
<value>删除当前存档</value>
@@ -1964,9 +1946,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>
@@ -1997,9 +1976,6 @@
<data name="ViewPageDailyNoteSettingRefreshHeader" xml:space="preserve">
<value>刷新</value>
</data>
<data name="ViewPageDailyNoteSettingRefreshNotifyIconDisabledHint" xml:space="preserve">
<value>未启用通知区域图标,关闭窗口后自动刷新将不会执行</value>
</data>
<data name="ViewPageDailyNoteSlientModeDescription" xml:space="preserve">
<value>在我游玩原神时不通知我</value>
</data>
@@ -2055,7 +2031,7 @@
<value>全量刷新</value>
</data>
<data name="ViewPageGachaLogExportAction" xml:space="preserve">
<value>Exporter</value>
<value>导出</value>
</data>
<data name="ViewPageGachaLogHint" xml:space="preserve">
<value>尚未获取任何祈愿记录</value>
@@ -2091,7 +2067,7 @@
<value>上传当前的祈愿存档</value>
</data>
<data name="ViewPageGachaLogImportAction" xml:space="preserve">
<value>Importer</value>
<value>导入</value>
</data>
<data name="ViewPageGachaLogImportDescription" xml:space="preserve">
<value>导入来自其它 App 的数据</value>
@@ -2262,7 +2238,7 @@
<value>请输入验证码</value>
</data>
<data name="ViewPageLaunchGameAction" xml:space="preserve">
<value>Lanceur de jeu</value>
<value>启动游戏</value>
</data>
<data name="ViewPageLaunchGameAdvanceHeader" xml:space="preserve">
<value>高级功能</value>
@@ -2607,7 +2583,7 @@
<value>祈愿记录</value>
</data>
<data name="ViewpageSettingHomeCardItemLaunchGameHeader" xml:space="preserve">
<value>Lanceur de jeu</value>
<value>启动游戏</value>
</data>
<data name="ViewPageSettingHomeCardOff" xml:space="preserve">
<value>隐藏</value>
@@ -2678,12 +2654,6 @@
<data name="ViewPageSettingKeyShortcutHeader" xml:space="preserve">
<value>快捷键</value>
</data>
<data name="ViewPageSettingNotifyIconDescription" xml:space="preserve">
<value>在通知区域显示图标,以允许执行后台任务,重启后生效</value>
</data>
<data name="ViewPageSettingNotifyIconHeader" xml:space="preserve">
<value>通知区域图标</value>
</data>
<data name="ViewPageSettingOfficialSiteNavigate" xml:space="preserve">
<value>前往官网</value>
</data>
@@ -3036,7 +3006,7 @@
<value>武器资料</value>
</data>
<data name="WebAnnouncementMatchPermanentActivityTime" xml:space="preserve">
<value>(?:(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)|&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;)后永久开放</value>
<value>(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)后永久开放</value>
</data>
<data name="WebAnnouncementMatchPersistentActivityTime" xml:space="preserve">
<value>〓活动时间〓.*?(\d\.\d)版本期间持续开放</value>
@@ -3074,9 +3044,6 @@
<data name="WebBridgeShareCopyToClipboardSuccess" xml:space="preserve">
<value>已复制到剪贴板</value>
</data>
<data name="WebDailyNoteArchonQuestChapterFinished" xml:space="preserve">
<value>所有魔神任务已完成</value>
</data>
<data name="WebDailyNoteArchonQuestStatusFinished" xml:space="preserve">
<value>全部完成</value>
</data>
@@ -3257,9 +3224,6 @@
<data name="WebResponseRequestExceptionFormat" xml:space="preserve">
<value>[{0}] 中的 [{1}] 网络请求异常,请稍后再试</value>
</data>
<data name="WebResponseSignInErrorHint" xml:space="preserve">
<value>登录失败,请前往 HoYoLAB 初始化账号,原始消息:{0}</value>
</data>
<data name="WindowIdentifyMonitorHeader" xml:space="preserve">
<value>显示器编号</value>
</data>

View File

@@ -192,18 +192,6 @@
<data name="CoreWindowHotkeyCombinationRegisterFailed" xml:space="preserve">
<value>[{0}] Hotkey [{1}] gagal terdaftar</value>
</data>
<data name="CoreWindowingNotifyIconExitLabel" xml:space="preserve">
<value>退出</value>
</data>
<data name="CoreWindowingNotifyIconLaunchGameLabel" xml:space="preserve">
<value>Luncurkan</value>
</data>
<data name="CoreWindowingNotifyIconPromotedHint" xml:space="preserve">
<value>胡桃已进入后台运行</value>
</data>
<data name="CoreWindowingNotifyIconViewLabel" xml:space="preserve">
<value>窗口</value>
</data>
<data name="CoreWindowThemeDark" xml:space="preserve">
<value>深色</value>
</data>
@@ -1568,12 +1556,6 @@
<data name="ViewModelCultivationProjectInvalidName" xml:space="preserve">
<value>Tidak dapat menambahkan rencana dengan nama yang salah.</value>
</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">
<value>URL Webhook Catatan Realtime berhasil dikonfigurasi.</value>
</data>
@@ -1964,9 +1946,6 @@
<data name="ViewPageDailyNoteNotificationSetting" xml:space="preserve">
<value>Pengaturan notifikasi</value>
</data>
<data name="ViewPageDailyNoteNotificationUnavailableHint" xml:space="preserve">
<value>胡桃的通知权限已被关闭</value>
</data>
<data name="ViewPageDailyNoteRefresh" xml:space="preserve">
<value>Segarkan sekarang</value>
</data>
@@ -1997,9 +1976,6 @@
<data name="ViewPageDailyNoteSettingRefreshHeader" xml:space="preserve">
<value>Perbarui</value>
</data>
<data name="ViewPageDailyNoteSettingRefreshNotifyIconDisabledHint" xml:space="preserve">
<value>未启用通知区域图标,关闭窗口后自动刷新将不会执行</value>
</data>
<data name="ViewPageDailyNoteSlientModeDescription" xml:space="preserve">
<value>Jangan ganggu selama bermain Genshin</value>
</data>
@@ -2678,12 +2654,6 @@
<data name="ViewPageSettingKeyShortcutHeader" xml:space="preserve">
<value>Tombol Pintas</value>
</data>
<data name="ViewPageSettingNotifyIconDescription" xml:space="preserve">
<value>在通知区域显示图标,以允许执行后台任务,重启后生效</value>
</data>
<data name="ViewPageSettingNotifyIconHeader" xml:space="preserve">
<value>通知区域图标</value>
</data>
<data name="ViewPageSettingOfficialSiteNavigate" xml:space="preserve">
<value>Website Resmi</value>
</data>
@@ -3036,7 +3006,7 @@
<value>Senjata WIKI</value>
</data>
<data name="WebAnnouncementMatchPermanentActivityTime" xml:space="preserve">
<value>(?:(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)|&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;)后永久开放</value>
<value>(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)后永久开放</value>
</data>
<data name="WebAnnouncementMatchPersistentActivityTime" xml:space="preserve">
<value>〓活动时间〓.*?(\d\.\d)版本期间持续开放</value>
@@ -3074,9 +3044,6 @@
<data name="WebBridgeShareCopyToClipboardSuccess" xml:space="preserve">
<value>Disalin ke clipboard</value>
</data>
<data name="WebDailyNoteArchonQuestChapterFinished" xml:space="preserve">
<value>所有魔神任务已完成</value>
</data>
<data name="WebDailyNoteArchonQuestStatusFinished" xml:space="preserve">
<value>Selesai</value>
</data>
@@ -3257,9 +3224,6 @@
<data name="WebResponseRequestExceptionFormat" xml:space="preserve">
<value>[{1}] pengecualian permintaan jaringan di [{0}], harap coba lagi nanti</value>
</data>
<data name="WebResponseSignInErrorHint" xml:space="preserve">
<value>登录失败,请前往 HoYoLAB 初始化账号,原始消息:{0}</value>
</data>
<data name="WindowIdentifyMonitorHeader" xml:space="preserve">
<value>ID Monitor</value>
</data>

View File

@@ -145,7 +145,7 @@
<value>保存</value>
</data>
<data name="ControlAutoSuggestBoxNotFoundValue" xml:space="preserve">
<value>検索結果なし</value>
<value>未找到结果</value>
</data>
<data name="ControlImageCachedImageInvalidResourceUri" xml:space="preserve">
<value>無効なURL</value>
@@ -192,18 +192,6 @@
<data name="CoreWindowHotkeyCombinationRegisterFailed" xml:space="preserve">
<value>[{0}] 热键 [{1}] 注册失败</value>
</data>
<data name="CoreWindowingNotifyIconExitLabel" xml:space="preserve">
<value>退出</value>
</data>
<data name="CoreWindowingNotifyIconLaunchGameLabel" xml:space="preserve">
<value>ゲームランチャー</value>
</data>
<data name="CoreWindowingNotifyIconPromotedHint" xml:space="preserve">
<value>胡桃已进入后台运行</value>
</data>
<data name="CoreWindowingNotifyIconViewLabel" xml:space="preserve">
<value>窗口</value>
</data>
<data name="CoreWindowThemeDark" xml:space="preserve">
<value>深色</value>
</data>
@@ -795,13 +783,13 @@
<value>キャラクターラインナップ:{0:MM-dd HH:mm}</value>
</data>
<data name="ServiceBackgroundImageTypeBing" xml:space="preserve">
<value>Bingからのランダム画像</value>
<value>必应每日一图</value>
</data>
<data name="ServiceBackgroundImageTypeDaily" xml:space="preserve">
<value>日替わり胡桃画像</value>
<value>胡桃每日一图</value>
</data>
<data name="ServiceBackgroundImageTypeLauncher" xml:space="preserve">
<value>公式ランチャー背景</value>
<value>官方启动器壁纸</value>
</data>
<data name="ServiceBackgroundImageTypeLocalFolder" xml:space="preserve">
<value>本地随机图片</value>
@@ -885,7 +873,7 @@
<value>イベント祈願・キャラクター</value>
</data>
<data name="ServiceGachaLogFactoryChronicledWishName" xml:space="preserve">
<value>集録祈願</value>
<value>集录祈愿</value>
</data>
<data name="ServiceGachaLogFactoryPermanentWishName" xml:space="preserve">
<value>奔走世間</value>
@@ -1568,12 +1556,6 @@
<data name="ViewModelCultivationProjectInvalidName" xml:space="preserve">
<value>育成計画名に無効な言葉が入っています</value>
</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">
<value>リアルタイムートのWebhook URLの設定に成功しました。</value>
</data>
@@ -1964,9 +1946,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>
@@ -1997,9 +1976,6 @@
<data name="ViewPageDailyNoteSettingRefreshHeader" xml:space="preserve">
<value>更新</value>
</data>
<data name="ViewPageDailyNoteSettingRefreshNotifyIconDisabledHint" xml:space="preserve">
<value>未启用通知区域图标,关闭窗口后自动刷新将不会执行</value>
</data>
<data name="ViewPageDailyNoteSlientModeDescription" xml:space="preserve">
<value>プレイ中に通知をオフ</value>
</data>
@@ -2678,20 +2654,14 @@
<data name="ViewPageSettingKeyShortcutHeader" xml:space="preserve">
<value>ショートカットキー</value>
</data>
<data name="ViewPageSettingNotifyIconDescription" xml:space="preserve">
<value>在通知区域显示图标,以允许执行后台任务,重启后生效</value>
</data>
<data name="ViewPageSettingNotifyIconHeader" xml:space="preserve">
<value>通知区域图标</value>
</data>
<data name="ViewPageSettingOfficialSiteNavigate" xml:space="preserve">
<value>公式サイト</value>
</data>
<data name="ViewPageSettingOpenBackgroundImageFolderDescription" xml:space="preserve">
<value>カスタム背景を設定する / bmp、git、ico、jpg、jpeg、png、tiffwebp形式をサポートしています</value>
<value>自定义背景图片,支持 bmp / gif / ico / jpg / jpeg / png / tiff / webp 格式</value>
</data>
<data name="ViewPageSettingOpenBackgroundImageFolderHeader" xml:space="preserve">
<value>カスタム背景フォルダーを開く</value>
<value>打开背景图片文件夹</value>
</data>
<data name="ViewPageSettingResetAction" xml:space="preserve">
<value>リセット</value>
@@ -3036,7 +3006,7 @@
<value>武器一覧</value>
</data>
<data name="WebAnnouncementMatchPermanentActivityTime" xml:space="preserve">
<value>(?:(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)|&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;)后永久开放</value>
<value>(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)后永久开放</value>
</data>
<data name="WebAnnouncementMatchPersistentActivityTime" xml:space="preserve">
<value>〓活动时间〓.*?(\d\.\d)版本期间持续开放</value>
@@ -3074,9 +3044,6 @@
<data name="WebBridgeShareCopyToClipboardSuccess" xml:space="preserve">
<value>クリップボードにコピーしました。</value>
</data>
<data name="WebDailyNoteArchonQuestChapterFinished" xml:space="preserve">
<value>所有魔神任务已完成</value>
</data>
<data name="WebDailyNoteArchonQuestStatusFinished" xml:space="preserve">
<value>すべて完了</value>
</data>
@@ -3204,7 +3171,7 @@
<value>イベント祈願・キャラクター2</value>
</data>
<data name="WebGachaConfigTypeChronicledWish" xml:space="preserve">
<value>集録祈願</value>
<value>集录祈愿</value>
</data>
<data name="WebGachaConfigTypeNoviceWish" xml:space="preserve">
<value>初心者祈願</value>
@@ -3257,9 +3224,6 @@
<data name="WebResponseRequestExceptionFormat" xml:space="preserve">
<value>[{0}] の[{1}] のリクエストにエラーが発生、時間をおいてから試してください</value>
</data>
<data name="WebResponseSignInErrorHint" xml:space="preserve">
<value>登录失败,请前往 HoYoLAB 初始化账号,原始消息:{0}</value>
</data>
<data name="WindowIdentifyMonitorHeader" xml:space="preserve">
<value>モニターID</value>
</data>

View File

@@ -192,18 +192,6 @@
<data name="CoreWindowHotkeyCombinationRegisterFailed" xml:space="preserve">
<value>[{0}] 热键 [{1}] 注册失败</value>
</data>
<data name="CoreWindowingNotifyIconExitLabel" xml:space="preserve">
<value>退出</value>
</data>
<data name="CoreWindowingNotifyIconLaunchGameLabel" xml:space="preserve">
<value>게임 시작</value>
</data>
<data name="CoreWindowingNotifyIconPromotedHint" xml:space="preserve">
<value>胡桃已进入后台运行</value>
</data>
<data name="CoreWindowingNotifyIconViewLabel" xml:space="preserve">
<value>窗口</value>
</data>
<data name="CoreWindowThemeDark" xml:space="preserve">
<value>深色</value>
</data>
@@ -1568,12 +1556,6 @@
<data name="ViewModelCultivationProjectInvalidName" xml:space="preserve">
<value>잘못된 이름을 가진 일정은 추가할 수 없습니다</value>
</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">
<value>实时便笺 Webhook Url 配置成功</value>
</data>
@@ -1964,9 +1946,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>
@@ -1997,9 +1976,6 @@
<data name="ViewPageDailyNoteSettingRefreshHeader" xml:space="preserve">
<value>동기화</value>
</data>
<data name="ViewPageDailyNoteSettingRefreshNotifyIconDisabledHint" xml:space="preserve">
<value>未启用通知区域图标,关闭窗口后自动刷新将不会执行</value>
</data>
<data name="ViewPageDailyNoteSlientModeDescription" xml:space="preserve">
<value>원신을 플레이 할 때 알리지 않음</value>
</data>
@@ -2678,12 +2654,6 @@
<data name="ViewPageSettingKeyShortcutHeader" xml:space="preserve">
<value>快捷键</value>
</data>
<data name="ViewPageSettingNotifyIconDescription" xml:space="preserve">
<value>在通知区域显示图标,以允许执行后台任务,重启后生效</value>
</data>
<data name="ViewPageSettingNotifyIconHeader" xml:space="preserve">
<value>通知区域图标</value>
</data>
<data name="ViewPageSettingOfficialSiteNavigate" xml:space="preserve">
<value>공식 홈페이지로 이동</value>
</data>
@@ -3036,7 +3006,7 @@
<value>무기 자료</value>
</data>
<data name="WebAnnouncementMatchPermanentActivityTime" xml:space="preserve">
<value>(?:(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)|&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;)后永久开放</value>
<value>(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)后永久开放</value>
</data>
<data name="WebAnnouncementMatchPersistentActivityTime" xml:space="preserve">
<value>〓活动时间〓.*?(\d\.\d)版本期间持续开放</value>
@@ -3074,9 +3044,6 @@
<data name="WebBridgeShareCopyToClipboardSuccess" xml:space="preserve">
<value>已复制到剪贴板</value>
</data>
<data name="WebDailyNoteArchonQuestChapterFinished" xml:space="preserve">
<value>所有魔神任务已完成</value>
</data>
<data name="WebDailyNoteArchonQuestStatusFinished" xml:space="preserve">
<value>全部完成</value>
</data>
@@ -3257,9 +3224,6 @@
<data name="WebResponseRequestExceptionFormat" xml:space="preserve">
<value>[{0}] 中的 [{1}] 网络请求异常,请稍后再试</value>
</data>
<data name="WebResponseSignInErrorHint" xml:space="preserve">
<value>登录失败,请前往 HoYoLAB 初始化账号,原始消息:{0}</value>
</data>
<data name="WindowIdentifyMonitorHeader" xml:space="preserve">
<value>显示器编号</value>
</data>

View File

@@ -192,18 +192,6 @@
<data name="CoreWindowHotkeyCombinationRegisterFailed" xml:space="preserve">
<value>Falha ao definir atalho [{0}] para [{1}].</value>
</data>
<data name="CoreWindowingNotifyIconExitLabel" xml:space="preserve">
<value>退出</value>
</data>
<data name="CoreWindowingNotifyIconLaunchGameLabel" xml:space="preserve">
<value>Iniciar</value>
</data>
<data name="CoreWindowingNotifyIconPromotedHint" xml:space="preserve">
<value>胡桃已进入后台运行</value>
</data>
<data name="CoreWindowingNotifyIconViewLabel" xml:space="preserve">
<value>窗口</value>
</data>
<data name="CoreWindowThemeDark" xml:space="preserve">
<value>Tema Escuro</value>
</data>
@@ -1568,12 +1556,6 @@
<data name="ViewModelCultivationProjectInvalidName" xml:space="preserve">
<value>Não é possível adicionar um plano com nome inválido</value>
</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">
<value>URL do webhook de lembrete de tempo real configurado com sucesso</value>
</data>
@@ -1964,9 +1946,6 @@
<data name="ViewPageDailyNoteNotificationSetting" xml:space="preserve">
<value>Configurações de notificação</value>
</data>
<data name="ViewPageDailyNoteNotificationUnavailableHint" xml:space="preserve">
<value>胡桃的通知权限已被关闭</value>
</data>
<data name="ViewPageDailyNoteRefresh" xml:space="preserve">
<value>Atualizar</value>
</data>
@@ -1997,9 +1976,6 @@
<data name="ViewPageDailyNoteSettingRefreshHeader" xml:space="preserve">
<value>Atualizar</value>
</data>
<data name="ViewPageDailyNoteSettingRefreshNotifyIconDisabledHint" xml:space="preserve">
<value>未启用通知区域图标,关闭窗口后自动刷新将不会执行</value>
</data>
<data name="ViewPageDailyNoteSlientModeDescription" xml:space="preserve">
<value>Não incomodar durante o Genshin</value>
</data>
@@ -2678,12 +2654,6 @@
<data name="ViewPageSettingKeyShortcutHeader" xml:space="preserve">
<value>Teclas de atalho</value>
</data>
<data name="ViewPageSettingNotifyIconDescription" xml:space="preserve">
<value>在通知区域显示图标,以允许执行后台任务,重启后生效</value>
</data>
<data name="ViewPageSettingNotifyIconHeader" xml:space="preserve">
<value>通知区域图标</value>
</data>
<data name="ViewPageSettingOfficialSiteNavigate" xml:space="preserve">
<value>Site oficial</value>
</data>
@@ -3036,7 +3006,7 @@
<value>Wiki de armas</value>
</data>
<data name="WebAnnouncementMatchPermanentActivityTime" xml:space="preserve">
<value>(?:(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)|&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;)后永久开放</value>
<value>(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)后永久开放</value>
</data>
<data name="WebAnnouncementMatchPersistentActivityTime" xml:space="preserve">
<value>〓活动时间〓.*?(\d\.\d)版本期间持续开放</value>
@@ -3074,9 +3044,6 @@
<data name="WebBridgeShareCopyToClipboardSuccess" xml:space="preserve">
<value>Copiado para a área de transferência</value>
</data>
<data name="WebDailyNoteArchonQuestChapterFinished" xml:space="preserve">
<value>Todas as missões de arconte concluídas</value>
</data>
<data name="WebDailyNoteArchonQuestStatusFinished" xml:space="preserve">
<value>Concluído</value>
</data>
@@ -3257,9 +3224,6 @@
<data name="WebResponseRequestExceptionFormat" xml:space="preserve">
<value>[{1}] erro de solicitação de rede em [{0}], tente novamente mais tarde</value>
</data>
<data name="WebResponseSignInErrorHint" xml:space="preserve">
<value>登录失败,请前往 HoYoLAB 初始化账号,原始消息:{0}</value>
</data>
<data name="WindowIdentifyMonitorHeader" xml:space="preserve">
<value>ID do monitor</value>
</data>

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>
@@ -2996,9 +2993,6 @@
<data name="ViewUserDocumentationHeader" xml:space="preserve">
<value>文档</value>
</data>
<data name="ViewUserLoginMihoyoUserDisabledTooltip" xml:space="preserve">
<value>由于米游社安全策略的相关更改,网页登录暂不可用</value>
</data>
<data name="ViewUserNoUserHint" xml:space="preserve">
<value>尚未登录</value>
</data>

View File

@@ -192,18 +192,6 @@
<data name="CoreWindowHotkeyCombinationRegisterFailed" xml:space="preserve">
<value>Регистрация [{0}] горячей клавиши [{1}] не удалась</value>
</data>
<data name="CoreWindowingNotifyIconExitLabel" xml:space="preserve">
<value>退出</value>
</data>
<data name="CoreWindowingNotifyIconLaunchGameLabel" xml:space="preserve">
<value>Game Launcher</value>
</data>
<data name="CoreWindowingNotifyIconPromotedHint" xml:space="preserve">
<value>胡桃已进入后台运行</value>
</data>
<data name="CoreWindowingNotifyIconViewLabel" xml:space="preserve">
<value>窗口</value>
</data>
<data name="CoreWindowThemeDark" xml:space="preserve">
<value>Тёмная</value>
</data>
@@ -1185,40 +1173,40 @@
<value>Режим импорта</value>
</data>
<data name="ViewDialogAchievementArchiveImportStrategyAggressive" xml:space="preserve">
<value>Жадно (добавляют новые данные, обновляют завершенные записи)</value>
<value>贪婪(添加新数据,更新已完成项)</value>
</data>
<data name="ViewDialogAchievementArchiveImportStrategyLazy" xml:space="preserve">
<value>Лениво (добавление новых данных, пропуск завершенных записей)</value>
<value>懒惰(添加新数据,跳过已完成项)</value>
</data>
<data name="ViewDialogAchievementArchiveImportStrategyOverwrite" xml:space="preserve">
<value>Перезапись (удаление старых данных, добавление новых)</value>
<value>覆盖(删除老数据,添加新的数据)</value>
</data>
<data name="ViewDialogAchievementArchiveImportTitle" xml:space="preserve">
<value>Импорт данных о достижениях в текущий архив</value>
</data>
<data name="ViewDialogCultivateBatchAvatarLevelTarget" xml:space="preserve">
<value>Целевой уровень персонажа</value>
<value>角色目标等级</value>
</data>
<data name="ViewDialogCultivateBatchSkillATarget" xml:space="preserve">
<value>Уровень цели обычной атаки</value>
<value>普通攻击目标等级</value>
</data>
<data name="ViewDialogCultivateBatchSkillETarget" xml:space="preserve">
<value>Целевой уровень Элементального навыка</value>
<value>元素战技目标等级</value>
</data>
<data name="ViewDialogCultivateBatchSkillQTarget" xml:space="preserve">
<value>Целевой уровень Взрыва стихий</value>
<value>元素爆发目标等级</value>
</data>
<data name="ViewDialogCultivateBatchWeaponLevelTarget" xml:space="preserve">
<value>Целевой уровень оружия</value>
<value>武器目标等级</value>
</data>
<data name="ViewDialogCultivateProjectAttachUid" xml:space="preserve">
<value>Связать текущего пользователя и роль</value>
<value>绑定当前用户与角色</value>
</data>
<data name="ViewDialogCultivateProjectInputPlaceholder" xml:space="preserve">
<value>Введите название плана</value>
<value>在此处输入计划名称</value>
</data>
<data name="ViewDialogCultivateProjectTitle" xml:space="preserve">
<value>Создание нового плана</value>
<value>创建新的养成计划</value>
</data>
<data name="ViewDialogCultivatePromotionDeltaBatchTitle" xml:space="preserve">
<value>批量添加或更新到当前养成计划</value>
@@ -1230,7 +1218,7 @@
<value>每日委托上线提醒</value>
</data>
<data name="ViewDialogDailyNoteNotificationExpeditionNotify" xml:space="preserve">
<value>Уведомление об окончании экспедиции</value>
<value>探索派遣完成提醒</value>
</data>
<data name="ViewDialogDailyNoteNotificationHomeCoinNotifyThreshold" xml:space="preserve">
<value>洞天宝钱提醒阈值</value>
@@ -1248,7 +1236,7 @@
<value>参量质变仪提醒</value>
</data>
<data name="ViewDialogDailyNoteWebhookUrlInputPlaceholder" xml:space="preserve">
<value>Пожалуйста, введите URL</value>
<value>请输入 Url</value>
</data>
<data name="ViewDialogDailyNoteWebhookUrlTitle" xml:space="preserve">
<value>实时便笺 Webhook Url</value>
@@ -1272,7 +1260,7 @@
<value>获取祈愿物品中</value>
</data>
<data name="ViewDialogGachaLogUrlInputPlaceholder" xml:space="preserve">
<value>Пожалуйста, введите URL</value>
<value>请输入 Url</value>
</data>
<data name="ViewDialogGachaLogUrlTitle" xml:space="preserve">
<value>手动输入祈愿记录 Url</value>
@@ -1299,7 +1287,7 @@
<value>将会通过 GET 方式对接口发送请求</value>
</data>
<data name="ViewDialogGeetestCustomUrlSampleHeader" xml:space="preserve">
<value>Пример</value>
<value>示例</value>
</data>
<data name="ViewDialogGeetestCustomUrlTitle" xml:space="preserve">
<value>配置无感验证接口</value>
@@ -1341,13 +1329,13 @@
<value>UIGF 版本</value>
</data>
<data name="ViewDialogLaunchGameAccountInputPlaceholder" xml:space="preserve">
<value>Введите имя</value>
<value>在此处输入名称</value>
</data>
<data name="ViewDialogLaunchGameAccountTitle" xml:space="preserve">
<value>Назовите ваш аккаунт</value>
<value>为账号命名</value>
</data>
<data name="ViewDialogLaunchGameConfigurationFixDialogHint" xml:space="preserve">
<value>Пожалуйста, выберите ваш игровой сервер</value>
<value>请选择当前游戏路径对应的游戏服务器</value>
</data>
<data name="ViewDialogLaunchGameConfigurationFixDialogTitle" xml:space="preserve">
<value>Восстановление файла конфигурации</value>
@@ -1359,7 +1347,7 @@
<value>正在转换客户端</value>
</data>
<data name="ViewDialogQRCodeTitle" xml:space="preserve">
<value>Отсканируйте QR-код с помощью Miyusha</value>
<value>使用米游社扫描二维码</value>
</data>
<data name="ViewDialogReconfirmTextHeader" xml:space="preserve">
<value>为防止你在无意间启用,请输入正在启用的功能开关的&lt;b&gt;标题名称&lt;/b&gt;</value>
@@ -1368,7 +1356,7 @@
<value>你正在启用一个危险功能</value>
</data>
<data name="ViewDialogSettingDeleteUserDataContent" xml:space="preserve">
<value>Эта операция необратима, и все входы пользователей в систему будут удалены</value>
<value>该操作是不可逆的,所有用户登录状态会丢失</value>
</data>
<data name="ViewDialogSettingDeleteUserDataTitle" xml:space="preserve">
<value>是否永久删除用户数据</value>
@@ -1380,7 +1368,7 @@
<value>当前未登录胡桃账号,上传深渊数据无法获赠胡桃云时长</value>
</data>
<data name="ViewDialogSpiralAbyssUploadRecordHomaNotLoginPrimaryButtonText" xml:space="preserve">
<value>Продолжить загрузку</value>
<value>继续上传</value>
</data>
<data name="ViewDialogSpiralAbyssUploadRecordHomaNotLoginTitle" xml:space="preserve">
<value>上传深渊数据</value>
@@ -1401,37 +1389,37 @@
<value>在此处输入包含 SToken 的 Cookie</value>
</data>
<data name="ViewDialogUserTitle" xml:space="preserve">
<value>Установка cookie-файлов</value>
<value>设置 Cookie</value>
</data>
<data name="ViewFeedbackHeader" xml:space="preserve">
<value>Центр обратной связи</value>
<value>反馈中心</value>
</data>
<data name="ViewGachaLogHeader" xml:space="preserve">
<value>История молитв</value>
<value>祈愿记录</value>
</data>
<data name="ViewGuideStaticResourceDownloadSize" xml:space="preserve">
<value>Примерный размер загрузки: {0}</value>
<value>预计下载大小:{0}</value>
</data>
<data name="ViewGuideStepAgreementIHaveReadText" xml:space="preserve">
<value>Я прочитал и согласен с</value>
<value>我已阅读并同意</value>
</data>
<data name="ViewGuideStepAgreementIssueReport" xml:space="preserve">
<value>问题报告方式与流程</value>
</data>
<data name="ViewGuideStepAgreementOpenSourceLicense" xml:space="preserve">
<value>Лицензия с открытым исходным кодом Snap Hutao</value>
<value>Snap Hutao 开源许可</value>
</data>
<data name="ViewGuideStepAgreementPrivacyPolicy" xml:space="preserve">
<value>Данные пользователя и права на конфиденциальность</value>
<value>用户数据与隐私权益</value>
</data>
<data name="ViewGuideStepAgreementTermOfService" xml:space="preserve">
<value>Пользовательское соглашение</value>
<value>用户使用协议与法律声明</value>
</data>
<data name="ViewGuideStepCommonSetting" xml:space="preserve">
<value>Основные настройки</value>
<value>基础设置</value>
</data>
<data name="ViewGuideStepCommonSettingHint" xml:space="preserve">
<value>Это можно изменить позже в настройках</value>
<value>稍后可以在设置中修改</value>
</data>
<data name="ViewGuideStepDocument" xml:space="preserve">
<value>Документация</value>
@@ -1568,12 +1556,6 @@
<data name="ViewModelCultivationProjectInvalidName" xml:space="preserve">
<value>不能添加名称无效的计划</value>
</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">
<value>实时便笺 Webhook Url 配置成功</value>
</data>
@@ -1964,9 +1946,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>
@@ -1997,9 +1976,6 @@
<data name="ViewPageDailyNoteSettingRefreshHeader" xml:space="preserve">
<value>Обновить</value>
</data>
<data name="ViewPageDailyNoteSettingRefreshNotifyIconDisabledHint" xml:space="preserve">
<value>未启用通知区域图标,关闭窗口后自动刷新将不会执行</value>
</data>
<data name="ViewPageDailyNoteSlientModeDescription" xml:space="preserve">
<value>在我游玩原神时不通知我</value>
</data>
@@ -2568,7 +2544,7 @@
<value>前往反馈</value>
</data>
<data name="ViewPageSettingGachaLogHeader" xml:space="preserve">
<value>История молитв</value>
<value>祈愿记录</value>
</data>
<data name="ViewPageSettingGameHeader" xml:space="preserve">
<value>游戏</value>
@@ -2604,7 +2580,7 @@
<value>Заметки в реальном времени</value>
</data>
<data name="ViewpageSettingHomeCardItemgachaStatisticsHeader" xml:space="preserve">
<value>История молитв</value>
<value>祈愿记录</value>
</data>
<data name="ViewpageSettingHomeCardItemLaunchGameHeader" xml:space="preserve">
<value>Game Launcher</value>
@@ -2678,12 +2654,6 @@
<data name="ViewPageSettingKeyShortcutHeader" xml:space="preserve">
<value>快捷键</value>
</data>
<data name="ViewPageSettingNotifyIconDescription" xml:space="preserve">
<value>在通知区域显示图标,以允许执行后台任务,重启后生效</value>
</data>
<data name="ViewPageSettingNotifyIconHeader" xml:space="preserve">
<value>通知区域图标</value>
</data>
<data name="ViewPageSettingOfficialSiteNavigate" xml:space="preserve">
<value>前往官网</value>
</data>
@@ -3036,7 +3006,7 @@
<value>武器资料</value>
</data>
<data name="WebAnnouncementMatchPermanentActivityTime" xml:space="preserve">
<value>(?:(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)|&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;)后永久开放</value>
<value>(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)后永久开放</value>
</data>
<data name="WebAnnouncementMatchPersistentActivityTime" xml:space="preserve">
<value>〓活动时间〓.*?(\d\.\d)版本期间持续开放</value>
@@ -3074,9 +3044,6 @@
<data name="WebBridgeShareCopyToClipboardSuccess" xml:space="preserve">
<value>Скопировано в буфер обмена</value>
</data>
<data name="WebDailyNoteArchonQuestChapterFinished" xml:space="preserve">
<value>所有魔神任务已完成</value>
</data>
<data name="WebDailyNoteArchonQuestStatusFinished" xml:space="preserve">
<value>Завершенно</value>
</data>
@@ -3257,9 +3224,6 @@
<data name="WebResponseRequestExceptionFormat" xml:space="preserve">
<value>[{1}] исключение сетевого запроса в [{0}] пожалуйста, повторите попытку позже</value>
</data>
<data name="WebResponseSignInErrorHint" xml:space="preserve">
<value>登录失败,请前往 HoYoLAB 初始化账号,原始消息:{0}</value>
</data>
<data name="WindowIdentifyMonitorHeader" xml:space="preserve">
<value>显示器编号</value>
</data>

File diff suppressed because it is too large Load Diff

View File

@@ -163,7 +163,7 @@
<value>清單</value>
</data>
<data name="CoreExceptionServiceDatabaseCorruptedMessage" xml:space="preserve">
<value>數據庫已損壞:{0}</value>
<value>資料庫已損壞:{0}</value>
</data>
<data name="CoreExceptionServiceUserdataCorruptedMessage" xml:space="preserve">
<value>用户數據已損壞:{0}</value>
@@ -172,10 +172,10 @@
<value>請勿在系統管理員模式下使用此功能 {0}</value>
</data>
<data name="CoreIOPickerExtensionPickerExceptionInfoBarTitle" xml:space="preserve">
<value>無法打開檔案選擇器</value>
<value>無法打開文件選擇器</value>
</data>
<data name="CoreIOTempFileCreateFail" xml:space="preserve">
<value>權限不足,創建臨時檔案失敗</value>
<value>權限不足,創建臨時文件失敗</value>
</data>
<data name="CoreJumpListHelperLaunchGameItemDisplayName" xml:space="preserve">
<value>啟動遊戲</value>
@@ -192,18 +192,6 @@
<data name="CoreWindowHotkeyCombinationRegisterFailed" xml:space="preserve">
<value>[{0}] 鍵盤快速鍵 [{1}] 註冊失敗</value>
</data>
<data name="CoreWindowingNotifyIconExitLabel" xml:space="preserve">
<value>退出</value>
</data>
<data name="CoreWindowingNotifyIconLaunchGameLabel" xml:space="preserve">
<value>啟動遊戲</value>
</data>
<data name="CoreWindowingNotifyIconPromotedHint" xml:space="preserve">
<value>胡桃已進入後臺運行</value>
</data>
<data name="CoreWindowingNotifyIconViewLabel" xml:space="preserve">
<value>窗口</value>
</data>
<data name="CoreWindowThemeDark" xml:space="preserve">
<value>深色</value>
</data>
@@ -283,7 +271,7 @@
<value>國際伺服器</value>
</data>
<data name="ModelBindingUserInitializationFailed" xml:space="preserve">
<value>網絡異常</value>
<value>網路連線錯誤</value>
</data>
<data name="ModelEntityDailyNoteNotRefreshed" xml:space="preserve">
<value>尚未重新整理</value>
@@ -352,7 +340,7 @@
<value>蘿莉</value>
</data>
<data name="ModelIntrinsicBodyTypeMale" xml:space="preserve">
<value>成</value>
<value>成年男子</value>
</data>
<data name="ModelIntrinsicElementNameElec" xml:space="preserve">
<value>雷</value>
@@ -421,7 +409,7 @@
<comment>Need EXACT same string in game</comment>
</data>
<data name="ModelMetadataAvatarPlayerName" xml:space="preserve">
<value>旅行者</value>
<value>旅</value>
</data>
<data name="ModelMetadataFetterInfoBirthdayFormat" xml:space="preserve">
<value>{0} 月 {1} 日</value>
@@ -552,7 +540,7 @@
<value>精煉 {0} 階</value>
</data>
<data name="MustSelectUserAndUid" xml:space="preserve">
<value>必登入 米社/ HoYoLAB 並選一個用戶與角色</value>
<value>必登入 米社/HoYoLAB 並選一個用戶與角色</value>
</data>
<data name="ServerGachaLogServiceDeleteEntrySucceed" xml:space="preserve">
<value>刪除了 UID{0} 的 {1} 筆祈願記錄</value>
@@ -585,25 +573,25 @@
<value>新密碼設定成功</value>
</data>
<data name="ServerPassportServiceEmailHasNotRegistered" xml:space="preserve">
<value>當前電子郵件地址尚未註冊</value>
<value>當前郵箱尚未註冊</value>
</data>
<data name="ServerPassportServiceEmailHasRegistered" xml:space="preserve">
<value>當前電子郵件地址已被註冊</value>
<value>當前郵箱已被註冊</value>
</data>
<data name="ServerPassportServiceInternalException" xml:space="preserve">
<value>註冊失敗,伺服器異常,請盡快聯繫開發者解決</value>
</data>
<data name="ServerPassportServiceUnregisterFailed" xml:space="preserve">
<value>用戶不存在,刪除帳號失敗</value>
<value>使用者不存在,刪除帳號失敗</value>
</data>
<data name="ServerPassportUnregisterSucceed" xml:space="preserve">
<value>用戶刪除成功</value>
<value>使用者刪除成功</value>
</data>
<data name="ServerPassportUserInfoNotExist" xml:space="preserve">
<value>用戶不存在,獲取用戶信息失敗</value>
<value>使用者不存在,獲取使用者信息失敗</value>
</data>
<data name="ServerPassportUserNameOrPasswordIncorrect" xml:space="preserve">
<value>用戶名稱或密碼錯誤</value>
<value>使用者名稱或密碼錯誤</value>
</data>
<data name="ServerPassportVerifyFailed" xml:space="preserve">
<value>驗證失敗</value>
@@ -612,10 +600,10 @@
<value>驗證請求失敗,不是當前登入的帳號</value>
</data>
<data name="ServerPassportVerifyRequestSuccess" xml:space="preserve">
<value>驗證碼已發送至箱</value>
<value>驗證碼已發送至箱</value>
</data>
<data name="ServerPassportVerifyRequestUserAlreadyExisted" xml:space="preserve">
<value>驗證請求失敗,當前電子郵件地址已被註冊</value>
<value>驗證請求失敗,當前郵箱已被註冊</value>
</data>
<data name="ServerPassportVerifyTooFrequent" xml:space="preserve">
<value>驗證請求過快,請 1 分鐘後再試</value>
@@ -651,7 +639,7 @@
<value>上傳深淵記錄成功,但未登入胡桃通行證,無法獲贈祈願記錄上傳服務時長</value>
</data>
<data name="ServerRecordUploadSuccessButNoSuchUser" xml:space="preserve">
<value>上傳深淵記錄成功,但無法找到用戶,無法獲贈祈願記錄上傳服務時長</value>
<value>上傳深淵記錄成功,但無法找到使用者,無法獲贈祈願記錄上傳服務時長</value>
</data>
<data name="ServerRecordUploadSuccessButNotFirstTimeAtCurrentSchedule" xml:space="preserve">
<value>上傳深淵記錄成功,但不是本期首次提交,無法獲贈祈願記錄上傳服務時長</value>
@@ -663,7 +651,7 @@
<value>UIAF Json 檔案</value>
</data>
<data name="ServiceAchievementUIAFImportPickerTitile" xml:space="preserve">
<value>打開 UIAF Json 檔案</value>
<value>打開 UIAF Json 文件</value>
</data>
<data name="ServiceAchievementUserdataCorruptedAchievementIdNotUnique" xml:space="preserve">
<value>單個成就存檔內發現多個相同的成就 Id</value>
@@ -783,10 +771,10 @@
<value>養成計算:{0:MM-dd HH:mm}</value>
</data>
<data name="ServiceAvatarInfoSummaryGameRecordNotRefreshed" xml:space="preserve">
<value>戰績:尚未重新整理</value>
<value>原神戰績:尚未重新整理</value>
</data>
<data name="ServiceAvatarInfoSummaryGameRecordRefreshTimeFormat" xml:space="preserve">
<value>戰績:{0:MM-dd HH:mm}</value>
<value>原神戰績:{0:MM-dd HH:mm}</value>
</data>
<data name="ServiceAvatarInfoSummaryShowcaseNotRefreshed" xml:space="preserve">
<value>角色櫥窗:尚未重新整理</value>
@@ -855,7 +843,7 @@
<value>目前原粹樹脂:{0}</value>
</data>
<data name="ServiceDailyNoteNotifierTitle" xml:space="preserve">
<value>時便箋提醒</value>
<value>時便箋提醒</value>
</data>
<data name="ServiceDailyNoteNotifierTransformer" xml:space="preserve">
<value>參數質變儀</value>
@@ -906,7 +894,7 @@
<value>請求驗證密鑰失敗</value>
</data>
<data name="ServiceGachaLogUrlProviderCachePathInvalid" xml:space="preserve">
<value>未正確提供原神路徑,或目前設的路徑不正確</value>
<value>未正確提供原神路徑,或目前設的路徑不正確</value>
</data>
<data name="ServiceGachaLogUrlProviderCachePathNotFound" xml:space="preserve">
<value>找不到原神內置瀏覽器緩存路徑:\n{0}</value>
@@ -927,13 +915,13 @@
<value>不支持的 Item Id{0}</value>
</data>
<data name="ServiceGachaUIGFImportLanguageNotMatch" xml:space="preserve">
<value>UIGF 檔案的語言:{0} 與胡桃的語言:{1} 不對應,請切換到對應語言重試</value>
<value>UIGF 文件的語言:{0} 與胡桃的語言:{1} 不對應,請切換到對應語言重試</value>
</data>
<data name="ServiceGameDetectGameAccountMultiMatched" xml:space="preserve">
<value>存在多個匹配賬號,請刪除重複的賬號</value>
</data>
<data name="ServiceGameEnsureGameResourceInsufficientDirectoryPermissions" xml:space="preserve">
<value>檔案系統權限不足,無法轉換伺服器</value>
<value>文件系統權限不足,無法轉換伺服器</value>
</data>
<data name="ServiceGameEnsureGameResourceQueryResourceInformation" xml:space="preserve">
<value>下載遊戲資源索引</value>
@@ -981,10 +969,10 @@
<value>遊戲本體</value>
</data>
<data name="ServiceGameLocatorUnityLogFileNotFound" xml:space="preserve">
<value>找不到 Unity 日誌檔案</value>
<value>找不到 Unity 日誌文件</value>
</data>
<data name="ServiceGameLocatorUnityLogGamePathNotFound" xml:space="preserve">
<value>在 Unity 日誌檔案中無法找到遊戲路徑</value>
<value>在 Unity 日誌文件中無法找到遊戲路徑</value>
</data>
<data name="ServiceGamePackageConvertMoveFileBackupFormat" xml:space="preserve">
<value>備份:{0}</value>
@@ -996,7 +984,7 @@
<value>替換:{0}</value>
</data>
<data name="ServiceGamePackageRenameDataFolderFailed" xml:space="preserve">
<value>重新命名資料檔案夾名稱失敗</value>
<value>重新命名資料文件夾名稱失敗</value>
</data>
<data name="ServiceGamePackageRequestPackageVerion" xml:space="preserve">
<value>正在獲取 Package Version</value>
@@ -1005,7 +993,7 @@
<value>獲取 Package Version 失敗</value>
</data>
<data name="ServiceGamePackageRequestScatteredFileFailed" xml:space="preserve">
<value>下載客戶端檔案失敗:{0}</value>
<value>下載客戶端文件失敗:{0}</value>
</data>
<data name="ServiceGamePathLocateFailed" xml:space="preserve">
<value>無法找到遊戲本體路徑,請前往設定修改</value>
@@ -1017,7 +1005,7 @@
<value>無法讀取遊戲設定檔 {0},可能是檔案不存在</value>
</data>
<data name="ServiceGameSetMultiChannelUnauthorizedAccess" xml:space="preserve">
<value>無法讀取或儲存配置檔案,請用系統管理員模式重試</value>
<value>無法讀取或儲存配置文件,請用系統管理員模式重試</value>
</data>
<data name="ServiceGameUnlockerFindModuleNoModuleFound" xml:space="preserve">
<value>在尋找必要的模組時遇到問題:無法讀取任何模組,可能是保護驅動已經載入完成,請重試</value>
@@ -1038,19 +1026,19 @@
<value>祈願紀錄上傳服務有效期至\n{0:yyyy.MM.dd HH:mm:ss}</value>
</data>
<data name="ServiceMetadataFileNotFound" xml:space="preserve">
<value>無法找到暫存的元數據檔案</value>
<value>無法找到暫存的元數據文件</value>
</data>
<data name="ServiceMetadataHttpRequestFailed" xml:space="preserve">
<value>HTTP {0} | Error:{1}:元資料校驗檔案下載失敗</value>
<value>HTTP {0} | Error:{1}:元資料校驗文件下載失敗</value>
</data>
<data name="ServiceMetadataNotInitialized" xml:space="preserve">
<value>元數據服務未初始化或初始化失敗</value>
</data>
<data name="ServiceMetadataParseFailed" xml:space="preserve">
<value>元數據校驗檔案解析失敗</value>
<value>元數據文件解析失敗</value>
</data>
<data name="ServiceMetadataRequestFailed" xml:space="preserve">
<value>元數據校驗檔案下載失敗</value>
<value>元數據文件下載失敗</value>
</data>
<data name="ServiceMetadataVersionNotSupported" xml:space="preserve">
<value>你的胡桃版本過低,請盡快升級</value>
@@ -1065,7 +1053,7 @@
<value>獲取獎勵清單失敗</value>
</data>
<data name="ServiceSignInRiskVerificationFailed" xml:space="preserve">
<value>驗證失敗,請前往 HoYoLAB 原神簽到頁面自行領取獎勵</value>
<value>驗證失敗請前往HoYoLAB原神簽到頁面自行領取獎勵</value>
</data>
<data name="ServiceSignInSuccessRewardFormat" xml:space="preserve">
<value>簽到成功,{0}×{1}</value>
@@ -1077,7 +1065,7 @@
<value>發現新版本 {0}</value>
</data>
<data name="ServiceUserCurrentMultiMatched" xml:space="preserve">
<value>多個用戶記錄為選中狀態</value>
<value>已选中多条用户记录</value>
</data>
<data name="ServiceUserCurrentUpdateAndSaveFailed" xml:space="preserve">
<value>用戶 {0} 狀態儲存失敗</value>
@@ -1179,7 +1167,7 @@
<value>在此處輸入</value>
</data>
<data name="ViewDialogAchievementArchiveCreateTitle" xml:space="preserve">
<value>設成就存檔的名稱</value>
<value>設成就存檔的名稱</value>
</data>
<data name="ViewDialogAchievementArchiveImportStrategy" xml:space="preserve">
<value>匯入模式</value>
@@ -1242,7 +1230,7 @@
<value>在主頁顯示卡片</value>
</data>
<data name="ViewDialogDailyNoteNotificationTitle" xml:space="preserve">
<value>時便箋通知設</value>
<value>時便箋通知設</value>
</data>
<data name="ViewDialogDailyNoteNotificationTransformerNotify" xml:space="preserve">
<value>參數質變儀提醒</value>
@@ -1347,10 +1335,10 @@
<value>為帳號命名</value>
</data>
<data name="ViewDialogLaunchGameConfigurationFixDialogHint" xml:space="preserve">
<value>請選擇當前遊戲路徑對應的遊戲服器</value>
<value>請選擇當前遊戲路徑對應的遊戲服器</value>
</data>
<data name="ViewDialogLaunchGameConfigurationFixDialogTitle" xml:space="preserve">
<value>正在修複配置檔案</value>
<value>正在修複配置文件</value>
</data>
<data name="ViewDialogLaunchGamePackageConvertHint" xml:space="preserve">
<value>轉換可能需要花費一段時間,請勿關閉胡桃</value>
@@ -1359,7 +1347,7 @@
<value>正在轉換客戶端</value>
</data>
<data name="ViewDialogQRCodeTitle" xml:space="preserve">
<value>使用米社掃描 QR 碼</value>
<value>使用米社掃描 QR 碼</value>
</data>
<data name="ViewDialogReconfirmTextHeader" xml:space="preserve">
<value>為防止你在無意間啟用,請輸入正在啟用的功能開關的&lt;b&gt;標題名稱&lt;/b&gt;</value>
@@ -1374,19 +1362,19 @@
<value>是否永久刪除用戶數據</value>
</data>
<data name="ViewDialogSpiralAbyssUploadRecordHomaNotLoginCloseButtonText" xml:space="preserve">
<value>前往登入畫面</value>
<value>前往登</value>
</data>
<data name="ViewDialogSpiralAbyssUploadRecordHomaNotLoginHint" xml:space="preserve">
<value>前未登胡桃賬號,上傳深淵數據無法獲贈胡桃雲時長</value>
<value>前未登胡桃账号,上传深渊数据无法获赠胡桃云时长</value>
</data>
<data name="ViewDialogSpiralAbyssUploadRecordHomaNotLoginPrimaryButtonText" xml:space="preserve">
<value>繼續上傳</value>
<value>继续上传</value>
</data>
<data name="ViewDialogSpiralAbyssUploadRecordHomaNotLoginTitle" xml:space="preserve">
<value>Загрузите данные о Бездне</value>
<value>上传深渊数据</value>
</data>
<data name="ViewDialogUpdatePackageDownloadUpdatelogLinkContent" xml:space="preserve">
<value>查看更新日</value>
<value>查看更新日</value>
</data>
<data name="ViewDialogUserDocumentAction" xml:space="preserve">
<value>立即前往</value>
@@ -1428,10 +1416,10 @@
<value>用戶使用協議與法律聲明</value>
</data>
<data name="ViewGuideStepCommonSetting" xml:space="preserve">
<value>基礎設</value>
<value>基礎設</value>
</data>
<data name="ViewGuideStepCommonSettingHint" xml:space="preserve">
<value>稍後可以在設中修改</value>
<value>稍後可以在設中修改</value>
</data>
<data name="ViewGuideStepDocument" xml:space="preserve">
<value>文檔</value>
@@ -1461,10 +1449,10 @@
<value>資源</value>
</data>
<data name="ViewGuideStepStaticResourceSetting" xml:space="preserve">
<value>圖像資源設</value>
<value>圖像資源設</value>
</data>
<data name="ViewGuideStepStaticResourceSettingHint" xml:space="preserve">
<value>* 除非你卸載並重新安裝胡桃,否則你將無法更改這些設</value>
<value>* 除非你卸載並重新安裝胡桃,否則你將無法更改這些設</value>
</data>
<data name="ViewGuideStepStaticResourceSettingMinimumHeader" xml:space="preserve">
<value>圖片資源包體</value>
@@ -1568,17 +1556,11 @@
<data name="ViewModelCultivationProjectInvalidName" xml:space="preserve">
<value>不能新增名稱無效的計劃</value>
</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">
<value>即時便箋 Webhook URL 配置成功</value>
</data>
<data name="ViewModelDailyNoteHoyolabVerificationUnsupported" xml:space="preserve">
<value>HoYoLAB 賬號不支持驗證即時便箋</value>
<value>HoYoLAB 賬號不支持驗證實时便箋</value>
</data>
<data name="ViewModelDailyNoteModifyTaskFail" xml:space="preserve">
<value>修改計劃任務失敗</value>
@@ -1599,7 +1581,7 @@
<value>8 分鐘 | 1 樹脂</value>
</data>
<data name="ViewModelDailyNoteRequestProgressTitle" xml:space="preserve">
<value>正在獲取時便箋信息,請稍候</value>
<value>正在獲取時便箋信息,請稍候</value>
</data>
<data name="ViewModelExportSuccessMessage" xml:space="preserve">
<value>成功儲存至指定位置</value>
@@ -1608,13 +1590,13 @@
<value>匯出成功</value>
</data>
<data name="ViewModelExportWarningMessage" xml:space="preserve">
<value>寫入檔案時遇到問題</value>
<value>寫入文件時遇到問題</value>
</data>
<data name="ViewModelExportWarningTitle" xml:space="preserve">
<value>匯出失敗</value>
</data>
<data name="ViewModelGachaLogExportFileType" xml:space="preserve">
<value>UIFG JSON 檔案</value>
<value>UIFG JSON 文件</value>
</data>
<data name="ViewModelGachaLogImportComplete" xml:space="preserve">
<value>匯入完成</value>
@@ -1671,7 +1653,7 @@
<value>下一步</value>
</data>
<data name="ViewModelGuideActionStaticResourceBegin" xml:space="preserve">
<value>下載資源檔案中,請稍候</value>
<value>下載資源文件中,請稍候</value>
</data>
<data name="ViewModelGuideStaticResourceQualityHigh" xml:space="preserve">
<value>高品質</value>
@@ -1680,7 +1662,7 @@
<value>原圖</value>
</data>
<data name="ViewModelHutaoPassportEmailNotValidHint" xml:space="preserve">
<value>請輸入正確的電子郵件地址</value>
<value>請輸入正確的郵箱</value>
</data>
<data name="ViewModelImportFromClipboardErrorTitle" xml:space="preserve">
<value>剪貼板中的文本格式不正塙</value>
@@ -1698,7 +1680,7 @@
<value>切換伺服器失敗</value>
</data>
<data name="ViewModelLaunchGameFixConfigurationFileButtonText" xml:space="preserve">
<value>修複配置檔案</value>
<value>修複配置文件</value>
</data>
<data name="ViewModelLaunchGameFixConfigurationFileSuccess" xml:space="preserve">
<value>修複完成</value>
@@ -1728,7 +1710,7 @@
<value>操作完成</value>
</data>
<data name="ViewModelSettingClearWebCacheFail" xml:space="preserve">
<value>清除失敗,檔案目錄權限不足,請使用系統管理員模式重試</value>
<value>清除失敗,文件目錄權限不足,請使用系統管理員模式重試</value>
</data>
<data name="ViewModelSettingClearWebCachePathInvalid" xml:space="preserve">
<value>清除失敗,找不到目錄:{0}</value>
@@ -1755,7 +1737,7 @@
<value>無感驗證復合 URL 配置成功</value>
</data>
<data name="ViewModelSettingResetStaticResourceProgress" xml:space="preserve">
<value>正在重設圖片資源</value>
<value>正在重置图片资源</value>
</data>
<data name="ViewModelSettingSetDataFolderSuccess" xml:space="preserve">
<value>設置數據目錄成功,重新啟動以應用更改</value>
@@ -1800,7 +1782,7 @@
<value>待處理</value>
</data>
<data name="ViewModelWelcomeDownloadSummaryException" xml:space="preserve">
<value>檔案下載異常</value>
<value>文件下載異常</value>
</data>
<data name="ViewPageAchievementAddArchive" xml:space="preserve">
<value>建立新存檔</value>
@@ -1815,7 +1797,7 @@
<value>從剪貼簿匯入</value>
</data>
<data name="ViewPageAchievementImportFromFile" xml:space="preserve">
<value>從 UIAF 檔案匯入</value>
<value>從 UIAF 文件匯入</value>
</data>
<data name="ViewPageAchievementImportLabel" xml:space="preserve">
<value>匯入</value>
@@ -1878,7 +1860,7 @@
<value>同步角色天賦信息</value>
</data>
<data name="ViewPageAvatarPropertyRefreshFromHoyolabGameRecord" xml:space="preserve">
<value>從 HoYoLAB 戰績同步</value>
<value>從米遊社原神戰績同步</value>
</data>
<data name="ViewPageAvatarPropertyRefreshFromHoyolabGameRecordDescription" xml:space="preserve">
<value>同步角色天賦外的大部分信息</value>
@@ -1964,9 +1946,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>
@@ -1989,7 +1968,7 @@
<value>自動重新整理</value>
</data>
<data name="ViewPageDailyNoteSettingAutoRefreshDescription" xml:space="preserve">
<value>間隔選定的時間後重新整理添加的時便箋</value>
<value>間隔選定的時間後重新整理添加的時便箋</value>
</data>
<data name="ViewPageDailyNoteSettingRefreshElevatedHint" xml:space="preserve">
<value>這些選項僅允許在非系統管理員模式下更改</value>
@@ -1997,9 +1976,6 @@
<data name="ViewPageDailyNoteSettingRefreshHeader" xml:space="preserve">
<value>重新整理</value>
</data>
<data name="ViewPageDailyNoteSettingRefreshNotifyIconDisabledHint" xml:space="preserve">
<value>為啟用通知區域圖標,關閉窗口後自動重新整理將不會執行</value>
</data>
<data name="ViewPageDailyNoteSlientModeDescription" xml:space="preserve">
<value>在我游玩原神時不通知我</value>
</data>
@@ -2103,7 +2079,7 @@
<value>輸入</value>
</data>
<data name="ViewPageGachaLogRecoverFromHutaoCloudDescription" xml:space="preserve">
<value>從胡桃恢復祈願紀錄</value>
<value>從胡桃恢復祈願紀錄</value>
</data>
<data name="ViewPageGachaLogRefresh" xml:space="preserve">
<value>重新整理</value>
@@ -2253,7 +2229,7 @@
<value>刪除帳號的數據將永遠丢失,無法恢復</value>
</data>
<data name="ViewPageHutaoPassportUserNameHint" xml:space="preserve">
<value>請輸入電子郵件地址</value>
<value>請輸入電地址</value>
</data>
<data name="ViewPageHutaoPassportVerifyCodeAction" xml:space="preserve">
<value>取得驗證碼</value>
@@ -2391,7 +2367,7 @@
<value>綁定當前用戶的角色</value>
</data>
<data name="ViewPageLaunchGameSwitchAccountDescription" xml:space="preserve">
<value>在游戲内切換賬號,網絡環境發生變化需要重新手動檢測</value>
<value>在游戲内切換賬號,網絡環境發生變化需要重新手動檢測</value>
</data>
<data name="ViewPageLaunchGameSwitchAccountDetectAction" xml:space="preserve">
<value>檢測</value>
@@ -2406,7 +2382,7 @@
<value>重新命名</value>
</data>
<data name="ViewPageLaunchGameSwitchSchemeDescription" xml:space="preserve">
<value>切換遊戲伺服器(大陸伺服器/渠道伺服器/國際伺服器</value>
<value>切換遊戲伺服器(陸服/渠道服/國際服</value>
</data>
<data name="ViewPageLaunchGameSwitchSchemeHeader" xml:space="preserve">
<value>伺服器</value>
@@ -2436,7 +2412,7 @@
<value>請輸入您的 HoYoLAB UID</value>
</data>
<data name="ViewPageLoginMihoyoUserDescription" xml:space="preserve">
<value>你正在通過由我們提供的內嵌網頁視圖登入 miHoYo 通行證賬號,我們會在你點擊 我已登 按鈕後,讀取你的 Cookie 信息,由此視圖起的網絡通信只生於你的計算機與 miHoYo 服務器之間</value>
<value>你正在通過由我們提供的內嵌網頁視圖登錄 米哈遊通行證,我們會在你點擊 我已登 按鈕後,讀取你的 Cookie 信息,由此視圖起的網絡通信只生於你的計算機與米哈遊服務器之間</value>
</data>
<data name="ViewPageLoginMihoyoUserLoggedInAction" xml:space="preserve">
<value>我已登入</value>
@@ -2445,7 +2421,7 @@
<value>在下方登入 miHoYo 通行證賬號</value>
</data>
<data name="ViewPageOpenScreenshotFolderAction" xml:space="preserve">
<value>開啟截圖檔案夾</value>
<value>開啟截圖資料夾</value>
</data>
<data name="ViewPageResetGamePathAction" xml:space="preserve">
<value>選定遊戲路徑</value>
@@ -2484,7 +2460,7 @@
<value>圖片暫存存放在此</value>
</data>
<data name="ViewPageSettingCacheFolderHeader" xml:space="preserve">
<value>暫存 檔案夾</value>
<value>暫存檔案夾</value>
</data>
<data name="ViewPageSettingCardHutaoPassportHeader" xml:space="preserve">
<value>胡桃通行證</value>
@@ -2514,7 +2490,7 @@
<value>用戶數據/元數據 存放在此</value>
</data>
<data name="ViewPageSettingDataFolderHeader" xml:space="preserve">
<value>資料 檔案夾</value>
<value>資料檔案夾</value>
</data>
<data name="ViewPageSettingDeleteCacheAction" xml:space="preserve">
<value>刪除</value>
@@ -2601,7 +2577,7 @@
<value>成就管理</value>
</data>
<data name="ViewpageSettingHomeCardItemDailyNoteHeader" xml:space="preserve">
<value>時便籤</value>
<value>時便籤</value>
</data>
<data name="ViewpageSettingHomeCardItemgachaStatisticsHeader" xml:space="preserve">
<value>祈願紀錄</value>
@@ -2664,7 +2640,7 @@
<value>刪除帳號</value>
</data>
<data name="ViewPageSettingIsAdvancedLaunchOptionsEnabledDescription" xml:space="preserve">
<value>在完整閱讀原神和胡桃工具箱用戶協定後,我選擇啟用「啟動遊戲 - 進階功能」</value>
<value>在完整閱讀原神和胡桃工具箱使用者協定後,我選擇啟用「啟動遊戲 - 進階功能」</value>
</data>
<data name="ViewPageSettingIsAdvancedLaunchOptionsEnabledHeader" xml:space="preserve">
<value>進階功能</value>
@@ -2678,12 +2654,6 @@
<data name="ViewPageSettingKeyShortcutHeader" xml:space="preserve">
<value>快速鍵</value>
</data>
<data name="ViewPageSettingNotifyIconDescription" xml:space="preserve">
<value>在通知區域顯示圖標,以允許執行後臺任務,重新啟動後生效</value>
</data>
<data name="ViewPageSettingNotifyIconHeader" xml:space="preserve">
<value>通知區域圖標</value>
</data>
<data name="ViewPageSettingOfficialSiteNavigate" xml:space="preserve">
<value>前往官網</value>
</data>
@@ -2691,7 +2661,7 @@
<value>自定義背景圖片,支援 bmp / gif / ico / jpg / jpeg / png / tiff / webp 格式</value>
</data>
<data name="ViewPageSettingOpenBackgroundImageFolderHeader" xml:space="preserve">
<value>打開背景圖片檔案夾</value>
<value>打開背景圖片資料夾</value>
</data>
<data name="ViewPageSettingResetAction" xml:space="preserve">
<value>重設</value>
@@ -2721,7 +2691,7 @@
<value>遊戲路徑</value>
</data>
<data name="ViewPageSettingSetGamePathHint" xml:space="preserve">
<value>設遊戲路徑時請選擇遊戲本體YuanShen.exe 或 GenshinImpact.exe 而不是啟動器launcher.exe</value>
<value>設遊戲路徑時請選擇遊戲本體YuanShen.exe 或 GenshinImpact.exe 而不是啟動器launcher.exe</value>
</data>
<data name="ViewPageSettingShellExperienceHeader" xml:space="preserve">
<value>Shell 體驗</value>
@@ -2925,7 +2895,7 @@
<value>出戰次數</value>
</data>
<data name="ViewSpiralAbyssStatistics" xml:space="preserve">
<value>統計資料</value>
<value>統計數據</value>
</data>
<data name="ViewSpiralAbyssTakeDamage" xml:space="preserve">
<value>最多承傷</value>
@@ -2937,7 +2907,7 @@
<value>上傳資料</value>
</data>
<data name="ViewTitileUpdatePackageDownloadContent" xml:space="preserve">
<value>是否立即下</value>
<value>是否立即下</value>
</data>
<data name="ViewTitileUpdatePackageDownloadFailedMessage" xml:space="preserve">
<value>下載更新失敗</value>
@@ -3036,19 +3006,19 @@
<value>武器資料</value>
</data>
<data name="WebAnnouncementMatchPermanentActivityTime" xml:space="preserve">
<value>(?:(?:〓活動時間〓|〓任務開放時間〓).*?(\d\.\d)版本更新(?:完成|)|&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;)後永久放</value>
<value>(?:〓活动时间〓|〓任务开放时间〓).*?(\d\.\d)版本更新(?:完成|)永久放</value>
</data>
<data name="WebAnnouncementMatchPersistentActivityTime" xml:space="preserve">
<value>〓活動時間〓.*?(\d\.\d)版本期間持續開放</value>
<value>〓活动时间〓.*?(\d\.\d)版本期间持续开放</value>
</data>
<data name="WebAnnouncementMatchTransientActivityTime" xml:space="preserve">
<value>(?:〓活動時間〓|祈願時間|【上架時間】|〓折扣時間〓).*?(\d\.\d)版本更新.*?~.*?&amp;lt;t class="t_(?:gl|lc)".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;</value>
<value>(?:〓活动时间〓|祈愿时间|【上架时间】|〓折扣时间〓).*?(\d\.\d)版本更新.*?~.*?&amp;lt;t class="t_(?:gl|lc)".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;</value>
</data>
<data name="WebAnnouncementMatchVersionUpdatePreviewTime" xml:space="preserve">
<value>將於&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;行版本更新維護</value>
<value>将于&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;行版本更新维护</value>
</data>
<data name="WebAnnouncementMatchVersionUpdatePreviewTitle" xml:space="preserve">
<value>\d\.\d版本更新停服說明</value>
<value>\d\.\d版本更新维护预告</value>
</data>
<data name="WebAnnouncementMatchVersionUpdateTime" xml:space="preserve">
<value>〓更新時間〓.+?&amp;lt;t class=\"t_(?:gl|lc)\".*?&amp;gt;(.*?)&amp;lt;/t&amp;gt;</value>
@@ -3074,9 +3044,6 @@
<data name="WebBridgeShareCopyToClipboardSuccess" xml:space="preserve">
<value>已複製到剪貼簿</value>
</data>
<data name="WebDailyNoteArchonQuestChapterFinished" xml:space="preserve">
<value>所有魔神任務已完成</value>
</data>
<data name="WebDailyNoteArchonQuestStatusFinished" xml:space="preserve">
<value>全部完成</value>
</data>
@@ -3174,7 +3141,7 @@
<value>{0} 秒</value>
</data>
<data name="WebDailyNoteVerificationFailed" xml:space="preserve">
<value>驗證失敗,請手動進行驗證或前往「 HoYoLAB -工具箱-戰績-時便箋」頁面查看。</value>
<value>驗證失敗,請手動進行驗證或前往「米遊社-旅行工具-原神戰績-時便箋」頁面查看。</value>
</data>
<data name="WebEnkaResponseStatusCode400" xml:space="preserve">
<value>錯誤的 UID 格式</value>
@@ -3225,10 +3192,10 @@
<value>無效的 UID</value>
</data>
<data name="WebHoyolabRegionCNGF01" xml:space="preserve">
<value>大陸伺服器 官方伺服器</value>
<value>陸服 官方服</value>
</data>
<data name="WebHoyolabRegionCNQD01" xml:space="preserve">
<value>大陸伺服器 渠道伺服器</value>
<value>陸服 渠道服</value>
</data>
<data name="WebHoyolabRegionOSASIA" xml:space="preserve">
<value>國際服 亞服</value>
@@ -3246,7 +3213,7 @@
<value>胡桃服務維護中</value>
</data>
<data name="WebIndexOrSpiralAbyssVerificationFailed" xml:space="preserve">
<value>驗證失敗,請手動進行驗證或前往「 HoYoLAB -工具箱-戰績」頁面查看。</value>
<value>驗證失敗,請手動進行驗證或前往「米遊社-旅行工具-原神戰績」頁面查看。</value>
</data>
<data name="WebResponseFormat" xml:space="preserve">
<value>狀態:{0} | 信息:{1}</value>
@@ -3257,9 +3224,6 @@
<data name="WebResponseRequestExceptionFormat" xml:space="preserve">
<value>[{0}] 中的 [{1}] 網路請求異常,請稍後再試</value>
</data>
<data name="WebResponseSignInErrorHint" xml:space="preserve">
<value>登入失敗,請前往 HoYoLAB 初始化賬號,原始消息:{0}</value>
</data>
<data name="WindowIdentifyMonitorHeader" xml:space="preserve">
<value>顯示器編號</value>
</data>

View File

@@ -82,10 +82,31 @@ internal abstract partial class DbStoreOptions : ObservableObject
return storage.Value;
}
[return: NotNullIfNotNull(nameof(defaultValue))]
protected T GetOption<T>(ref T? storage, string key, Func<string, T> deserializer, T defaultValue)
[return: NotNull]
protected T GetOption<T>(ref T? storage, string key, Func<string, T> deserializer, [DisallowNull] T defaultValue)
{
return GetOption(ref storage, key, deserializer, () => defaultValue);
if (storage is not null)
{
return storage;
}
using (IServiceScope scope = serviceProvider.CreateScope())
{
AppDbContext appDbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
string? value = appDbContext.Settings.SingleOrDefault(e => e.Key == key)?.Value;
if (value is null)
{
storage = defaultValue;
}
else
{
T targetValue = deserializer(value);
ArgumentNullException.ThrowIfNull(targetValue);
storage = targetValue;
}
}
return storage;
}
protected T GetOption<T>(ref T? storage, string key, Func<string, T> deserializer, Func<T> defaultValueFactory)

View File

@@ -32,6 +32,6 @@ internal sealed partial class DailyNoteWebhookOperation
.SetHeader("x-uid", $"{playerUid}")
.PostJson(dailyNote);
await builder.SendAsync(httpClient, logger, token).ConfigureAwait(false);
await builder.TryCatchSendAsync(httpClient, logger, token).ConfigureAwait(false);
}
}

View File

@@ -1,85 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Win32.Foundation;
using Snap.Hutao.Win32.Graphics.Direct3D;
using Snap.Hutao.Win32.Graphics.Direct3D11;
using Snap.Hutao.Win32.Graphics.Dxgi;
using Snap.Hutao.Win32.System.Com;
using Windows.Graphics.DirectX.Direct3D11;
using WinRT;
using static Snap.Hutao.Win32.ConstValues;
using static Snap.Hutao.Win32.D3d11;
using static Snap.Hutao.Win32.Dxgi;
using static Snap.Hutao.Win32.Macros;
namespace Snap.Hutao.Service.Game.Automation.ScreenCapture;
internal static class DirectX
{
public static unsafe bool TryCreateDXGIFactory(uint flags, out IDXGIFactory6* factory, out HRESULT hr)
{
hr = CreateDXGIFactory2(flags, in IDXGIFactory6.IID, out factory);
return SUCCEEDED(hr);
}
public static unsafe bool TryGetHighPerformanceAdapter(IDXGIFactory6* factory, out IDXGIAdapter* adapter, out HRESULT hr)
{
hr = factory->EnumAdapterByGpuPreference(0U, DXGI_GPU_PREFERENCE.DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, in IDXGIAdapter.IID, out adapter);
if (FAILED(hr))
{
return false;
}
IUnknownMarshal.Release(adapter);
return true;
}
public static unsafe bool TryCreateD3D11Device(IDXGIAdapter* adapter, D3D11_CREATE_DEVICE_FLAG flags, out ID3D11Device* device, out HRESULT hr)
{
hr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE.D3D_DRIVER_TYPE_HARDWARE, default, flags, [], D3D11_SDK_VERSION, out device, out _, out _);
if (FAILED(hr))
{
return false;
}
IUnknownMarshal.Release(device);
return true;
}
public static unsafe bool TryAsDXGIDevice(ID3D11Device* device, out IDXGIDevice* dxgiDevice, out HRESULT hr)
{
hr = IUnknownMarshal.QueryInterface(device, in IDXGIDevice.IID, out dxgiDevice);
if (FAILED(hr))
{
return false;
}
IUnknownMarshal.Release(dxgiDevice);
return true;
}
public static unsafe bool TryCreateDirect3D11Device(IDXGIDevice* dxgiDevice, [NotNullWhen(true)] out IDirect3DDevice? direct3DDevice, out HRESULT hr)
{
hr = CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice, out Win32.System.WinRT.IInspectable* inspectable);
if (FAILED(hr))
{
direct3DDevice = default;
return false;
}
direct3DDevice = IInspectable.FromAbi((nint)inspectable).ObjRef.AsInterface<IDirect3DDevice>();
return true;
}
public static unsafe bool TryCreateSwapChainForComposition(IDXGIFactory6* factory, ID3D11Device* device, ref readonly DXGI_SWAP_CHAIN_DESC1 desc, out IDXGISwapChain1* swapChain, out HRESULT hr)
{
hr = factory->CreateSwapChainForComposition((IUnknown*)device, in desc, default, out swapChain);
if (FAILED(hr))
{
return false;
}
return true;
}
}

View File

@@ -4,106 +4,44 @@
using Snap.Hutao.Win32.Foundation;
using Snap.Hutao.Win32.Graphics.Direct3D11;
using Snap.Hutao.Win32.Graphics.Dwm;
using Snap.Hutao.Win32.Graphics.Dxgi;
using Snap.Hutao.Win32.Graphics.Dxgi.Common;
using Snap.Hutao.Win32.Graphics.Gdi;
using Snap.Hutao.Win32.System.Com;
using Snap.Hutao.Win32.System.WinRT.Graphics.Capture;
using Windows.Graphics.Capture;
using Windows.Graphics.DirectX;
using Windows.Graphics.DirectX.Direct3D11;
using static Snap.Hutao.Win32.ConstValues;
using static Snap.Hutao.Win32.DwmApi;
using static Snap.Hutao.Win32.Gdi32;
using static Snap.Hutao.Win32.User32;
namespace Snap.Hutao.Service.Game.Automation.ScreenCapture;
internal struct GameScreenCaptureContext : IDisposable
internal readonly struct GameScreenCaptureContext
{
public readonly GraphicsCaptureItem Item;
public readonly bool PreviewEnabled;
private const uint CreateDXGIFactoryFlag =
#if DEBUG
DXGI_CREATE_FACTORY_DEBUG;
#else
0;
#endif
private const D3D11_CREATE_DEVICE_FLAG D3d11CreateDeviceFlag =
D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_BGRA_SUPPORT
#if DEBUG
| D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_DEBUG
#endif
;
private readonly IDirect3DDevice direct3DDevice;
private readonly HWND hwnd;
private unsafe IDXGIFactory6* factory;
private unsafe IDXGIAdapter* adapter;
private unsafe ID3D11Device* d3d11Device;
private unsafe IDXGIDevice* dxgiDevice;
private IDirect3DDevice? direct3DDevice;
private unsafe IDXGISwapChain1* swapChain;
[SuppressMessage("", "SH002")]
private unsafe GameScreenCaptureContext(HWND hwnd, bool preview)
public GameScreenCaptureContext(IDirect3DDevice direct3DDevice, HWND hwnd)
{
this.direct3DDevice = direct3DDevice;
this.hwnd = hwnd;
GraphicsCaptureItem.As<IGraphicsCaptureItemInterop>().CreateForWindow(hwnd, out Item);
PreviewEnabled = preview;
}
[SuppressMessage("", "SH002")]
public static unsafe GameScreenCaptureContextCreationResult Create(HWND hwnd, bool preview)
{
GameScreenCaptureContext context = new(hwnd, preview);
if (!DirectX.TryCreateDXGIFactory(CreateDXGIFactoryFlag, out context.factory, out HRESULT hr))
{
return new(GameScreenCaptureContextCreationResultKind.CreateDxgiFactoryFailed, hr);
}
if (!DirectX.TryGetHighPerformanceAdapter(context.factory, out context.adapter, out hr))
{
return new(GameScreenCaptureContextCreationResultKind.EnumAdapterByGpuPreferenceFailed, hr);
}
if (!DirectX.TryCreateD3D11Device(default, D3d11CreateDeviceFlag, out context.d3d11Device, out hr))
{
return new(GameScreenCaptureContextCreationResultKind.D3D11CreateDeviceFailed, hr);
}
if (!DirectX.TryAsDXGIDevice(context.d3d11Device, out context.dxgiDevice, out hr))
{
return new(GameScreenCaptureContextCreationResultKind.D3D11DeviceQueryDXGIDeviceFailed, hr);
}
if (!DirectX.TryCreateDirect3D11Device(context.dxgiDevice, out context.direct3DDevice, out hr))
{
return new(GameScreenCaptureContextCreationResultKind.CreateDirect3D11DeviceFromDXGIDeviceFailed, hr);
}
return new GameScreenCaptureContextCreationResult(GameScreenCaptureContextCreationResultKind.Success, context);
}
public Direct3D11CaptureFramePool CreatePool()
{
(DirectXPixelFormat winrt, DXGI_FORMAT dx) = DeterminePixelFormat(hwnd);
CreateOrUpdateDXGISwapChain(dx);
return Direct3D11CaptureFramePool.CreateFreeThreaded(direct3DDevice, winrt, 2, Item.Size);
return Direct3D11CaptureFramePool.CreateFreeThreaded(direct3DDevice, DeterminePixelFormat(hwnd), 2, Item.Size);
}
public void RecreatePool(Direct3D11CaptureFramePool framePool)
{
(DirectXPixelFormat winrt, DXGI_FORMAT dx) = DeterminePixelFormat(hwnd);
CreateOrUpdateDXGISwapChain(dx);
framePool.Recreate(direct3DDevice, winrt, 2, Item.Size);
framePool.Recreate(direct3DDevice, DeterminePixelFormat(hwnd), 2, Item.Size);
}
public readonly GraphicsCaptureSession CreateSession(Direct3D11CaptureFramePool framePool)
public GraphicsCaptureSession CreateSession(Direct3D11CaptureFramePool framePool)
{
GraphicsCaptureSession session = framePool.CreateCaptureSession(Item);
session.IsCursorCaptureEnabled = false;
@@ -111,7 +49,7 @@ internal struct GameScreenCaptureContext : IDisposable
return session;
}
public readonly bool TryGetClientBox(uint width, uint height, out D3D11_BOX clientBox)
public bool TryGetClientBox(uint width, uint height, out D3D11_BOX clientBox)
{
clientBox = default;
@@ -150,39 +88,8 @@ internal struct GameScreenCaptureContext : IDisposable
return clientBox.right <= width && clientBox.bottom <= height;
}
public unsafe readonly void AttachPreview(GameScreenCaptureDebugPreviewWindow? window)
{
if (PreviewEnabled && window is not null)
{
window.UpdateSwapChain(swapChain);
}
}
public unsafe readonly void UpdatePreview(GameScreenCaptureDebugPreviewWindow? window, IDirect3DSurface surface)
{
if (PreviewEnabled && window is not null)
{
window.UnsafeUpdatePreview(d3d11Device, surface);
}
}
public unsafe readonly void DetachPreview(GameScreenCaptureDebugPreviewWindow? window)
{
if (PreviewEnabled && window is not null)
{
window.UpdateSwapChain(null);
window.Close();
}
}
public unsafe readonly void Dispose()
{
IUnknownMarshal.Release(factory);
IUnknownMarshal.Release(swapChain);
}
[SuppressMessage("", "SH002")]
private static (DirectXPixelFormat WinRTFormat, DXGI_FORMAT DXFormat) DeterminePixelFormat(HWND hwnd)
private static DirectXPixelFormat DeterminePixelFormat(HWND hwnd)
{
HDC hdc = GetDC(hwnd);
if (hdc != HDC.NULL)
@@ -191,31 +98,10 @@ internal struct GameScreenCaptureContext : IDisposable
_ = ReleaseDC(hwnd, hdc);
if (bitsPerPixel >= 32)
{
return (DirectXPixelFormat.R16G16B16A16Float, DXGI_FORMAT.DXGI_FORMAT_R16G16B16A16_FLOAT);
return DirectXPixelFormat.R16G16B16A16Float;
}
}
return (DirectXPixelFormat.B8G8R8A8UIntNormalized, DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM);
}
private unsafe void CreateOrUpdateDXGISwapChain(DXGI_FORMAT format)
{
if (!PreviewEnabled)
{
return;
}
DXGI_SWAP_CHAIN_DESC1 desc = default;
desc.Width = (uint)Item.Size.Width;
desc.Height = (uint)Item.Size.Height;
desc.Format = format;
desc.SampleDesc.Count = 1;
desc.BufferUsage = DXGI_USAGE.DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.BufferCount = 2;
desc.Scaling = DXGI_SCALING.DXGI_SCALING_STRETCH;
desc.SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
desc.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_PREMULTIPLIED;
DirectX.TryCreateSwapChainForComposition(factory, d3d11Device, in desc, out swapChain, out HRESULT hr);
return DirectXPixelFormat.B8G8R8A8UIntNormalized;
}
}

View File

@@ -1,25 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Snap.Hutao.Win32.Foundation;
namespace Snap.Hutao.Service.Game.Automation.ScreenCapture;
internal readonly struct GameScreenCaptureContextCreationResult
{
public readonly GameScreenCaptureContextCreationResultKind Kind;
public readonly HRESULT HResult;
public readonly GameScreenCaptureContext Context;
public GameScreenCaptureContextCreationResult(GameScreenCaptureContextCreationResultKind kind, HRESULT hResult)
{
Kind = kind;
HResult = hResult;
}
public GameScreenCaptureContextCreationResult(GameScreenCaptureContextCreationResultKind kind, GameScreenCaptureContext context)
{
Kind = kind;
Context = context;
}
}

View File

@@ -1,14 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
namespace Snap.Hutao.Service.Game.Automation.ScreenCapture;
internal enum GameScreenCaptureContextCreationResultKind
{
Success,
CreateDxgiFactoryFailed,
EnumAdapterByGpuPreferenceFailed,
D3D11CreateDeviceFailed,
D3D11DeviceQueryDXGIDeviceFailed,
CreateDirect3D11DeviceFromDXGIDeviceFailed,
}

View File

@@ -1,14 +0,0 @@
<Window
x:Class="Snap.Hutao.Service.Game.Automation.ScreenCapture.GameScreenCaptureDebugPreviewWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:Snap.Hutao.Service.Game.Automation.ScreenCapture"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<SwapChainPanel
x:Name="Presenter"
AllowFocusOnInteraction="False"
AllowFocusWhenDisabled="False"/>
</Window>

View File

@@ -1,47 +0,0 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Snap.Hutao.Core.Windowing;
using Snap.Hutao.Win32.Graphics.Direct3D11;
using Snap.Hutao.Win32.Graphics.Dxgi;
using Snap.Hutao.Win32.System.WinRT.Graphics.Capture;
using Snap.Hutao.Win32.System.WinRT.Xaml;
using Windows.Graphics.DirectX.Direct3D11;
using WinRT;
namespace Snap.Hutao.Service.Game.Automation.ScreenCapture;
internal sealed partial class GameScreenCaptureDebugPreviewWindow : Window
{
private unsafe IDXGISwapChain1* swapChain1;
public GameScreenCaptureDebugPreviewWindow()
{
if (AppWindow.Presenter is OverlappedPresenter presenter)
{
presenter.IsMaximizable = false;
}
InitializeComponent();
this.InitializeController(Ioc.Default);
}
public unsafe void UpdateSwapChain(IDXGISwapChain1* swapChain1)
{
this.swapChain1 = swapChain1;
ISwapChainPanelNative native = Presenter.As<IInspectable>().ObjRef.AsInterface<ISwapChainPanelNative>();
native.SetSwapChain((IDXGISwapChain*)swapChain1);
}
public unsafe void UnsafeUpdatePreview(ID3D11Device* device, IDirect3DSurface surface)
{
IDirect3DDxgiInterfaceAccess access = surface.As<IDirect3DDxgiInterfaceAccess>();
swapChain1->GetBuffer(0, in ID3D11Texture2D.IID, out ID3D11Texture2D* buffer);
device->GetImmediateContext(out ID3D11DeviceContext* deviceContext);
access.GetInterface(in ID3D11Resource.IID, out ID3D11Resource* resource);
deviceContext->CopyResource((ID3D11Resource*)buffer, resource);
swapChain1->Present(0, default);
}
}

View File

@@ -3,9 +3,16 @@
using Snap.Hutao.Core;
using Snap.Hutao.Win32.Foundation;
using Snap.Hutao.Win32.Graphics.Direct3D;
using Snap.Hutao.Win32.Graphics.Direct3D11;
using Snap.Hutao.Win32.Graphics.Dxgi;
using Snap.Hutao.Win32.System.Com;
using Windows.Graphics.Capture;
using Windows.Graphics.DirectX.Direct3D11;
using WinRT;
using static Snap.Hutao.Win32.ConstValues;
using static Snap.Hutao.Win32.D3D11;
using static Snap.Hutao.Win32.Macros;
namespace Snap.Hutao.Service.Game.Automation.ScreenCapture;
@@ -13,25 +20,11 @@ namespace Snap.Hutao.Service.Game.Automation.ScreenCapture;
[Injection(InjectAs.Singleton, typeof(IGameScreenCaptureService))]
internal sealed partial class GameScreenCaptureService : IGameScreenCaptureService
{
private const uint CreateDXGIFactoryFlag =
#if DEBUG
DXGI_CREATE_FACTORY_DEBUG;
#else
0;
#endif
private const D3D11_CREATE_DEVICE_FLAG D3d11CreateDeviceFlag =
D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_BGRA_SUPPORT
#if DEBUG
| D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_DEBUG
#endif
;
private readonly ILogger<GameScreenCaptureService> logger;
public bool IsSupported()
{
if (!UniversalApiContract.IsPresent(WindowsVersion.Windows10Version1903))
if (!Core.UniversalApiContract.IsPresent(WindowsVersion.Windows10Version1903))
{
logger.LogWarning("Windows 10 Version 1903 or later is required for Windows.Graphics.Capture API.");
return false;
@@ -47,34 +40,47 @@ internal sealed partial class GameScreenCaptureService : IGameScreenCaptureServi
}
[SuppressMessage("", "SH002")]
public unsafe bool TryStartCapture(HWND hwnd, bool preview, [NotNullWhen(true)] out GameScreenCaptureSession? session)
public unsafe bool TryStartCapture(HWND hwnd, [NotNullWhen(true)] out GameScreenCaptureSession? session)
{
session = default;
GameScreenCaptureContextCreationResult result = GameScreenCaptureContext.Create(hwnd, preview);
D3D11_CREATE_DEVICE_FLAG flag = D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_BGRA_SUPPORT
#if DEBUG
| D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_DEBUG
#endif
;
switch (result.Kind)
HRESULT hr;
hr = D3D11CreateDevice(default, D3D_DRIVER_TYPE.D3D_DRIVER_TYPE_HARDWARE, default, flag, [], D3D11_SDK_VERSION, out ID3D11Device* pD3D11Device, out _, out _);
if (FAILED(hr))
{
case GameScreenCaptureContextCreationResultKind.Success:
session = new(result.Context, logger);
return true;
case GameScreenCaptureContextCreationResultKind.CreateDxgiFactoryFailed:
logger.LogWarning("CreateDXGIFactory2 failed with code: {Code}", result.HResult);
return false;
case GameScreenCaptureContextCreationResultKind.EnumAdapterByGpuPreferenceFailed:
logger.LogWarning("IDXGIFactory6.EnumAdapterByGpuPreference failed with code: {Code}", result.HResult);
return false;
case GameScreenCaptureContextCreationResultKind.D3D11CreateDeviceFailed:
logger.LogWarning("D3D11CreateDevice failed with code: {Code}", result.HResult);
return false;
case GameScreenCaptureContextCreationResultKind.D3D11DeviceQueryDXGIDeviceFailed:
logger.LogWarning("ID3D11Device.QueryInterface<IDXGIDevice> failed with code: {Code}", result.HResult);
return false;
case GameScreenCaptureContextCreationResultKind.CreateDirect3D11DeviceFromDXGIDeviceFailed:
logger.LogWarning("CreateDirect3D11DeviceFromDXGIDevice failed with code: {Code}", result.HResult);
return false;
default:
return false;
logger.LogWarning("D3D11CreateDevice failed with code: {Code}", hr);
return false;
}
hr = IUnknownMarshal.QueryInterface(pD3D11Device, in IDXGIDevice.IID, out IDXGIDevice* pDXGIDevice);
if (FAILED(hr))
{
logger.LogWarning("ID3D11Device.QueryInterface<IDXGIDevice> failed with code: {Code}", hr);
return false;
}
IUnknownMarshal.Release(pDXGIDevice);
hr = CreateDirect3D11DeviceFromDXGIDevice(pDXGIDevice, out Win32.System.WinRT.IInspectable* inspectable);
if (FAILED(hr))
{
logger.LogWarning("CreateDirect3D11DeviceFromDXGIDevice failed with code: {Code}", hr);
return false;
}
IUnknownMarshal.Release(inspectable);
IDirect3DDevice direct3DDevice = IInspectable.FromAbi((nint)inspectable).ObjRef.AsInterface<IDirect3DDevice>();
GameScreenCaptureContext captureContext = new(direct3DDevice, hwnd);
session = new(captureContext, logger);
return true;
}
}

View File

@@ -7,7 +7,6 @@ using Snap.Hutao.Core.ExceptionService;
using Snap.Hutao.Win32.Graphics.Direct3D11;
using Snap.Hutao.Win32.Graphics.Dxgi;
using Snap.Hutao.Win32.Graphics.Dxgi.Common;
using Snap.Hutao.Win32.System.Com;
using Snap.Hutao.Win32.System.WinRT.Graphics.Capture;
using System.Buffers;
using System.Runtime.CompilerServices;
@@ -25,7 +24,6 @@ internal sealed class GameScreenCaptureSession : IDisposable
private static readonly Half ByteMaxValue = 255;
private readonly GameScreenCaptureContext captureContext;
private readonly GameScreenCaptureDebugPreviewWindow? previewWindow;
private readonly Direct3D11CaptureFramePool framePool;
private readonly GraphicsCaptureSession session;
private readonly ILogger logger;
@@ -37,23 +35,16 @@ internal sealed class GameScreenCaptureSession : IDisposable
private bool isDisposed;
[SuppressMessage("", "SH002")]
public unsafe GameScreenCaptureSession(GameScreenCaptureContext captureContext, ILogger logger)
public GameScreenCaptureSession(GameScreenCaptureContext captureContext, ILogger logger)
{
this.captureContext = captureContext;
this.logger = logger;
contentSize = captureContext.Item.Size;
if (captureContext.PreviewEnabled)
{
previewWindow = new();
}
captureContext.Item.Closed += OnItemClosed;
framePool = captureContext.CreatePool();
captureContext.AttachPreview(previewWindow);
framePool.FrameArrived += OnFrameArrived;
session = captureContext.CreateSession(framePool);
@@ -85,7 +76,6 @@ internal sealed class GameScreenCaptureSession : IDisposable
return;
}
captureContext.DetachPreview(previewWindow);
session.Dispose();
framePool.Dispose();
isDisposed = true;
@@ -121,9 +111,7 @@ internal sealed class GameScreenCaptureSession : IDisposable
try
{
captureContext.UpdatePreview(previewWindow, frame.Surface);
// UnsafeProcessFrameSurface(frame.Surface);
UnsafeProcessFrameSurface(frame.Surface);
}
catch (Exception ex)
{
@@ -147,8 +135,6 @@ internal sealed class GameScreenCaptureSession : IDisposable
return;
}
IUnknownMarshal.Release(pDXGISurface);
if (FAILED(pDXGISurface->GetDesc(out DXGI_SURFACE_DESC dxgiSurfaceDesc)))
{
return;
@@ -165,8 +151,6 @@ internal sealed class GameScreenCaptureSession : IDisposable
return;
}
IUnknownMarshal.Release(pD3D11Device);
D3D11_TEXTURE2D_DESC d3d11Texture2DDesc = default;
d3d11Texture2DDesc.Width = textureWidth;
d3d11Texture2DDesc.Height = textureHeight;
@@ -182,17 +166,12 @@ internal sealed class GameScreenCaptureSession : IDisposable
return;
}
IUnknownMarshal.Release(pD3D11Texture2D);
if (FAILED(access.GetInterface(in ID3D11Resource.IID, out ID3D11Resource* pD3D11Resource)))
{
return;
}
IUnknownMarshal.Release(pD3D11Resource);
pD3D11Device->GetImmediateContext(out ID3D11DeviceContext* pD3D11DeviceContext);
IUnknownMarshal.Release(pD3D11DeviceContext);
if (boxAvailable)
{

View File

@@ -9,5 +9,5 @@ internal interface IGameScreenCaptureService
{
bool IsSupported();
bool TryStartCapture(HWND hwnd, bool preview, [NotNullWhen(true)] out GameScreenCaptureSession? session);
bool TryStartCapture(HWND hwnd, [NotNullWhen(true)] out GameScreenCaptureSession? session);
}

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