This commit is contained in:
Poker 2023-11-15 19:49:32 +08:00
parent e28d9f6041
commit ea84843b4f
No known key found for this signature in database
GPG Key ID: C65A6AD457D5C8F8
143 changed files with 473 additions and 555 deletions

View File

@ -226,6 +226,5 @@ dotnet_naming_style.camel_begin_with__.required_prefix = _
dotnet_naming_style.camel_begin_with__.capitalization = camel_case dotnet_naming_style.camel_begin_with__.capitalization = camel_case
# ReSharper properties # ReSharper properties
resharper_max_initializer_elements_on_line = 1 resharper_max_initializer_elements_on_line = 1

1
.gitattributes vendored
View File

@ -38,7 +38,6 @@
*.filters text eol=crlf *.filters text eol=crlf
*.vcxitems text eol=crlf *.vcxitems text eol=crlf
#*.sln merge=binary #*.sln merge=binary
#*.csproj merge=binary #*.csproj merge=binary
#*.vbproj merge=binary #*.vbproj merge=binary

View File

@ -30,17 +30,18 @@
--- ---
**The Pixeval that based on WinUI 3 is now WIP, the older version, **The Pixeval that based on WinUI 3 is now WIP, the older version,
which is the WPF version has been deprecated and expecting no more supports from developers, which is the WPF version has been deprecated and expecting no more supports from developers.**
the WinUI 3 version provides a better user interface,
a more structural codebase and a modern development experience compared to the WPF version.
You can download and compile it yourself if you want to take a glance at the new version,
follow the following steps to compile and run:**
For more information, see [main page](https://sora.ink/pixeval/)
> The WinUI 3 codebase for Pixeval supports only Windows 10 (1809, Build Number 17763) and higher. > The WinUI 3 codebase for Pixeval supports only Windows 10 (1809, Build Number 17763) and higher.
> You can check this at Settings | System | About | Windows specifications > You can check this at Settings | System | About | Windows specifications
For more information, see [main page](https://sora.ink/pixeval/)
**The WinUI 3 version provides a better user interface,
a more structural codebase and a modern development experience compared to the WPF version.
You can download and compile it yourself if you want to take a glance at the new version,
follow the following steps to compile and run:**
## Prerequisites ## Prerequisites
1. Install [Visual Studio 2022](https://visualstudio.microsoft.com/vs) (Roslyn 4.x requires VS17.x, i.e. VS2022) 1. Install [Visual Studio 2022](https://visualstudio.microsoft.com/vs) (Roslyn 4.x requires VS17.x, i.e. VS2022)
@ -108,7 +109,6 @@ If this project meets your requirements perfectly, welcome the buy me a coffee a
## JetBrains Open Source License ## JetBrains Open Source License
<div> <div>
<a href="https://www.jetbrains.com/?from=Pixeval" align="right"><img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.svg" alt="JetBrains" class="logo-footer" width="100" align="left"></a> <a href="https://www.jetbrains.com/?from=Pixeval" align="right"><img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.svg" alt="JetBrains" class="logo-footer" width="100" align="left"></a>
<br/> <br/>

View File

@ -36,7 +36,7 @@
更多详细信息请前往 [项目主页](https://sora.ink/pixeval) 查看 更多详细信息请前往 [项目主页](https://sora.ink/pixeval) 查看
**WinUI3版本提供了更好的UI更好的项目结构以及更好的开发体验如果你想要了解目前的开发进度可以通过以下方法来下载并编译该项目** **WinUI3版本提供了更好的UI更好的项目结构以及更好的开发体验如果你想要了解目前的开发进度可以通过以下方法来下载并编译该项目**
## 环境要求 ## 环境要求

View File

@ -25,17 +25,12 @@ namespace Pixeval.Controls;
/// <summary> /// <summary>
/// AutomationPeer for CardControl /// AutomationPeer for CardControl
/// </summary> /// </summary>
public class CardControlAutomationPeer : FrameworkElementAutomationPeer /// <remarks>
/// Initializes a new instance of the <see cref="CardControl"/> class.
/// </remarks>
/// <param name="owner">CardControl</param>
public class CardControlAutomationPeer(CardControl owner) : FrameworkElementAutomationPeer(owner)
{ {
/// <summary>
/// Initializes a new instance of the <see cref="CardControl"/> class.
/// </summary>
/// <param name="owner">CardControl</param>
public CardControlAutomationPeer(CardControl owner)
: base(owner)
{
}
/// <summary> /// <summary>
/// Gets the control type for the element that is associated with the UI Automation peer. /// Gets the control type for the element that is associated with the UI Automation peer.
/// </summary> /// </summary>

View File

@ -43,6 +43,6 @@ public partial class PersonView : UserControl
private async void ContentContainerOnTapped(object sender, TappedRoutedEventArgs e) private async void ContentContainerOnTapped(object sender, TappedRoutedEventArgs e)
{ {
await Launcher.LaunchUriAsync(PersonProfileNavigateUri); _ = await Launcher.LaunchUriAsync(PersonProfileNavigateUri);
} }
} }

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0-windows10.0.19041.0</TargetFramework> <TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion> <TargetPlatformMinVersion>10.0.19041.0</TargetPlatformMinVersion>
<RootNamespace>Pixeval.Controls</RootNamespace> <RootNamespace>Pixeval.Controls</RootNamespace>
<Platforms>x86;x64;arm64</Platforms> <Platforms>x86;x64;arm64</Platforms>
<RuntimeIdentifiers>win-x86;win-x64;win-arm64</RuntimeIdentifiers> <RuntimeIdentifiers>win-x86;win-x64;win-arm64</RuntimeIdentifiers>

View File

@ -48,6 +48,6 @@ public sealed partial class PixevalBadge : UserControl
private void GoToState(bool useSmall) private void GoToState(bool useSmall)
{ {
VisualStateManager.GoToState(this, useSmall ? SmallState : NormalState, true); _ = VisualStateManager.GoToState(this, useSmall ? SmallState : NormalState, true);
} }
} }

View File

@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
namespace Pixeval.Controls.Windowing; namespace Pixeval.Controls.Windowing;
public interface ISupportCustomTitleBarDragRegion public interface ISupportCustomTitleBarDragRegion

View File

@ -34,7 +34,7 @@ public static class WindowFactory
public static EnhancedWindow RootWindow => _forkedWindowsInternal[0]; public static EnhancedWindow RootWindow => _forkedWindowsInternal[0];
private static readonly List<EnhancedWindow> _forkedWindowsInternal = new(); private static readonly List<EnhancedWindow> _forkedWindowsInternal = [];
public static IReadOnlyList<EnhancedWindow> ForkedWindows => _forkedWindowsInternal; public static IReadOnlyList<EnhancedWindow> ForkedWindows => _forkedWindowsInternal;

View File

@ -134,7 +134,7 @@ public sealed partial class ZoomableImage : UserControl
private bool _timerRunning; private bool _timerRunning;
private CanvasBitmap? _currentFrame; private CanvasBitmap? _currentFrame;
private readonly List<CanvasBitmap> _frames = new(); private readonly List<CanvasBitmap> _frames = [];
private readonly CancellationTokenSource _token = new(); private readonly CancellationTokenSource _token = new();
private List<int>? ClonedMsIntervals { get; set; } private List<int>? ClonedMsIntervals { get; set; }
private ManualResetEvent ManualResetEvent { get; } = new(true); private ManualResetEvent ManualResetEvent { get; } = new(true);

View File

@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
namespace Pixeval.CoreApi.Engine; namespace Pixeval.CoreApi.Engine;
public interface ICancellable public interface ICancellable

View File

@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
namespace Pixeval.CoreApi.Engine; namespace Pixeval.CoreApi.Engine;
public interface ICompletionCallback<in T> public interface ICompletionCallback<in T>

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi #region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval.CoreApi // Pixeval/Pixeval.CoreApi
@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
namespace Pixeval.CoreApi.Engine; namespace Pixeval.CoreApi.Engine;
/// <summary> /// <summary>

View File

@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
namespace Pixeval.CoreApi.Engine; namespace Pixeval.CoreApi.Engine;
public interface INotifyCompletion public interface INotifyCompletion

View File

@ -31,20 +31,15 @@ namespace Pixeval.CoreApi.Engine.Implements;
/// only supposed to be used by caching systems /// only supposed to be used by caching systems
/// </summary> /// </summary>
/// <typeparam name="T">The type of the results of the <see cref="IFetchEngine{E}" /></typeparam> /// <typeparam name="T">The type of the results of the <see cref="IFetchEngine{E}" /></typeparam>
public class AdaptedComputedFetchEngine<T> : IFetchEngine<T> /// <remarks>
/// Creates an <see cref="AdaptedComputedFetchEngine{T}" /> that delegates all of its
/// property and methods to
/// <param name="outer"></param>
/// </remarks>
/// <param name="outer">The <see cref="IEnumerable{T}" /> that is going to be delegated</param>
public class AdaptedComputedFetchEngine<T>(IEnumerable<T> outer) : IFetchEngine<T>
{ {
private readonly IEnumerable<T> _outer; private readonly IEnumerable<T> _outer = outer;
/// <summary>
/// Creates an <see cref="AdaptedComputedFetchEngine{T}" /> that delegates all of its
/// property and methods to
/// <param name="outer"></param>
/// </summary>
/// <param name="outer">The <see cref="IEnumerable{T}" /> that is going to be delegated</param>
public AdaptedComputedFetchEngine(IEnumerable<T> outer)
{
_outer = outer;
}
public MakoClient MakoClient => throw new NotSupportedException(); public MakoClient MakoClient => throw new NotSupportedException();

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi #region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval.CoreApi // Pixeval/Pixeval.CoreApi
@ -30,31 +30,24 @@ namespace Pixeval.CoreApi.Engine.Implements;
/// <summary> /// <summary>
/// An <see cref="IFetchEngine{E}" /> that fetches the bookmark of a specific user /// An <see cref="IFetchEngine{E}" /> that fetches the bookmark of a specific user
/// </summary> /// </summary>
internal class BookmarkEngine : AbstractPixivFetchEngine<Illustration> /// <remarks>
/// Creates a <see cref="BookmarkEngine" />
/// </remarks>
/// <param name="makoClient">The <see cref="MakoClient" /> that owns this object</param>
/// <param name="uid">Id of the user</param>
/// <param name="privacyPolicy">The privacy option</param>
/// <param name="targetFilter">Indicates the target API of the fetch operation</param>
/// <param name="engineHandle"></param>
internal class BookmarkEngine(
MakoClient makoClient,
string uid,
PrivacyPolicy privacyPolicy,
TargetFilter targetFilter,
EngineHandle? engineHandle = null) : AbstractPixivFetchEngine<Illustration>(makoClient, engineHandle)
{ {
private readonly PrivacyPolicy _privacyPolicy; private readonly PrivacyPolicy _privacyPolicy = privacyPolicy;
private readonly TargetFilter _targetFilter; private readonly TargetFilter _targetFilter = targetFilter;
private readonly string _uid; private readonly string _uid = uid;
/// <summary>
/// Creates a <see cref="BookmarkEngine" />
/// </summary>
/// <param name="makoClient">The <see cref="MakoClient" /> that owns this object</param>
/// <param name="uid">Id of the user</param>
/// <param name="privacyPolicy">The privacy option</param>
/// <param name="targetFilter">Indicates the target API of the fetch operation</param>
/// <param name="engineHandle"></param>
public BookmarkEngine(
MakoClient makoClient,
string uid,
PrivacyPolicy privacyPolicy,
TargetFilter targetFilter,
EngineHandle? engineHandle = null) : base(makoClient, engineHandle)
{
_uid = uid;
_privacyPolicy = privacyPolicy;
_targetFilter = targetFilter;
}
public override IAsyncEnumerator<Illustration> GetAsyncEnumerator(CancellationToken cancellationToken = new()) public override IAsyncEnumerator<Illustration> GetAsyncEnumerator(CancellationToken cancellationToken = new())
{ {

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi #region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval.CoreApi // Pixeval/Pixeval.CoreApi
@ -33,20 +33,19 @@ using Pixeval.Utilities;
namespace Pixeval.CoreApi.Engine.Implements; namespace Pixeval.CoreApi.Engine.Implements;
internal class FeedEngine(MakoClient makoClient, EngineHandle? engineHandle) : AbstractPixivFetchEngine<Feed>(makoClient, engineHandle) internal partial class FeedEngine(MakoClient makoClient, EngineHandle? engineHandle) : AbstractPixivFetchEngine<Feed>(makoClient, engineHandle)
{ {
public override IAsyncEnumerator<Feed> GetAsyncEnumerator(CancellationToken cancellationToken = new()) public override IAsyncEnumerator<Feed> GetAsyncEnumerator(CancellationToken cancellationToken = new())
{ {
return new UserFeedsAsyncEnumerator(this, MakoApiKind.WebApi)!; return new UserFeedsAsyncEnumerator(this, MakoApiKind.WebApi)!;
} }
private class UserFeedsAsyncEnumerator private partial class UserFeedsAsyncEnumerator
(FeedEngine pixivFetchEngine, MakoApiKind apiKind) : AbstractPixivAsyncEnumerator<Feed, string, FeedEngine>(pixivFetchEngine, apiKind) (FeedEngine pixivFetchEngine, MakoApiKind apiKind) : AbstractPixivAsyncEnumerator<Feed, string, FeedEngine>(pixivFetchEngine, apiKind)
{ {
private FeedRequestContext? _feedRequestContext; private FeedRequestContext? _feedRequestContext;
private string? _tt; private string? _tt;
public override async ValueTask<bool> MoveNextAsync() public override async ValueTask<bool> MoveNextAsync()
{ {
if (_feedRequestContext is null) if (_feedRequestContext is null)
@ -57,7 +56,7 @@ internal class FeedEngine(MakoClient makoClient, EngineHandle? engineHandle) : A
if (TryParsePreloadJsonFromHtml(response, out var result)) if (TryParsePreloadJsonFromHtml(response, out var result))
{ {
await UpdateAsync(result).ConfigureAwait(false); await UpdateAsync(result).ConfigureAwait(false);
_tt = Regex.Match(response, "tt: \"(?<tt>.*)\"").Groups["tt"].Value; _tt = TtRegex().Match(response).Groups["tt"].Value;
_feedRequestContext = ExtractRequestContextFromHtml(response); _feedRequestContext = ExtractRequestContextFromHtml(response);
} }
else else
@ -147,7 +146,7 @@ internal class FeedEngine(MakoClient makoClient, EngineHandle? engineHandle) : A
private static bool TryExtractPreloadJson(string html, out string json) private static bool TryExtractPreloadJson(string html, out string json)
{ {
var match = Regex.Match(html, "pixiv\\.stacc\\.env\\.preload\\.stacc \\= (?<json>.*);"); var match = PreloadRegex().Match(html);
if (match.Success) if (match.Success)
{ {
json = match.Groups["json"].Value; json = match.Groups["json"].Value;
@ -296,6 +295,11 @@ internal class FeedEngine(MakoClient makoClient, EngineHandle? engineHandle) : A
return Result<string>.OfFailure(new MakoNetworkException(url, MakoClient.Configuration.Bypass, e.Message, (int?)e.StatusCode ?? -1)); return Result<string>.OfFailure(new MakoNetworkException(url, MakoClient.Configuration.Bypass, e.Message, (int?)e.StatusCode ?? -1));
} }
} }
[GeneratedRegex("tt: \"(?<tt>.*)\"")]
private static partial Regex TtRegex();
[GeneratedRegex("pixiv\\.stacc\\.env\\.preload\\.stacc \\= (?<json>.*);")]
private static partial Regex PreloadRegex();
} }
/// <summary> /// <summary>

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi #region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval.CoreApi // Pixeval/Pixeval.CoreApi
@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
using System.Runtime.Serialization;
using Pixeval.CoreApi.Global.Enum; using Pixeval.CoreApi.Global.Enum;
namespace Pixeval.CoreApi.Global.Exception; namespace Pixeval.CoreApi.Global.Exception;
@ -34,11 +33,6 @@ public class IllegalPrivatePolicyException : MakoException
Uid = uid; Uid = uid;
} }
protected IllegalPrivatePolicyException(SerializationInfo info, StreamingContext context, string uid) : base(info, context)
{
Uid = uid;
}
public IllegalPrivatePolicyException(string? message, string uid) : base(message) public IllegalPrivatePolicyException(string? message, string uid) : base(message)
{ {
Uid = uid; Uid = uid;

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi #region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval.CoreApi // Pixeval/Pixeval.CoreApi
@ -18,8 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
using System.Runtime.Serialization;
namespace Pixeval.CoreApi.Global.Exception; namespace Pixeval.CoreApi.Global.Exception;
/// <summary> /// <summary>
@ -31,10 +29,6 @@ public class IllegalSortOptionException : MakoException
{ {
} }
protected IllegalSortOptionException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public IllegalSortOptionException(string? message) : base(message) public IllegalSortOptionException(string? message) : base(message)
{ {
} }

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi #region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval.CoreApi // Pixeval/Pixeval.CoreApi
@ -18,8 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
using System.Runtime.Serialization;
namespace Pixeval.CoreApi.Global.Exception; namespace Pixeval.CoreApi.Global.Exception;
public class MakoException : System.Exception public class MakoException : System.Exception
@ -28,10 +26,6 @@ public class MakoException : System.Exception
{ {
} }
protected MakoException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public MakoException(string? message) : base(message) public MakoException(string? message) : base(message)
{ {
} }

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi #region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval.CoreApi // Pixeval/Pixeval.CoreApi
@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
using System.Runtime.Serialization;
using Pixeval.CoreApi.Model; using Pixeval.CoreApi.Model;
namespace Pixeval.CoreApi.Global.Exception; namespace Pixeval.CoreApi.Global.Exception;
@ -30,11 +29,6 @@ public class MangaPagesNotFoundException : MakoException
Illustration = illustration; Illustration = illustration;
} }
protected MangaPagesNotFoundException(SerializationInfo info, StreamingContext context, Illustration illustration) : base(info, context)
{
Illustration = illustration;
}
public MangaPagesNotFoundException(string? message, Illustration illustration) : base(message) public MangaPagesNotFoundException(string? message, Illustration illustration) : base(message)
{ {
Illustration = illustration; Illustration = illustration;

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi #region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval.CoreApi // Pixeval/Pixeval.CoreApi
@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
using System.Runtime.Serialization;
namespace Pixeval.CoreApi.Global.Exception; namespace Pixeval.CoreApi.Global.Exception;
@ -31,10 +30,6 @@ public class RankingDateOutOfRangeException : MakoException
{ {
} }
protected RankingDateOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public RankingDateOutOfRangeException(string? message) : base(message) public RankingDateOutOfRangeException(string? message) : base(message)
{ {
} }

View File

@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
namespace Pixeval.CoreApi.Global; namespace Pixeval.CoreApi.Global;
/// <summary> /// <summary>

View File

@ -312,7 +312,7 @@ public partial class MakoClient
public IFetchEngine<Novel> NovelBookmarks(string uid, PrivacyPolicy privacyPolicy, TargetFilter targetFilter) public IFetchEngine<Novel> NovelBookmarks(string uid, PrivacyPolicy privacyPolicy, TargetFilter targetFilter)
{ {
EnsureNotCancelled(); EnsureNotCancelled();
CheckPrivacyPolicy(uid, privacyPolicy); _ = CheckPrivacyPolicy(uid, privacyPolicy);
return new NovelBookmarkEngine(this, uid, privacyPolicy, targetFilter, new EngineHandle(CancelInstance)); return new NovelBookmarkEngine(this, uid, privacyPolicy, targetFilter, new EngineHandle(CancelInstance));
} }

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi #region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval.CoreApi // Pixeval/Pixeval.CoreApi
@ -28,7 +28,7 @@ namespace Pixeval.CoreApi;
public partial class MakoClient public partial class MakoClient
{ {
private readonly List<IEngineHandleSource> _runningInstances = new(); private readonly List<IEngineHandleSource> _runningInstances = [];
/// <summary> /// <summary>
/// The globally unique ID of current <see cref="MakoClient" /> /// The globally unique ID of current <see cref="MakoClient" />

View File

@ -87,64 +87,64 @@ public partial class MakoClient : ICancellable
private IContainer BuildContainer() private IContainer BuildContainer()
{ {
var builder = new ContainerBuilder(); var builder = new ContainerBuilder();
builder.RegisterInstance(this).SingleInstance(); _ = builder.RegisterInstance(this).SingleInstance();
builder.RegisterType<PixivApiNameResolver>().SingleInstance(); _ = builder.RegisterType<PixivApiNameResolver>().SingleInstance();
builder.RegisterType<PixivImageNameResolver>().SingleInstance(); _ = builder.RegisterType<PixivImageNameResolver>().SingleInstance();
builder.RegisterType<LocalMachineNameResolver>().SingleInstance(); _ = builder.RegisterType<LocalMachineNameResolver>().SingleInstance();
builder.RegisterType<PixivApiHttpMessageHandler>().SingleInstance(); _ = builder.RegisterType<PixivApiHttpMessageHandler>().SingleInstance();
builder.RegisterType<PixivImageHttpMessageHandler>().SingleInstance(); _ = builder.RegisterType<PixivImageHttpMessageHandler>().SingleInstance();
builder.Register(static c => new MakoRetryHttpClientHandler(c.Resolve<PixivApiHttpMessageHandler>())) _ = builder.Register(static c => new MakoRetryHttpClientHandler(c.Resolve<PixivApiHttpMessageHandler>()))
.Keyed<HttpMessageHandler>(typeof(PixivApiHttpMessageHandler)) .Keyed<HttpMessageHandler>(typeof(PixivApiHttpMessageHandler))
.As<HttpMessageHandler>() .As<HttpMessageHandler>()
.PropertiesAutowired(static (info, _) => info.PropertyType == typeof(MakoClient)) .PropertiesAutowired(static (info, _) => info.PropertyType == typeof(MakoClient))
.SingleInstance(); .SingleInstance();
builder.Register(static c => new MakoRetryHttpClientHandler(c.Resolve<PixivImageHttpMessageHandler>())) _ = builder.Register(static c => new MakoRetryHttpClientHandler(c.Resolve<PixivImageHttpMessageHandler>()))
.Keyed<HttpMessageHandler>(typeof(PixivImageHttpMessageHandler)) .Keyed<HttpMessageHandler>(typeof(PixivImageHttpMessageHandler))
.As<HttpMessageHandler>() .As<HttpMessageHandler>()
.PropertiesAutowired(static (info, _) => info.PropertyType == typeof(MakoClient)) .PropertiesAutowired(static (info, _) => info.PropertyType == typeof(MakoClient))
.SingleInstance(); .SingleInstance();
builder.Register(static c => MakoHttpClient.Create(c.ResolveKeyed<HttpMessageHandler>(typeof(PixivApiHttpMessageHandler)), _ = builder.Register(static c => MakoHttpClient.Create(c.ResolveKeyed<HttpMessageHandler>(typeof(PixivApiHttpMessageHandler)),
static client => client.BaseAddress = new Uri(MakoHttpOptions.AppApiBaseUrl))) static client => client.BaseAddress = new Uri(MakoHttpOptions.AppApiBaseUrl)))
.Keyed<HttpClient>(MakoApiKind.AppApi) .Keyed<HttpClient>(MakoApiKind.AppApi)
.As<HttpClient>() .As<HttpClient>()
.SingleInstance(); .SingleInstance();
builder.Register(static c => MakoHttpClient.Create(c.ResolveKeyed<HttpMessageHandler>(typeof(PixivApiHttpMessageHandler)), _ = builder.Register(static c => MakoHttpClient.Create(c.ResolveKeyed<HttpMessageHandler>(typeof(PixivApiHttpMessageHandler)),
static client => client.BaseAddress = new Uri(MakoHttpOptions.WebApiBaseUrl))) static client => client.BaseAddress = new Uri(MakoHttpOptions.WebApiBaseUrl)))
.Keyed<HttpClient>(MakoApiKind.WebApi) .Keyed<HttpClient>(MakoApiKind.WebApi)
.As<HttpClient>() .As<HttpClient>()
.SingleInstance(); .SingleInstance();
builder.Register(static c => MakoHttpClient.Create(c.ResolveKeyed<HttpMessageHandler>(typeof(PixivApiHttpMessageHandler)), _ = builder.Register(static c => MakoHttpClient.Create(c.ResolveKeyed<HttpMessageHandler>(typeof(PixivApiHttpMessageHandler)),
static client => client.BaseAddress = new Uri(MakoHttpOptions.OAuthBaseUrl))) static client => client.BaseAddress = new Uri(MakoHttpOptions.OAuthBaseUrl)))
.Keyed<HttpClient>(MakoApiKind.AuthApi) .Keyed<HttpClient>(MakoApiKind.AuthApi)
.As<HttpClient>() .As<HttpClient>()
.SingleInstance(); .SingleInstance();
builder.Register(static c => MakoHttpClient.Create(c.ResolveKeyed<HttpMessageHandler>(typeof(PixivImageHttpMessageHandler)), _ = builder.Register(static c => MakoHttpClient.Create(c.ResolveKeyed<HttpMessageHandler>(typeof(PixivImageHttpMessageHandler)),
static client => static client =>
{ {
client.DefaultRequestHeaders.TryAddWithoutValidation("Referer", "https://www.pixiv.net"); _ = client.DefaultRequestHeaders.TryAddWithoutValidation("Referer", "https://www.pixiv.net");
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PixivIOSApp/5.8.7"); _ = client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PixivIOSApp/5.8.7");
})) }))
.Keyed<HttpClient>(MakoApiKind.ImageApi) .Keyed<HttpClient>(MakoApiKind.ImageApi)
.As<HttpClient>() .As<HttpClient>()
.SingleInstance(); .SingleInstance();
builder.Register(static c => MakoHttpOptions.CreateHttpMessageInvoker(c.Resolve<PixivApiNameResolver>())) _ = builder.Register(static c => MakoHttpOptions.CreateHttpMessageInvoker(c.Resolve<PixivApiNameResolver>()))
.Keyed<HttpMessageInvoker>(typeof(PixivApiNameResolver)) .Keyed<HttpMessageInvoker>(typeof(PixivApiNameResolver))
.As<HttpMessageInvoker>() .As<HttpMessageInvoker>()
.SingleInstance(); .SingleInstance();
builder.Register(static c => MakoHttpOptions.CreateHttpMessageInvoker(c.Resolve<PixivImageNameResolver>())) _ = builder.Register(static c => MakoHttpOptions.CreateHttpMessageInvoker(c.Resolve<PixivImageNameResolver>()))
.Keyed<HttpMessageInvoker>(typeof(PixivImageNameResolver)) .Keyed<HttpMessageInvoker>(typeof(PixivImageNameResolver))
.As<HttpMessageInvoker>() .As<HttpMessageInvoker>()
.SingleInstance(); .SingleInstance();
builder.Register(static _ => MakoHttpOptions.CreateDirectHttpMessageInvoker()) _ = builder.Register(static _ => MakoHttpOptions.CreateDirectHttpMessageInvoker())
.Keyed<HttpMessageInvoker>(typeof(LocalMachineNameResolver)) .Keyed<HttpMessageInvoker>(typeof(LocalMachineNameResolver))
.As<HttpMessageInvoker>() .As<HttpMessageInvoker>()
.SingleInstance(); .SingleInstance();
builder.Register(static c => _ = builder.Register(static c =>
{ {
var context = c.Resolve<IComponentContext>(); // or a System.ObjectDisposedException will thrown because the 'c' cannot be hold var context = c.Resolve<IComponentContext>(); // or a System.ObjectDisposedException will thrown because the 'c' cannot be hold
return RestService.For<IAppApiEndPoint>(c.ResolveKeyed<HttpClient>(MakoApiKind.AppApi), new RefitSettings return RestService.For<IAppApiEndPoint>(c.ResolveKeyed<HttpClient>(MakoApiKind.AppApi), new RefitSettings
@ -153,7 +153,7 @@ public partial class MakoClient : ICancellable
}); });
}); });
builder.Register(static c => _ = builder.Register(static c =>
{ {
var context = c.Resolve<IComponentContext>(); // or a System.ObjectDisposedException will thrown because the 'c' cannot be hold var context = c.Resolve<IComponentContext>(); // or a System.ObjectDisposedException will thrown because the 'c' cannot be hold
return RestService.For<IAuthEndPoint>(c.ResolveKeyed<HttpClient>(MakoApiKind.AuthApi), new RefitSettings return RestService.For<IAuthEndPoint>(c.ResolveKeyed<HttpClient>(MakoApiKind.AuthApi), new RefitSettings
@ -162,7 +162,7 @@ public partial class MakoClient : ICancellable
}); });
}); });
builder.Register(static c => _ = builder.Register(static c =>
{ {
var context = c.Resolve<IComponentContext>(); // or a System.ObjectDisposedException will thrown because the 'c' cannot be hold var context = c.Resolve<IComponentContext>(); // or a System.ObjectDisposedException will thrown because the 'c' cannot be hold
return RestService.For<IReverseSearchApiEndPoint>("https://saucenao.com/", new RefitSettings return RestService.For<IReverseSearchApiEndPoint>("https://saucenao.com/", new RefitSettings
@ -225,7 +225,7 @@ public partial class MakoClient : ICancellable
// removes an instance from the running instances list // removes an instance from the running instances list
private void CancelInstance(EngineHandle handle) private void CancelInstance(EngineHandle handle)
{ {
_runningInstances.RemoveAll(instance => instance.EngineHandle == handle); _ = _runningInstances.RemoveAll(instance => instance.EngineHandle == handle);
} }
// PrivacyPolicy.Private is only allowed when the uid is pointing to yourself // PrivacyPolicy.Private is only allowed when the uid is pointing to yourself

View File

@ -113,7 +113,6 @@ public record Illustration : IIllustrate
return other?.Id == Id; return other?.Id == Id;
} }
public class IllustrationMetaSinglePage public class IllustrationMetaSinglePage
{ {
[JsonPropertyName("original_image_url")] [JsonPropertyName("original_image_url")]

View File

@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
namespace Pixeval.CoreApi.Model; namespace Pixeval.CoreApi.Model;
public record TrendingTag(string? Tag, string? Translation, Illustration? Illustration); public record TrendingTag(string? Tag, string? Translation, Illustration? Illustration);

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi #region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval.CoreApi // Pixeval/Pixeval.CoreApi
@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
namespace Pixeval.CoreApi.Net; namespace Pixeval.CoreApi.Net;
/// <summary> /// <summary>

View File

@ -72,7 +72,6 @@ public static class MakoHttpOptions
return new HttpMessageInvoker(new SocketsHttpHandler()); return new HttpMessageInvoker(new SocketsHttpHandler());
} }
private static Func<SocketsHttpConnectionContext, CancellationToken, ValueTask<Stream>> BypassedConnectCallback(INameResolver nameResolver) private static Func<SocketsHttpConnectionContext, CancellationToken, ValueTask<Stream>> BypassedConnectCallback(INameResolver nameResolver)
{ {
return async (context, token) => return async (context, token) =>

View File

@ -41,14 +41,14 @@ internal class PixivApiHttpMessageHandler(MakoClient makoClient) : MakoClientSup
MakoHttpOptions.UseHttpScheme(request); MakoHttpOptions.UseHttpScheme(request);
} }
headers.TryAddWithoutValidation("Accept-Language", MakoClient.Configuration.CultureInfo.Name); _ = headers.TryAddWithoutValidation("Accept-Language", MakoClient.Configuration.CultureInfo.Name);
var session = MakoClient.Session; var session = MakoClient.Session;
switch (host) switch (host)
{ {
case MakoHttpOptions.WebApiHost: case MakoHttpOptions.WebApiHost:
headers.TryAddWithoutValidation("Cookie", session.Cookie); _ = headers.TryAddWithoutValidation("Cookie", session.Cookie);
break; break;
case MakoHttpOptions.AppApiHost: case MakoHttpOptions.AppApiHost:
headers.Authorization = new AuthenticationHeaderValue("Bearer", session.AccessToken); headers.Authorization = new AuthenticationHeaderValue("Bearer", session.AccessToken);

View File

@ -30,7 +30,7 @@ namespace Pixeval.SourceGen;
[Generator] [Generator]
public class SettingsEntryGenerator : IIncrementalGenerator public class SettingsEntryGenerator : IIncrementalGenerator
{ {
private const string SettingPOCOAttributeFqName = "Pixeval.Attributes.SettingPOCO"; private const string SettingPocoAttributeFqName = "Pixeval.Attributes.SettingPoco";
private const string SyntheticSettingAttributeFqName = "Pixeval.Attributes.SyntheticSetting"; private const string SyntheticSettingAttributeFqName = "Pixeval.Attributes.SyntheticSetting";
private const string SettingMetadataAttributeFqName = "Pixeval.Attributes.SettingMetadata"; private const string SettingMetadataAttributeFqName = "Pixeval.Attributes.SettingMetadata";
private const string SettingEntryFqName = "global::Pixeval.SettingEntry"; private const string SettingEntryFqName = "global::Pixeval.SettingEntry";
@ -42,7 +42,7 @@ public class SettingsEntryGenerator : IIncrementalGenerator
transform: static (ctx, _) => transform: static (ctx, _) =>
{ {
var tds = (TypeDeclarationSyntax)ctx.Node; var tds = (TypeDeclarationSyntax)ctx.Node;
(TypeDeclarationSyntax, IEnumerable<(PropertyDeclarationSyntax, AttributeSyntax?)>)? tuple = tds.HasAttribute(ctx.SemanticModel, SettingPOCOAttributeFqName) (TypeDeclarationSyntax, IEnumerable<(PropertyDeclarationSyntax, AttributeSyntax?)>)? tuple = tds.HasAttribute(ctx.SemanticModel, SettingPocoAttributeFqName)
? (tds, tds.Members.OfType<PropertyDeclarationSyntax>().Where(pds => !pds.HasAttribute(ctx.SemanticModel, SyntheticSettingAttributeFqName) && pds.HasAttribute(ctx.SemanticModel, SettingMetadataAttributeFqName)) ? (tds, tds.Members.OfType<PropertyDeclarationSyntax>().Where(pds => !pds.HasAttribute(ctx.SemanticModel, SyntheticSettingAttributeFqName) && pds.HasAttribute(ctx.SemanticModel, SettingMetadataAttributeFqName))
.Select(property => (property, property.GetAttribute(ctx.SemanticModel, SettingMetadataAttributeFqName))) .Select(property => (property, property.GetAttribute(ctx.SemanticModel, SettingMetadataAttributeFqName)))
.Where(tuple => tuple.Item2 is not null)) .Where(tuple => tuple.Item2 is not null))
@ -96,8 +96,8 @@ public class SettingsEntryGenerator : IIncrementalGenerator
ctx.ReportDiagnostic( ctx.ReportDiagnostic(
Diagnostic.Create(new DiagnosticDescriptor( Diagnostic.Create(new DiagnosticDescriptor(
"PSG0001", "PSG0001",
"There should be only one [SettingPOCO] in an assembly", "There should be only one [SettingPoco] in an assembly",
"There should be only one [SettingPOCO] in an assembly", "There should be only one [SettingPoco] in an assembly",
"SourceGen", "SourceGen",
DiagnosticSeverity.Error, DiagnosticSeverity.Error,
true), typeDeclarationSyntax.GetLocation())); true), typeDeclarationSyntax.GetLocation()));

View File

@ -137,14 +137,14 @@ public static class Enumerates
public static T? FirstOrNull<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate) where T : struct public static T? FirstOrNull<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate) where T : struct
{ {
var matches = enumerable.Where(predicate).Take(1).ToArray(); var matches = enumerable.Where(predicate).Take(1).ToArray();
return matches.Any() ? matches[0] : null; return matches.Length is 0 ? null : matches[0];
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T? FirstOrNull<T>(this IEnumerable<T> enumerable) where T : struct public static T? FirstOrNull<T>(this IEnumerable<T> enumerable) where T : struct
{ {
var matches = enumerable.Take(1).ToArray(); var matches = enumerable.Take(1).ToArray();
return matches.Any() ? matches[0] : null; return matches.Length is 0 ? null : matches[0];
} }
public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<T> source) public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<T> source)
@ -183,7 +183,7 @@ public static class Enumerates
public static void ReplaceByUpdate<T>(this IList<T> dest, IEnumerable<T> source) public static void ReplaceByUpdate<T>(this IList<T> dest, IEnumerable<T> source)
{ {
var enumerable = source as T[] ?? source.ToArray(); var enumerable = source as T[] ?? source.ToArray();
if (enumerable.Any()) if (enumerable.Length != 0)
{ {
_ = dest.RemoveAll(x => !enumerable.Contains(x)); _ = dest.RemoveAll(x => !enumerable.Contains(x));
enumerable.Where(x => !dest.Contains(x)).ForEach(dest.Add); enumerable.Where(x => !dest.Contains(x)).ForEach(dest.Add);
@ -197,7 +197,7 @@ public static class Enumerates
public static void ReplaceByUpdate<T>(this ISet<T> dest, IEnumerable<T> source) public static void ReplaceByUpdate<T>(this ISet<T> dest, IEnumerable<T> source)
{ {
var enumerable = source as T[] ?? source.ToArray(); var enumerable = source as T[] ?? source.ToArray();
if (enumerable.Any()) if (enumerable.Length != 0)
{ {
dest.ToArray().Where(x => !enumerable.Contains(x)).ForEach(x => dest.Remove(x)); dest.ToArray().Where(x => !enumerable.Contains(x)).ForEach(x => dest.Remove(x));
dest.AddRange(enumerable); dest.AddRange(enumerable);

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.Utilities #region Copyright (c) Pixeval/Pixeval.Utilities
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval.Utilities // Pixeval/Pixeval.Utilities
@ -117,7 +117,7 @@ public class ObservableHashSet<T>
void ICollection<T>.Add(T item) void ICollection<T>.Add(T item)
{ {
Add(item); _ = Add(item);
} }
/// <summary> /// <summary>
@ -183,7 +183,7 @@ public class ObservableHashSet<T>
OnCountPropertyChanging(); OnCountPropertyChanging();
_set.Remove(item); _ = _set.Remove(item);
OnCollectionChanged(NotifyCollectionChangedAction.Remove, item); OnCollectionChanged(NotifyCollectionChangedAction.Remove, item);
@ -233,7 +233,7 @@ public class ObservableHashSet<T>
OnCountPropertyChanging(); OnCountPropertyChanging();
_set.Add(item); _ = _set.Add(item);
OnCollectionChanged(NotifyCollectionChangedAction.Add, item); OnCollectionChanged(NotifyCollectionChangedAction.Add, item);
@ -555,5 +555,5 @@ internal static class ObservableHashSetSingletons
public static readonly PropertyChangedEventArgs CountPropertyChanged = new("Count"); public static readonly PropertyChangedEventArgs CountPropertyChanged = new("Count");
public static readonly PropertyChangingEventArgs CountPropertyChanging = new("Count"); public static readonly PropertyChangingEventArgs CountPropertyChanging = new("Count");
public static readonly object[] NoItems = Array.Empty<object>(); public static readonly object[] NoItems = [];
} }

View File

@ -5,7 +5,7 @@ namespace Pixeval.Utilities;
public class SharedRef<T> public class SharedRef<T>
{ {
private readonly HashSet<object> _keys = new(); private readonly HashSet<object> _keys = [];
public T Value { get; init; } public T Value { get; init; }

View File

@ -48,7 +48,7 @@ public class CancellationHandle
if (!IsCancelled) if (!IsCancelled)
{ {
_onCancellation?.Invoke(); _onCancellation?.Invoke();
Interlocked.Increment(ref _isCancelled); _ = Interlocked.Increment(ref _isCancelled);
} }
} }
@ -56,12 +56,12 @@ public class CancellationHandle
{ {
if (IsPaused) if (IsPaused)
{ {
Interlocked.Decrement(ref _paused); _ = Interlocked.Decrement(ref _paused);
} }
if (IsCancelled) if (IsCancelled)
{ {
Interlocked.Decrement(ref _isCancelled); _ = Interlocked.Decrement(ref _isCancelled);
} }
} }
@ -70,7 +70,7 @@ public class CancellationHandle
if (!IsPaused) if (!IsPaused)
{ {
_onPause?.Invoke(); _onPause?.Invoke();
Interlocked.Increment(ref _paused); _ = Interlocked.Increment(ref _paused);
} }
} }
@ -79,7 +79,7 @@ public class CancellationHandle
if (IsPaused) if (IsPaused)
{ {
_onResume?.Invoke(); _onResume?.Invoke();
Interlocked.Decrement(ref _paused); _ = Interlocked.Decrement(ref _paused);
} }
} }

View File

@ -93,7 +93,7 @@ public class ReenterableAwaiter(bool initialSignal) : INotifyCompletion
} }
else else
{ {
Task.Factory.StartNew(_continuation, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); _ = Task.Factory.StartNew(_continuation, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
} }
} }

View File

@ -97,7 +97,7 @@ public class ReenterableAwaiter<TResult>(bool initialSignal, TResult resultIniti
} }
else else
{ {
Task.Factory.StartNew(_continuation, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); _ = Task.Factory.StartNew(_continuation, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
} }
} }

View File

@ -27,7 +27,7 @@ namespace Pixeval.Activation;
public static class ActivationRegistrar public static class ActivationRegistrar
{ {
public static readonly List<IAppActivationHandler> FeatureHandlers = new(); public static readonly List<IAppActivationHandler> FeatureHandlers = [];
static ActivationRegistrar() static ActivationRegistrar()
{ {
@ -39,7 +39,7 @@ public static class ActivationRegistrar
if (args is { Kind: ExtendedActivationKind.Protocol, Data: IProtocolActivatedEventArgs { Uri: var activationUri } } && if (args is { Kind: ExtendedActivationKind.Protocol, Data: IProtocolActivatedEventArgs { Uri: var activationUri } } &&
FeatureHandlers.FirstOrDefault(f => f.ActivationFragment == activationUri.Host) is { } handler) FeatureHandlers.FirstOrDefault(f => f.ActivationFragment == activationUri.Host) is { } handler)
{ {
handler.Execute(activationUri.PathAndQuery[1..]); _ = handler.Execute(activationUri.PathAndQuery[1..]);
} }
} }
} }

View File

@ -83,7 +83,7 @@ public partial class App
public static void ExitWithPushNotification() public static void ExitWithPushNotification()
{ {
WeakReferenceMessenger.Default.Send(new ApplicationExitingMessage()); _ = WeakReferenceMessenger.Default.Send(new ApplicationExitingMessage());
CurrentContext.App.Exit(); CurrentContext.App.Exit();
} }
} }

View File

@ -56,7 +56,7 @@ public static partial class AppContext
public static readonly string AppVersion = GitVersionInformation.AssemblySemVer; public static readonly string AppVersion = GitVersionInformation.AssemblySemVer;
private static readonly ApplicationDataContainer SessionContainer; private static readonly ApplicationDataContainer _sessionContainer;
private static SoftwareBitmapSource? _imageNotAvailable; private static SoftwareBitmapSource? _imageNotAvailable;
@ -70,14 +70,14 @@ public static partial class AppContext
{ {
if (!ApplicationData.Current.LocalSettings.Containers.ContainsKey(SessionContainerKey)) if (!ApplicationData.Current.LocalSettings.Containers.ContainsKey(SessionContainerKey))
{ {
ApplicationData.Current.LocalSettings.CreateContainer(SessionContainerKey, ApplicationDataCreateDisposition.Always); _ = ApplicationData.Current.LocalSettings.CreateContainer(SessionContainerKey, ApplicationDataCreateDisposition.Always);
} }
// Keys in the RoamingSettings will be synced through the devices of the same user // Keys in the RoamingSettings will be synced through the devices of the same user
// For more detailed information see https://docs.microsoft.com/en-us/windows/apps/design/app-settings/store-and-retrieve-app-data // For more detailed information see https://docs.microsoft.com/en-us/windows/apps/design/app-settings/store-and-retrieve-app-data
InitializeConfigurationContainer(); InitializeConfigurationContainer();
SessionContainer = ApplicationData.Current.LocalSettings.Containers[SessionContainerKey]; _sessionContainer = ApplicationData.Current.LocalSettings.Containers[SessionContainerKey];
} }
public static async Task<SoftwareBitmapSource> GetNotAvailableImageAsync() public static async Task<SoftwareBitmapSource> GetNotAvailableImageAsync()
@ -160,7 +160,7 @@ public static partial class AppContext
using var scope = App.AppViewModel.AppServicesScope; using var scope = App.AppViewModel.AppServicesScope;
var downloadHistoryManager = scope.ServiceProvider.GetRequiredService<DownloadHistoryPersistentManager>(); var downloadHistoryManager = scope.ServiceProvider.GetRequiredService<DownloadHistoryPersistentManager>();
// the HasFlag is not allow in expression tree // the HasFlag is not allow in expression tree
downloadHistoryManager.Delete(entry => entry.State == DownloadState.Running || _ = downloadHistoryManager.Delete(entry => entry.State == DownloadState.Running ||
entry.State == DownloadState.Queued || entry.State == DownloadState.Queued ||
entry.State == DownloadState.Created || entry.State == DownloadState.Created ||
entry.State == DownloadState.Paused); entry.State == DownloadState.Paused);
@ -201,7 +201,7 @@ public static partial class AppContext
{ {
if (App.AppViewModel.MakoClient.Session is { } session) if (App.AppViewModel.MakoClient.Session is { } session)
{ {
var values = SessionContainer.Values; var values = _sessionContainer.Values;
values[nameof(Session.AccessToken)] = session.AccessToken; values[nameof(Session.AccessToken)] = session.AccessToken;
values[nameof(Session.Account)] = session.Account; values[nameof(Session.Account)] = session.Account;
values[nameof(Session.AvatarUrl)] = session.AvatarUrl; values[nameof(Session.AvatarUrl)] = session.AvatarUrl;
@ -219,7 +219,7 @@ public static partial class AppContext
{ {
try try
{ {
var values = SessionContainer.Values; var values = _sessionContainer.Values;
return new Session return new Session
{ {
AccessToken = values[nameof(Session.AccessToken)].CastOrThrow<string>(), AccessToken = values[nameof(Session.AccessToken)].CastOrThrow<string>(),

View File

@ -33,7 +33,7 @@ using WinUI3Utilities.Attributes;
namespace Pixeval.AppManagement; namespace Pixeval.AppManagement;
[GenerateConstructor, SettingPOCO] [GenerateConstructor, SettingPoco]
public partial record AppSetting : IWindowSettings public partial record AppSetting : IWindowSettings
{ {
#pragma warning disable CS8618 #pragma warning disable CS8618

View File

@ -88,7 +88,7 @@ public class AppViewModel(App app) : AutoActivateObservableRecipient, IRecipient
public async Task ShowExceptionDialogAsync(Exception e) public async Task ShowExceptionDialogAsync(Exception e)
{ {
await MessageDialogBuilder.CreateAcknowledgement(CurrentContext.Window, MiscResources.ExceptionEncountered, e.ToString()).ShowAsync(); _ = await MessageDialogBuilder.CreateAcknowledgement(CurrentContext.Window, MiscResources.ExceptionEncountered, e.ToString()).ShowAsync();
} }
public async Task InitializeAsync(bool activatedByProtocol) public async Task InitializeAsync(bool activatedByProtocol)

View File

@ -22,7 +22,6 @@ using System;
using System.Reflection; using System.Reflection;
using Pixeval.Misc; using Pixeval.Misc;
namespace Pixeval.Attributes; namespace Pixeval.Attributes;
[AttributeUsage(AttributeTargets.Property)] [AttributeUsage(AttributeTargets.Property)]

View File

@ -22,4 +22,4 @@ using System;
namespace Pixeval.Attributes; namespace Pixeval.Attributes;
public class SettingPOCO : Attribute { } public class SettingPoco : Attribute { }

View File

@ -24,7 +24,6 @@ using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media;
using WinUI3Utilities.Attributes; using WinUI3Utilities.Attributes;
namespace Pixeval.Controls.IllustratorView; namespace Pixeval.Controls.IllustratorView;
[TemplatePart(Name = PartContentContainer, Type = typeof(CardControl))] [TemplatePart(Name = PartContentContainer, Type = typeof(CardControl))]

View File

@ -73,7 +73,7 @@ public partial class IllustratorViewModel : ObservableObject, IIllustrationVisua
Account = info.Account; Account = info.Account;
Comment = info.Comment; Comment = info.Comment;
IsFollowed = info.IsFollowed; IsFollowed = info.IsFollowed;
Illustrations = new ObservableCollection<IllustrationViewModel>(); Illustrations = [];
VisualizationController = new IllustrationVisualizationController(this); VisualizationController = new IllustrationVisualizationController(this);
IsFollowButtonEnabled = true; IsFollowButtonEnabled = true;
_ = LoadAvatar(); _ = LoadAvatar();
@ -81,7 +81,8 @@ public partial class IllustratorViewModel : ObservableObject, IIllustrationVisua
public async Task LoadAvatar() public async Task LoadAvatar()
{ {
if (AvatarSource != null) return; if (AvatarSource != null)
return;
AvatarSource = (await App.AppViewModel.MakoClient.DownloadBitmapImageResultAsync(AvatarUrl, 60) AvatarSource = (await App.AppViewModel.MakoClient.DownloadBitmapImageResultAsync(AvatarUrl, 60)
.GetOrElseAsync(await AppContext.GetPixivNoProfileImageAsync()))!; .GetOrElseAsync(await AppContext.GetPixivNoProfileImageAsync()))!;
} }

View File

@ -29,7 +29,6 @@ public partial class DownloadHistoryEntry : ObservableObject
[ObservableProperty] [ObservableProperty]
private string? _errorCause; private string? _errorCause;
[ObservableProperty] [ObservableProperty]
private DownloadState _state; private DownloadState _state;

View File

@ -42,12 +42,12 @@ public class DownloadHistoryPersistentManager(ILiteDatabase collection, int maxi
Purge(MaximumRecords); Purge(MaximumRecords);
} }
Collection.Insert(t); _ = Collection.Insert(t);
t.PropertyChanged += (_, _) => t.PropertyChanged += (_, _) =>
{ {
if (Collection.Find(entry => entry.Destination == t.Destination).Any()) if (Collection.Find(entry => entry.Destination == t.Destination).Any())
{ {
Collection.Update(t); _ = Collection.Update(t);
} }
}; };
} }
@ -88,13 +88,13 @@ public class DownloadHistoryPersistentManager(ILiteDatabase collection, int maxi
if (Collection.Count() > limit) if (Collection.Count() > limit)
{ {
var last = Collection.FindAll().Take(^limit..).Select(e => e.Destination).ToHashSet(); var last = Collection.FindAll().Take(^limit..).Select(e => e.Destination).ToHashSet();
Delete(e => !last.Contains(e.Destination!)); _ = Delete(e => !last.Contains(e.Destination!));
} }
} }
public void Clear() public void Clear()
{ {
Collection.DeleteAll(); _ = Collection.DeleteAll();
App.AppViewModel.DownloadManager.ClearTasks(); App.AppViewModel.DownloadManager.ClearTasks();
} }

View File

@ -45,7 +45,6 @@ public interface IPersistentManager<TEntry, out TModel> where TEntry : new()
int MaximumRecords { get; set; } int MaximumRecords { get; set; }
int Count { get; } int Count { get; }
void Insert(TEntry t); void Insert(TEntry t);

View File

@ -47,7 +47,7 @@ public abstract class SimplePersistentManager<T>(ILiteDatabase db, int maximumRe
Purge(MaximumRecords); Purge(MaximumRecords);
} }
Collection.Insert(t); _ = Collection.Insert(t);
} }
public IEnumerable<T> Query(Expression<Func<T, bool>> predicate) public IEnumerable<T> Query(Expression<Func<T, bool>> predicate)
@ -86,12 +86,12 @@ public abstract class SimplePersistentManager<T>(ILiteDatabase db, int maximumRe
if (Collection.Count() > limit) if (Collection.Count() > limit)
{ {
var last = Collection.FindAll().Take(^limit..).ToHashSet(); var last = Collection.FindAll().Take(^limit..).ToHashSet();
Delete(e => !last.Contains(e!)); _ = Delete(e => !last.Contains(e!));
} }
} }
public void Clear() public void Clear()
{ {
Collection.DeleteAll(); _ = Collection.DeleteAll();
} }
} }

View File

@ -20,7 +20,6 @@
using WinUI3Utilities.Attributes; using WinUI3Utilities.Attributes;
namespace Pixeval.Dialogs; namespace Pixeval.Dialogs;
[DependencyProperty<bool>("DeleteLocalFiles", "false")] [DependencyProperty<bool>("DeleteLocalFiles", "false")]

View File

@ -43,6 +43,6 @@ public sealed partial class ReverseSearchApiKeyNotPresentDialog
private void SetApiKeyHyperlinkButton_OnTapped(object sender, TappedRoutedEventArgs e) private void SetApiKeyHyperlinkButton_OnTapped(object sender, TappedRoutedEventArgs e)
{ {
Owner?.Hide(); Owner?.Hide();
WeakReferenceMessenger.Default.Send(new NavigateToSettingEntryMessage(SettingEntry.ReverseSearchApiKey)); _ = WeakReferenceMessenger.Default.Send(new NavigateToSettingEntryMessage(SettingEntry.ReverseSearchApiKey));
} }
} }

View File

@ -59,8 +59,8 @@ public class AnimatedIllustrationDownloadTask : ObservableDownloadTask, ICustomB
{ {
using (stream) using (stream)
{ {
using var ugoiraStream = await IOHelper.GetStreamFromZipStreamAsync(stream.AsStreamForRead(), _metadata); using var ugoiraStream = await IoHelper.GetStreamFromZipStreamAsync(stream.AsStreamForRead(), _metadata);
await IOHelper.CreateAndWriteToFileAsync(ugoiraStream, Destination); await IoHelper.CreateAndWriteToFileAsync(ugoiraStream, Destination);
} }
} }

View File

@ -51,7 +51,7 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
public DownloadManager(int concurrencyDegree, HttpClient? httpClient = null) public DownloadManager(int concurrencyDegree, HttpClient? httpClient = null)
{ {
_httpClient = httpClient ?? new HttpClient(); _httpClient = httpClient ?? new HttpClient();
_queuedTasks = new(); _queuedTasks = [];
_taskQuerySet = new HashSet<TDownloadTask>(); _taskQuerySet = new HashSet<TDownloadTask>();
_throttle = new(true, true); _throttle = new(true, true);
_downloadTaskChannel = Channel.CreateUnbounded<TDownloadTask>(); _downloadTaskChannel = Channel.CreateUnbounded<TDownloadTask>();
@ -79,7 +79,7 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
return; return;
} }
_taskQuerySet.Add(task); _ = _taskQuerySet.Add(task);
_queuedTasks.Add(task); _queuedTasks.Add(task);
// Start the task only if it is created and is ready-to-run // Start the task only if it is created and is ready-to-run
if (task.CurrentState == DownloadState.Created) if (task.CurrentState == DownloadState.Created)
@ -102,8 +102,8 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
public void RemoveTask(TDownloadTask task) public void RemoveTask(TDownloadTask task)
{ {
_taskQuerySet.Remove(task); _ = _taskQuerySet.Remove(task);
_queuedTasks.Remove(task); _ = _queuedTasks.Remove(task);
} }
public void ClearTasks() public void ClearTasks()
@ -134,7 +134,7 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
private void QueueDownloadTask(TDownloadTask task) private void QueueDownloadTask(TDownloadTask task)
{ {
_downloadTaskChannel.Writer.WriteAsync(task); _ = _downloadTaskChannel.Writer.WriteAsync(task);
} }
private async Task Download(TDownloadTask task) private async Task Download(TDownloadTask task)
@ -161,10 +161,10 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
private async Task DecrementCounterAsync() private async Task DecrementCounterAsync()
{ {
Interlocked.Decrement(ref _workingTasks); _ = Interlocked.Decrement(ref _workingTasks);
await _semaphoreSlim.WaitAsync(); await _semaphoreSlim.WaitAsync();
_throttle.SetResult(true); _throttle.SetResult(true);
_semaphoreSlim.Release(); _ = _semaphoreSlim.Release();
} }
private async Task DownloadInternal(TDownloadTask task) private async Task DownloadInternal(TDownloadTask task)
@ -187,7 +187,7 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
{ {
using (resultStream) using (resultStream)
{ {
await IOHelper.CreateAndWriteToFileAsync(resultStream, task.Destination); await IoHelper.CreateAndWriteToFileAsync(resultStream, task.Destination);
} }
} }
} }
@ -204,7 +204,7 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
break; break;
case Result<IRandomAccessStream>.Failure(var exception): case Result<IRandomAccessStream>.Failure(var exception):
Functions.IgnoreException(() => File.Delete(task.Destination)); Functions.IgnoreException(() => File.Delete(task.Destination));
if (exception is not OperationCanceledException && exception is not null) if (exception is not OperationCanceledException and not null)
{ {
ThreadingHelper.DispatchTask(() => task.ErrorCause = exception); ThreadingHelper.DispatchTask(() => task.ErrorCause = exception);
SetState(task, DownloadState.Error); SetState(task, DownloadState.Error);

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval #region Copyright (c) Pixeval/Pixeval
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval // Pixeval/Pixeval
@ -19,7 +19,6 @@
#endregion #endregion
using System; using System;
using System.Runtime.Serialization;
namespace Pixeval.Download; namespace Pixeval.Download;
@ -29,10 +28,6 @@ public class DownloadTaskInitializationException : Exception
{ {
} }
protected DownloadTaskInitializationException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public DownloadTaskInitializationException(string? message) : base(message) public DownloadTaskInitializationException(string? message) : base(message)
{ {
} }

View File

@ -64,7 +64,7 @@ public class IllustrationDownloadTask : ObservableDownloadTask, IIllustrationVie
{ {
using (stream) using (stream)
{ {
IOHelper.CreateParentDirectories(Destination); IoHelper.CreateParentDirectories(Destination);
await using var fs = File.Open(Destination, FileMode.Create, FileAccess.ReadWrite, FileShare.None); await using var fs = File.Open(Destination, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
await stream.AsStreamForRead().CopyToAsync(fs); await stream.AsStreamForRead().CopyToAsync(fs);
} }

View File

@ -41,11 +41,11 @@ public class IllustrationDownloadTaskFactory : IDownloadTaskFactory<Illustration
{ {
using var scope = App.AppViewModel.AppServicesScope; using var scope = App.AppViewModel.AppServicesScope;
var manager = scope.ServiceProvider.GetRequiredService<DownloadHistoryPersistentManager>(); var manager = scope.ServiceProvider.GetRequiredService<DownloadHistoryPersistentManager>();
var path = IOHelper.NormalizePath(PathParser.Reduce(rawPath, context)); var path = IoHelper.NormalizePath(PathParser.Reduce(rawPath, context));
if (manager.Collection.Find(entry => entry.Destination == path).Any()) if (manager.Collection.Find(entry => entry.Destination == path).Any())
{ {
// delete the original entry // delete the original entry
manager.Delete(entry => entry.Destination == path); _ = manager.Delete(entry => entry.Destination == path);
} }
var task = Functions.Block<ObservableDownloadTask>(() => var task = Functions.Block<ObservableDownloadTask>(() =>

View File

@ -25,22 +25,16 @@ using Pixeval.UserControls.IllustrationView;
namespace Pixeval.Download; namespace Pixeval.Download;
public class IntrinsicIllustrationDownloadTask : IllustrationDownloadTask, IIntrinsicDownloadTask /// <summary>
/// The disposal of <paramref name="imageStream" /> is not handled
/// </summary>
public class IntrinsicIllustrationDownloadTask(DownloadHistoryEntry entry, IllustrationViewModel illustrationViewModel, IRandomAccessStream imageStream) : IllustrationDownloadTask(entry, illustrationViewModel), IIntrinsicDownloadTask
{ {
/// <summary> public IRandomAccessStream Stream { get; } = imageStream;
/// The disposal of <paramref name="imageStream" /> is not handled
/// </summary>
public IntrinsicIllustrationDownloadTask(DownloadHistoryEntry entry, IllustrationViewModel illustrationViewModel, IRandomAccessStream imageStream)
: base(entry, illustrationViewModel)
{
Stream = imageStream;
}
public IRandomAccessStream Stream { get; }
public override async void DownloadStarting(DownloadStartingEventArgs args) public override async void DownloadStarting(DownloadStartingEventArgs args)
{ {
args.GetDeferral().Complete(false); args.GetDeferral().Complete(false);
await IOHelper.CreateAndWriteToFileAsync(Stream, Destination); await IoHelper.CreateAndWriteToFileAsync(Stream, Destination);
} }
} }

View File

@ -45,8 +45,8 @@ public class LazyInitializedAnimatedIllustrationDownloadTask : AnimatedIllustrat
using (stream) using (stream)
{ {
var metadata = await App.AppViewModel.MakoClient.GetUgoiraMetadataAsync(_illustId); var metadata = await App.AppViewModel.MakoClient.GetUgoiraMetadataAsync(_illustId);
using var ugoiraStream = await IOHelper.GetStreamFromZipStreamAsync(stream.AsStreamForRead(), metadata); using var ugoiraStream = await IoHelper.GetStreamFromZipStreamAsync(stream.AsStreamForRead(), metadata);
await IOHelper.CreateAndWriteToFileAsync(ugoiraStream, Destination); await IoHelper.CreateAndWriteToFileAsync(ugoiraStream, Destination);
} }
} }

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval #region Copyright (c) Pixeval/Pixeval
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval // Pixeval/Pixeval
@ -29,30 +29,30 @@ namespace Pixeval.Download.MacroParser;
public class CharStream : ISeekable<char> public class CharStream : ISeekable<char>
{ {
private readonly Stack<int> markers = new(); private readonly Stack<int> _markers = new();
private readonly string text; private readonly string _text;
private char[] stream; private char[] _stream;
public CharStream(string text) public CharStream(string text)
{ {
stream = text.ToCharArray(); _stream = text.ToCharArray();
this.text = text; this._text = text;
markers.Push(0); _markers.Push(0);
} }
public int Forward { get; private set; } public int Forward { get; private set; }
public void Seek(int pos) public void Seek(int pos)
{ {
markers.Pop(); _ = _markers.Pop();
markers.Push(pos); _markers.Push(pos);
Forward = pos; Forward = pos;
} }
public char Peek() public char Peek()
{ {
return Forward >= stream.Length ? char.MaxValue : stream[Forward]; return Forward >= _stream.Length ? char.MaxValue : _stream[Forward];
} }
public void Advance() public void Advance()
@ -67,18 +67,18 @@ public class CharStream : ISeekable<char>
public char[] GetWindow() public char[] GetWindow()
{ {
return stream[markers.Peek()..Forward]; return _stream[_markers.Peek()..Forward];
} }
public void AdvanceMarker() public void AdvanceMarker()
{ {
markers.Pop(); _ = _markers.Pop();
markers.Push(Forward); _markers.Push(Forward);
} }
public void ResetForward() public void ResetForward()
{ {
Forward = markers.Peek(); Forward = _markers.Peek();
} }
public void Return() public void Return()
@ -94,25 +94,25 @@ public class CharStream : ISeekable<char>
public LineInfo GetCurrentLineInfo() public LineInfo GetCurrentLineInfo()
{ {
if (Forward >= text.Length) if (Forward >= _text.Length)
{ {
return LineInfo.Eof; return LineInfo.Eof;
} }
var lines = text[..Forward].Split(Environment.NewLine); var lines = _text[..Forward].Split(Environment.NewLine);
return new LineInfo(lines.Length, lines[^1].Length); return new LineInfo(lines.Length, lines[^1].Length);
} }
public void Replace(char[] newStream) public void Replace(char[] newStream)
{ {
stream = newStream; _stream = newStream;
Forward = 0; Forward = 0;
if (markers.Any()) if (_markers.Any())
{ {
markers.Clear(); _markers.Clear();
} }
markers.Push(0); _markers.Push(0);
} }
public char NextChar() public char NextChar()
@ -124,7 +124,7 @@ public class CharStream : ISeekable<char>
public string GetWindowString() public string GetWindowString()
{ {
return new string(stream[markers.Peek()..Forward]); return new string(_stream[_markers.Peek()..Forward]);
} }
public void Return(int count) public void Return(int count)
@ -201,12 +201,12 @@ public class CharStream : ISeekable<char>
public void PushMarker() public void PushMarker()
{ {
markers.Push(Forward); _markers.Push(Forward);
} }
public int PopMarker() public int PopMarker()
{ {
return markers.Pop(); return _markers.Pop();
} }
public string GetUntilIfAndReturn(Func<char, bool> func) public string GetUntilIfAndReturn(Func<char, bool> func)

View File

@ -24,11 +24,11 @@ public class Lexer(string rawString)
{ {
private readonly CharStream _rawString = new(rawString); private readonly CharStream _rawString = new(rawString);
private char _currentChar => _rawString.Peek(); private char CurrentChar => _rawString.Peek();
public TokenInfo? NextToken() public TokenInfo? NextToken()
{ {
switch (_currentChar) switch (CurrentChar)
{ {
case char.MaxValue: case char.MaxValue:
return null; return null;

View File

@ -104,12 +104,12 @@ public class MacroParser<TContext>
private Macro<TContext> Macro() private Macro<TContext> Macro()
{ {
EatToken(TokenKind.At); _ = EatToken(TokenKind.At);
EatToken(TokenKind.LBrace); _ = EatToken(TokenKind.LBrace);
var macroName = PlainText(); var macroName = PlainText();
_expectContextualColon = true; _expectContextualColon = true;
var node = new Macro<TContext>(macroName, OptionalMacroParameter()); var node = new Macro<TContext>(macroName, OptionalMacroParameter());
EatToken(TokenKind.RBrace); _ = EatToken(TokenKind.RBrace);
return node; return node;
} }
@ -128,7 +128,7 @@ public class MacroParser<TContext>
throw new MacroParseException(MacroParserResources.UnexpectedTokenFormatted.Format(_currentToken.Position.Start)); throw new MacroParseException(MacroParserResources.UnexpectedTokenFormatted.Format(_currentToken.Position.Start));
} }
EatToken(TokenKind.Colon); _ = EatToken(TokenKind.Colon);
return new PlainText<TContext>($":{EatToken(TokenKind.PlainText).Text}"); return new PlainText<TContext>($":{EatToken(TokenKind.PlainText).Text}");
} }

View File

@ -32,6 +32,6 @@ public class IllustrationTitleMacro : IMacro<IllustrationViewModel>.ITransducer
public string Substitute(IllustrationViewModel context) public string Substitute(IllustrationViewModel context)
{ {
return context.Illustrate.Title?.Let(IOHelper.NormalizePathSegment) ?? MacroParserResources.UnknownIllustrationTitle; return context.Illustrate.Title?.Let(IoHelper.NormalizePathSegment) ?? MacroParserResources.UnknownIllustrationTitle;
} }
} }

View File

@ -32,6 +32,6 @@ public class IllustratorNameMacro : IMacro<IllustrationViewModel>.ITransducer
public string Substitute(IllustrationViewModel context) public string Substitute(IllustrationViewModel context)
{ {
return context.Illustrate.User?.Name?.Let(IOHelper.NormalizePathSegment) ?? MacroParserResources.UnknownArtist; return context.Illustrate.User?.Name?.Let(IoHelper.NormalizePathSegment) ?? MacroParserResources.UnknownArtist;
} }
} }

View File

@ -32,6 +32,6 @@ public class SpotlightTitleMacro : IMacro<IllustrationViewModel>.ITransducer
public string Substitute(IllustrationViewModel context) public string Substitute(IllustrationViewModel context)
{ {
return context.Illustrate.SpotlightTitle?.Let(IOHelper.NormalizePathSegment) ?? MacroParserResources.UnknownSpotlightTitle; return context.Illustrate.SpotlightTitle?.Let(IoHelper.NormalizePathSegment) ?? MacroParserResources.UnknownSpotlightTitle;
} }
} }

View File

@ -60,7 +60,7 @@ public sealed partial class CommentRepliesBlock
private void CommentList_OnRepliesHyperlinkButtonTapped(object? sender, TappedRoutedEventArgs e) private void CommentList_OnRepliesHyperlinkButtonTapped(object? sender, TappedRoutedEventArgs e)
{ {
ReplyBar.FindDescendant<RichEditBox>()?.Focus(FocusState.Programmatic); _ = (ReplyBar.FindDescendant<RichEditBox>()?.Focus(FocusState.Programmatic));
} }
private async void ReplyBar_OnSendButtonTapped(object? sender, SendButtonTappedEventArgs e) private async void ReplyBar_OnSendButtonTapped(object? sender, SendButtonTappedEventArgs e)

View File

@ -44,6 +44,6 @@ public sealed partial class LoginWebView
private async void LoginWebView_OnCoreWebView2Initialized(WebView2 sender, CoreWebView2InitializedEventArgs args) private async void LoginWebView_OnCoreWebView2Initialized(WebView2 sender, CoreWebView2InitializedEventArgs args)
{ {
await LoginWebView2.CoreWebView2.CallDevToolsProtocolMethodAsync("Security.setIgnoreCertificateErrors", "{ \"ignore\": true }"); _ = await LoginWebView2.CoreWebView2.CallDevToolsProtocolMethodAsync("Security.setIgnoreCertificateErrors", "{ \"ignore\": true }");
} }
} }

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval #region Copyright (c) Pixeval/Pixeval
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval // Pixeval/Pixeval
@ -19,7 +19,6 @@
#endregion #endregion
using System; using System;
using System.Runtime.Serialization;
namespace Pixeval; namespace Pixeval;
@ -29,10 +28,6 @@ public class IllustrationSourceNotFoundException : Exception
{ {
} }
protected IllustrationSourceNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public IllustrationSourceNotFoundException(string? message) : base(message) public IllustrationSourceNotFoundException(string? message) : base(message)
{ {
} }

View File

@ -20,13 +20,14 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
namespace Pixeval.Interop; namespace Pixeval.Interop;
[ComImport] [GeneratedComInterface]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("3A3DCD6C-3EAB-43DC-BCDE-45671CE800C8")] [Guid("3A3DCD6C-3EAB-43DC-BCDE-45671CE800C8")]
public interface IDataTransferManagerInterop public partial interface IDataTransferManagerInterop
{ {
unsafe void GetForWindow(nint appWindow, Guid* riId, [Optional] void** dataTransferManager); unsafe void GetForWindow(nint appWindow, Guid* riId, [Optional] void** dataTransferManager);

View File

@ -19,6 +19,7 @@
#endregion #endregion
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
namespace Pixeval.Interop; namespace Pixeval.Interop;
@ -32,10 +33,10 @@ public enum TaskBarState
Paused = 1 << 3 Paused = 1 << 3
} }
[ComImport] [GeneratedComInterface]
[Guid("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")] [Guid("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ITaskBarList3 public partial interface ITaskBarList3
{ {
[PreserveSig] [PreserveSig]
void HrInit(); void HrInit();

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval #region Copyright (c) Pixeval/Pixeval
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval // Pixeval/Pixeval
@ -32,10 +32,6 @@ public class LoginProxyException : Exception
{ {
} }
protected LoginProxyException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public LoginProxyException(string? message) : base(message) public LoginProxyException(string? message) : base(message)
{ {
} }

View File

@ -54,7 +54,7 @@ public abstract class FetchEngineIncrementalSource<T, TModel>
if (_asyncEnumerator.Current is { } obj && !_yieldedItems.Contains(Identifier(obj))) if (_asyncEnumerator.Current is { } obj && !_yieldedItems.Contains(Identifier(obj)))
{ {
result.Add(Select(obj)); result.Add(Select(obj));
_yieldedItems.Add(Identifier(obj)); _ = _yieldedItems.Add(Identifier(obj));
i++; i++;
_yieldedCounter++; _yieldedCounter++;
} }

View File

@ -20,7 +20,6 @@
using Pixeval.Attributes; using Pixeval.Attributes;
namespace Pixeval.Options; namespace Pixeval.Options;
public enum ThumbnailDirection public enum ThumbnailDirection

View File

@ -20,7 +20,6 @@
using Pixeval.Attributes; using Pixeval.Attributes;
namespace Pixeval.Options; namespace Pixeval.Options;
public enum XRestrictLevel public enum XRestrictLevel

View File

@ -50,7 +50,7 @@ public sealed partial class BookmarksPage : ISortedIllustrationContainerPageHelp
{ {
PrivacyPolicyComboBox.SelectedItem = PrivacyPolicyComboBoxPublicItem; PrivacyPolicyComboBox.SelectedItem = PrivacyPolicyComboBoxPublicItem;
SortOptionComboBox.SelectedItem = MakoHelper.GetAppSettingDefaultSortOptionWrapper(); SortOptionComboBox.SelectedItem = MakoHelper.GetAppSettingDefaultSortOptionWrapper();
WeakReferenceMessenger.Default.TryRegister<BookmarksPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.IllustrationContainer.ViewModel.DataProvider.FetchEngine?.Cancel()); _ = WeakReferenceMessenger.Default.TryRegister<BookmarksPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.IllustrationContainer.ViewModel.DataProvider.FetchEngine?.Cancel());
ChangeSource(); ChangeSource();
} }

View File

@ -62,7 +62,7 @@ public sealed partial class FollowingsPage
public override void OnPageActivated(NavigationEventArgs e) public override void OnPageActivated(NavigationEventArgs e)
{ {
WeakReferenceMessenger.Default.TryRegister<FollowingsPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.ViewModel.DataProvider.FetchEngine?.Cancel()); _ = WeakReferenceMessenger.Default.TryRegister<FollowingsPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.ViewModel.DataProvider.FetchEngine?.Cancel());
_ = ViewModel.ResetEngineAndFillAsync(App.AppViewModel.MakoClient.Following(App.AppViewModel.PixivUid!, PrivacyPolicy.Public)); _ = ViewModel.ResetEngineAndFillAsync(App.AppViewModel.MakoClient.Following(App.AppViewModel.PixivUid!, PrivacyPolicy.Public));
} }
@ -75,7 +75,7 @@ public sealed partial class FollowingsPage
if (IllustratorListView.SelectedIndex is > 0 and var i && i < ViewModel.DataProvider.Source.Count && IllustratorContentViewerFrame is { } frame) if (IllustratorListView.SelectedIndex is > 0 and var i && i < ViewModel.DataProvider.Source.Count && IllustratorContentViewerFrame is { } frame)
{ {
frame.Navigate(typeof(IllustratorContentViewerPage), ViewModel.DataProvider.Source[i]); _ = frame.Navigate(typeof(IllustratorContentViewerPage), ViewModel.DataProvider.Source[i]);
} }
} }
@ -89,6 +89,6 @@ public sealed partial class FollowingsPage
_illustratorListViewLoaded = true; _illustratorListViewLoaded = true;
await ThreadingHelper.SpinWaitAsync(() => !ViewModel.DataProvider.Source.Any() && !ViewModel.HasNoItems); await ThreadingHelper.SpinWaitAsync(() => !ViewModel.DataProvider.Source.Any() && !ViewModel.HasNoItems);
IllustratorListView.SelectedIndex = 0; IllustratorListView.SelectedIndex = 0;
IllustratorContentViewerFrame.Navigate(typeof(IllustratorContentViewerPage), ViewModel.DataProvider.Source[0]); _ = IllustratorContentViewerFrame.Navigate(typeof(IllustratorContentViewerPage), ViewModel.DataProvider.Source[0]);
} }
} }

View File

@ -55,7 +55,7 @@ public sealed partial class RankingsPage : ISortedIllustrationContainerPageHelpe
SortOptionComboBox.SelectedItem = MakoHelper.GetAppSettingDefaultSortOptionWrapper(); SortOptionComboBox.SelectedItem = MakoHelper.GetAppSettingDefaultSortOptionWrapper();
RankOptionComboBox.SelectedItem = LocalizedBoxHelper.Of<RankOption, RankOptionWrapper>(RankOption.Day); RankOptionComboBox.SelectedItem = LocalizedBoxHelper.Of<RankOption, RankOptionWrapper>(RankOption.Day);
RankDateTimeCalendarDatePicker.Date = DateTime.Now.AddDays(-2); RankDateTimeCalendarDatePicker.Date = DateTime.Now.AddDays(-2);
WeakReferenceMessenger.Default.TryRegister<RankingsPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.IllustrationContainer.ViewModel.DataProvider.FetchEngine?.Cancel()); _ = WeakReferenceMessenger.Default.TryRegister<RankingsPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.IllustrationContainer.ViewModel.DataProvider.FetchEngine?.Cancel());
ChangeSource(); ChangeSource();
} }

View File

@ -50,7 +50,7 @@ public sealed partial class RecentPostsPage : ISortedIllustrationContainerPageHe
{ {
PrivacyPolicyComboBox.SelectedItem = PrivacyPolicyComboBoxPublicItem; PrivacyPolicyComboBox.SelectedItem = PrivacyPolicyComboBoxPublicItem;
SortOptionComboBox.SelectedItem = MakoHelper.GetAppSettingDefaultSortOptionWrapper(); SortOptionComboBox.SelectedItem = MakoHelper.GetAppSettingDefaultSortOptionWrapper();
WeakReferenceMessenger.Default.TryRegister<RecentPostsPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.IllustrationContainer.ViewModel.DataProvider.FetchEngine?.Cancel()); _ = WeakReferenceMessenger.Default.TryRegister<RecentPostsPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.IllustrationContainer.ViewModel.DataProvider.FetchEngine?.Cancel());
ChangeSource(); ChangeSource();
} }

View File

@ -52,7 +52,7 @@ public sealed partial class RecommendationPage : ISortedIllustrationContainerPag
{ {
ModeSelectionComboBox.SelectedItem = ModeSelectionComboBoxIllustComboBoxItem; ModeSelectionComboBox.SelectedItem = ModeSelectionComboBoxIllustComboBoxItem;
SortOptionComboBox.SelectedItem = MakoHelper.GetAppSettingDefaultSortOptionWrapper(); SortOptionComboBox.SelectedItem = MakoHelper.GetAppSettingDefaultSortOptionWrapper();
WeakReferenceMessenger.Default.TryRegister<RecommendationPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.IllustrationContainer.ViewModel.DataProvider.FetchEngine?.Cancel()); _ = WeakReferenceMessenger.Default.TryRegister<RecommendationPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.IllustrationContainer.ViewModel.DataProvider.FetchEngine?.Cancel());
ChangeSource(); ChangeSource();
} }

View File

@ -50,7 +50,7 @@ public sealed partial class SearchResultsPage : ISortedIllustrationContainerPage
{ {
SortOptionComboBox.SelectedItem = MakoHelper.GetAppSettingDefaultSortOptionWrapper(); SortOptionComboBox.SelectedItem = MakoHelper.GetAppSettingDefaultSortOptionWrapper();
ChangeSource((IFetchEngine<Illustration>)navigationEventArgs.Parameter); ChangeSource((IFetchEngine<Illustration>)navigationEventArgs.Parameter);
WeakReferenceMessenger.Default.TryRegister<SearchResultsPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.IllustrationContainer.ViewModel.DataProvider.FetchEngine?.Cancel()); _ = WeakReferenceMessenger.Default.TryRegister<SearchResultsPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.IllustrationContainer.ViewModel.DataProvider.FetchEngine?.Cancel());
} }
private void ChangeSource(IFetchEngine<Illustration> engine) private void ChangeSource(IFetchEngine<Illustration> engine)

View File

@ -78,7 +78,7 @@ public sealed partial class DownloadListEntry
case DownloadState.Error: case DownloadState.Error:
case DownloadState.Cancelled: case DownloadState.Cancelled:
case DownloadState.Completed: case DownloadState.Completed:
await Launcher.LaunchUriAsync(new(ViewModel.DownloadTask.Destination)); _ = await Launcher.LaunchUriAsync(new(ViewModel.DownloadTask.Destination));
break; break;
case DownloadState.Paused: case DownloadState.Paused:
ViewModel.DownloadTask.CancellationHandle.Resume(); ViewModel.DownloadTask.CancellationHandle.Resume();
@ -101,14 +101,14 @@ public sealed partial class DownloadListEntry
private async void OpenDownloadLocationItem_OnTapped(object sender, TappedRoutedEventArgs e) private async void OpenDownloadLocationItem_OnTapped(object sender, TappedRoutedEventArgs e)
{ {
await Launcher.LaunchFolderPathAsync(Path.GetDirectoryName(ViewModel.DownloadTask.Destination)); _ = await Launcher.LaunchFolderPathAsync(Path.GetDirectoryName(ViewModel.DownloadTask.Destination));
} }
private void GoToPageItem_OnTapped(object sender, TappedRoutedEventArgs e) => OpenIllustrationRequested?.Invoke(this, ViewModel); private void GoToPageItem_OnTapped(object sender, TappedRoutedEventArgs e) => OpenIllustrationRequested?.Invoke(this, ViewModel);
private async void CheckErrorMessageInDetail_OnTapped(object sender, TappedRoutedEventArgs e) private async void CheckErrorMessageInDetail_OnTapped(object sender, TappedRoutedEventArgs e)
{ {
await MessageDialogBuilder.CreateAcknowledgement(CurrentContext.Window, DownloadListEntryResources.ErrorMessageDialogTitle, ViewModel.DownloadTask.ErrorCause!.ToString()) _ = await MessageDialogBuilder.CreateAcknowledgement(CurrentContext.Window, DownloadListEntryResources.ErrorMessageDialogTitle, ViewModel.DownloadTask.ErrorCause!.ToString())
.ShowAsync(); .ShowAsync();
} }
} }

View File

@ -20,7 +20,6 @@
using Pixeval.Attributes; using Pixeval.Attributes;
namespace Pixeval.Pages.Download; namespace Pixeval.Pages.Download;
public enum DownloadListOption public enum DownloadListOption

View File

@ -107,7 +107,7 @@ public sealed partial class DownloadListPage
{ {
foreach (var downloadListEntryViewModel in _viewModel.SelectedTasks) foreach (var downloadListEntryViewModel in _viewModel.SelectedTasks)
{ {
IOHelper.DeleteAsync(downloadListEntryViewModel.DownloadTask.Destination).Discard(); IoHelper.DeleteAsync(downloadListEntryViewModel.DownloadTask.Destination).Discard();
} }
} }
@ -170,7 +170,6 @@ public sealed partial class DownloadListPage
viewModel.CreateWindowWithPage(_viewModel.DownloadTasks); viewModel.CreateWindowWithPage(_viewModel.DownloadTasks);
} }
private void DownloadListEntryOnEffectiveViewportChanged(FrameworkElement sender, EffectiveViewportChangedEventArgs args) private void DownloadListEntryOnEffectiveViewportChanged(FrameworkElement sender, EffectiveViewportChangedEventArgs args)
{ {
var context = sender.GetDataContext<IllustrationViewModel>(); var context = sender.GetDataContext<IllustrationViewModel>();

View File

@ -56,8 +56,8 @@ public partial class DownloadListPageViewModel : ObservableObject, IDisposable
public DownloadListPageViewModel() public DownloadListPageViewModel()
{ {
_downloadTasks = new(); _downloadTasks = [];
_filteredTasks = new(); _filteredTasks = [];
_downloadTasksView = new(_downloadTasks, true); _downloadTasksView = new(_downloadTasks, true);
_selectionLabel = DownloadListPageResources.CancelSelectionButtonDefaultLabel; _selectionLabel = DownloadListPageResources.CancelSelectionButtonDefaultLabel;
} }
@ -104,8 +104,8 @@ public partial class DownloadListPageViewModel : ObservableObject, IDisposable
SelectedTasks.ToList().ForEach(task => SelectedTasks.ToList().ForEach(task =>
{ {
App.AppViewModel.DownloadManager.RemoveTask(task.DownloadTask); App.AppViewModel.DownloadManager.RemoveTask(task.DownloadTask);
DownloadTasks.Remove(task); _ = DownloadTasks.Remove(task);
manager.Delete(m => m.Destination == task.DownloadTask.Destination); _ = manager.Delete(m => m.Destination == task.DownloadTask.Destination);
}); });
DownloadTasksView.Refresh(); DownloadTasksView.Refresh();

View File

@ -51,7 +51,7 @@ public sealed partial class CommentsPage
public override void OnPageActivated(NavigationEventArgs e) public override void OnPageActivated(NavigationEventArgs e)
{ {
// Dispose current page contents if the parent page (IllustrationViewerPage) is navigating // Dispose current page contents if the parent page (IllustrationViewerPage) is navigating
WeakReferenceMessenger.Default.TryRegister<CommentsPage, NavigatingFromIllustrationViewerMessage>(this, (recipient, _) => _ = WeakReferenceMessenger.Default.TryRegister<CommentsPage, NavigatingFromIllustrationViewerMessage>(this, (recipient, _) =>
{ {
recipient.CommentList.Dispose(); recipient.CommentList.Dispose();
WeakReferenceMessenger.Default.UnregisterAll(this); WeakReferenceMessenger.Default.UnregisterAll(this);

View File

@ -52,7 +52,7 @@ public sealed partial class IllustrationInfoPage
private void IllustrationTagButton_OnTapped(object sender, TappedRoutedEventArgs e) private void IllustrationTagButton_OnTapped(object sender, TappedRoutedEventArgs e)
{ {
WeakReferenceMessenger.Default.Send(new IllustrationTagClickedMessage((string)((Button)sender).Content)); _ = WeakReferenceMessenger.Default.Send(new IllustrationTagClickedMessage((string)((Button)sender).Content));
} }
//private async void IllustrationCaptionMarkdownTextBlock_OnLinkClicked(object? sender, LinkClickedEventArgs e) //private async void IllustrationCaptionMarkdownTextBlock_OnLinkClicked(object? sender, LinkClickedEventArgs e)
@ -64,7 +64,7 @@ public sealed partial class IllustrationInfoPage
{ {
if (_viewModel.Illustrator is { } userInfo) if (_viewModel.Illustrator is { } userInfo)
{ {
ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ForwardConnectedAnimation", (UIElement)sender); _ = ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ForwardConnectedAnimation", (UIElement)sender);
// todo IllustratorPage use Navigate // todo IllustratorPage use Navigate
// CurrentContext.Window.Content.To<Frame>().Navigate(typeof(IllustratorPage), Tuple.Create((UIElement)sender, new IllustratorViewModel(userInfo)), new SlideNavigationTransitionInfo // CurrentContext.Window.Content.To<Frame>().Navigate(typeof(IllustratorPage), Tuple.Create((UIElement)sender, new IllustratorViewModel(userInfo)), new SlideNavigationTransitionInfo
// { // {

View File

@ -115,7 +115,7 @@ public sealed partial class IllustrationViewerPage : ISupportCustomTitleBarDragR
} }
case IllustrationViewerPageViewModel.ShowShare: case IllustrationViewerPageViewModel.ShowShare:
{ {
Window.ShowShareUI(); Window.ShowShareUi();
break; break;
} }
case nameof(IllustrationViewerPageViewModel.IsInfoPaneOpen): case nameof(IllustrationViewerPageViewModel.IsInfoPaneOpen):

View File

@ -359,7 +359,7 @@ public partial class IllustrationViewerPageViewModel : DetailedObservableObject,
RestoreResolutionCommand.CanExecuteRequested += LoadingCompletedCanExecuteRequested; RestoreResolutionCommand.CanExecuteRequested += LoadingCompletedCanExecuteRequested;
CopyCommand.CanExecuteRequested += LoadingCompletedCanExecuteRequested; CopyCommand.CanExecuteRequested += LoadingCompletedCanExecuteRequested;
CopyCommand.ExecuteRequested += async (_, _) => UIHelper.ClipboardSetBitmap(await CurrentImage.OriginalImageStream!.EncodeBitmapStreamAsync(false)); CopyCommand.ExecuteRequested += async (_, _) => UiHelper.ClipboardSetBitmap(await CurrentImage.OriginalImageStream!.EncodeBitmapStreamAsync(false));
PlayGifCommand.CanExecuteRequested += (_, e) => e.CanExecute = IsUgoira && CurrentImage.LoadingCompletedSuccessfully; PlayGifCommand.CanExecuteRequested += (_, e) => e.CanExecute = IsUgoira && CurrentImage.LoadingCompletedSuccessfully;
PlayGifCommand.ExecuteRequested += PlayGifCommandOnExecuteRequested; PlayGifCommand.ExecuteRequested += PlayGifCommandOnExecuteRequested;
@ -461,13 +461,13 @@ public partial class IllustrationViewerPageViewModel : DetailedObservableObject,
GenerateLinkTeachingTip.IsOpen = true; GenerateLinkTeachingTip.IsOpen = true;
} }
UIHelper.ClipboardSetText(MakoHelper.GenerateIllustrationAppUri(CurrentIllustration.Id).ToString()); UiHelper.ClipboardSetText(MakoHelper.GenerateIllustrationAppUri(CurrentIllustration.Id).ToString());
} }
private void GenerateWebLinkCommandOnExecuteRequested(XamlUICommand sender, ExecuteRequestedEventArgs args) private void GenerateWebLinkCommandOnExecuteRequested(XamlUICommand sender, ExecuteRequestedEventArgs args)
{ {
var link = MakoHelper.GenerateIllustrationWebUri(CurrentIllustration.Id).ToString(); var link = MakoHelper.GenerateIllustrationWebUri(CurrentIllustration.Id).ToString();
UIHelper.ClipboardSetText(link); UiHelper.ClipboardSetText(link);
SnackBarTeachingTip.ShowAndHide(IllustrationViewerPageResources.WebLinkCopiedToClipboardToastTitle); SnackBarTeachingTip.ShowAndHide(IllustrationViewerPageResources.WebLinkCopiedToClipboardToastTitle);
} }
@ -484,7 +484,7 @@ public partial class IllustrationViewerPageViewModel : DetailedObservableObject,
private async void ShowQrCodeCommandExecuteRequested(XamlUICommand sender, ExecuteRequestedEventArgs args) private async void ShowQrCodeCommandExecuteRequested(XamlUICommand sender, ExecuteRequestedEventArgs args)
{ {
var qrCodeSource = await UIHelper.GenerateQrCodeForUrlAsync(MakoHelper.GenerateIllustrationWebUri(CurrentIllustration.Id).ToString()); var qrCodeSource = await UiHelper.GenerateQrCodeForUrlAsync(MakoHelper.GenerateIllustrationWebUri(CurrentIllustration.Id).ToString());
ShowQrCodeTeachingTip.HeroContent.To<Image>().Source = qrCodeSource; ShowQrCodeTeachingTip.HeroContent.To<Image>().Source = qrCodeSource;
OnPropertyChanged(nameof(ShowQrCode)); OnPropertyChanged(nameof(ShowQrCode));

View File

@ -40,7 +40,7 @@ public class IllustrationVisualizationController(IIllustrationVisualizer visuali
{ {
var collection = new IncrementalLoadingCollection<FetchEngineIncrementalSource<Illustration, IllustrationViewModel>, IllustrationViewModel>(new IllustrationFetchEngineIncrementalSource(FetchEngine!, itemsLimit)); var collection = new IncrementalLoadingCollection<FetchEngineIncrementalSource<Illustration, IllustrationViewModel>, IllustrationViewModel>(new IllustrationFetchEngineIncrementalSource(FetchEngine!, itemsLimit));
visualizer.Illustrations = collection; visualizer.Illustrations = collection;
await collection.LoadMoreItemsAsync(20); _ = await collection.LoadMoreItemsAsync(20);
visualizer.Illustrations.CollectionChanged += CollectionChanged; visualizer.Illustrations.CollectionChanged += CollectionChanged;
return visualizer.Illustrations.Count > 0; return visualizer.Illustrations.Count > 0;
} }
@ -48,7 +48,7 @@ public class IllustrationVisualizationController(IIllustrationVisualizer visuali
public async Task FillAsync(IFetchEngine<Illustration?>? newEngine, int itemsLimit = -1) public async Task FillAsync(IFetchEngine<Illustration?>? newEngine, int itemsLimit = -1)
{ {
FetchEngine = newEngine; FetchEngine = newEngine;
await FillAsync(itemsLimit); _ = await FillAsync(itemsLimit);
} }
public Task<bool> ResetAndFillAsync(IFetchEngine<Illustration?>? newEngine, int itemsLimit = -1) public Task<bool> ResetAndFillAsync(IFetchEngine<Illustration?>? newEngine, int itemsLimit = -1)

View File

@ -147,7 +147,7 @@ public partial class ImageViewerPageViewModel : ObservableObject, IDisposable
{ {
using var scope = App.AppViewModel.AppServicesScope; using var scope = App.AppViewModel.AppServicesScope;
var manager = scope.ServiceProvider.GetRequiredService<BrowseHistoryPersistentManager>(); var manager = scope.ServiceProvider.GetRequiredService<BrowseHistoryPersistentManager>();
manager.Delete(x => x.Id == IllustrationViewerPageViewModel.IllustrationId); _ = manager.Delete(x => x.Id == IllustrationViewerPageViewModel.IllustrationId);
manager.Insert(new() { Id = IllustrationViewModel.Id }); manager.Insert(new() { Id = IllustrationViewModel.Id });
} }
@ -158,10 +158,7 @@ public partial class ImageViewerPageViewModel : ObservableObject, IDisposable
_disposed = false; _disposed = false;
const ThumbnailUrlOption option = ThumbnailUrlOption.Medium; const ThumbnailUrlOption option = ThumbnailUrlOption.Medium;
_ = IllustrationViewModel.TryLoadThumbnail(this, option).ContinueWith( _ = IllustrationViewModel.TryLoadThumbnail(this, option).ContinueWith(
_ => _ => OriginalImageSources ??= [IllustrationViewModel.ThumbnailStreams[option]],
{
OriginalImageSources ??= new[] { IllustrationViewModel.ThumbnailStreams[option] };
},
TaskScheduler.FromCurrentSynchronizationContext()); TaskScheduler.FromCurrentSynchronizationContext());
AddHistory(); AddHistory();
await LoadOriginalImage(); await LoadOriginalImage();
@ -198,7 +195,7 @@ public partial class ImageViewerPageViewModel : ObservableObject, IDisposable
{ {
case Result<Stream>.Success(var zipStream): case Result<Stream>.Success(var zipStream):
AdvancePhase(LoadingPhase.MergingGifFrames); AdvancePhase(LoadingPhase.MergingGifFrames);
OriginalImageSources = await IOHelper.GetStreamsFromZipStreamAsync(zipStream); OriginalImageSources = await IoHelper.GetStreamsFromZipStreamAsync(zipStream);
MsIntervals = ugoiraMetadata.UgoiraMetadataInfo.Frames?.Select(x => (int)x.Delay)?.ToList(); MsIntervals = ugoiraMetadata.UgoiraMetadataInfo.Frames?.Select(x => (int)x.Delay)?.ToList();
break; break;
case Result<Stream>.Failure(OperationCanceledException): case Result<Stream>.Failure(OperationCanceledException):

View File

@ -39,7 +39,7 @@ namespace Pixeval.Pages.IllustrationViewer;
public sealed partial class PixivReplyEmojiListPage public sealed partial class PixivReplyEmojiListPage
{ {
public static ObservableCollection<PixivReplyEmojiViewModel> EmojiList = new(); public static ObservableCollection<PixivReplyEmojiViewModel> EmojiList = [];
private PixivReplyBar? _replyBar; private PixivReplyBar? _replyBar;

View File

@ -22,7 +22,6 @@ using Microsoft.UI.Xaml.Media;
using Pixeval.Misc; using Pixeval.Misc;
using Windows.Storage.Streams; using Windows.Storage.Streams;
namespace Pixeval.Pages.IllustrationViewer; namespace Pixeval.Pages.IllustrationViewer;
public class PixivReplyEmojiViewModel(PixivReplyEmoji emojiEnumValue, IRandomAccessStream imageStream) public class PixivReplyEmojiViewModel(PixivReplyEmoji emojiEnumValue, IRandomAccessStream imageStream)

View File

@ -37,7 +37,7 @@ namespace Pixeval.Pages.IllustrationViewer;
public sealed partial class PixivReplyStickerListPage public sealed partial class PixivReplyStickerListPage
{ {
public static readonly ObservableCollection<PixivReplyStickerViewModel> Stickers = new(); public static readonly ObservableCollection<PixivReplyStickerViewModel> Stickers = [];
private EventHandler<StickerTappedEventArgs>? _replyBarStickerTappedEventHandler; private EventHandler<StickerTappedEventArgs>? _replyBarStickerTappedEventHandler;

View File

@ -41,7 +41,7 @@ public sealed partial class RelatedWorksPage
public override async void OnPageActivated(NavigationEventArgs e) public override async void OnPageActivated(NavigationEventArgs e)
{ {
// Dispose current page contents if the parent page (IllustrationViewerPage) is navigating // Dispose current page contents if the parent page (IllustrationViewerPage) is navigating
WeakReferenceMessenger.Default.TryRegister<RelatedWorksPage, NavigatingFromIllustrationViewerMessage>(this, (recipient, _) => _ = WeakReferenceMessenger.Default.TryRegister<RelatedWorksPage, NavigatingFromIllustrationViewerMessage>(this, (recipient, _) =>
{ {
recipient.RelatedWorksIllustrationGrid.ViewModel.Dispose(); recipient.RelatedWorksIllustrationGrid.ViewModel.Dispose();
WeakReferenceMessenger.Default.UnregisterAll(this); WeakReferenceMessenger.Default.UnregisterAll(this);

View File

@ -93,8 +93,8 @@ public sealed partial class IllustratorPage
switch (navigationEventArgs.Parameter) switch (navigationEventArgs.Parameter)
{ {
case (UIElement sender, IllustratorViewModel viewModel): case (UIElement sender, IllustratorViewModel viewModel):
WeakReferenceMessenger.Default.Send(new MainPageFrameSetConnectedAnimationTargetMessage(sender)); _ = WeakReferenceMessenger.Default.Send(new MainPageFrameSetConnectedAnimationTargetMessage(sender));
ConnectedAnimationService.GetForCurrentView().GetAnimation("ForwardConnectedAnimation")?.TryStart(ProfileImage); _ = (ConnectedAnimationService.GetForCurrentView().GetAnimation("ForwardConnectedAnimation")?.TryStart(ProfileImage));
_viewModel = viewModel; _viewModel = viewModel;
break; break;
case IllustratorViewModel viewModel1: case IllustratorViewModel viewModel1:
@ -102,7 +102,7 @@ public sealed partial class IllustratorPage
break; break;
} }
WeakReferenceMessenger.Default.TryRegister<IllustratorPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.ViewModelProvider.ViewModel.DataProvider.FetchEngine?.Cancel()); _ = WeakReferenceMessenger.Default.TryRegister<IllustratorPage, MainPageFrameNavigatingEvent>(this, static (recipient, _) => recipient.ViewModelProvider.ViewModel.DataProvider.FetchEngine?.Cancel());
ChangeSource(); ChangeSource();
} }
@ -217,7 +217,7 @@ public sealed partial class IllustratorPage
public void GoBack() public void GoBack()
{ {
ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ForwardConnectedAnimation", ProfileImage); _ = ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ForwardConnectedAnimation", ProfileImage);
Parent.To<Frame>().GoBack(new SuppressNavigationTransitionInfo()); Parent.To<Frame>().GoBack(new SuppressNavigationTransitionInfo());
} }
@ -228,7 +228,7 @@ public sealed partial class IllustratorPage
private async void OpenLinkButton_OnTapped(object sender, TappedRoutedEventArgs e) private async void OpenLinkButton_OnTapped(object sender, TappedRoutedEventArgs e)
{ {
await Launcher.LaunchUriAsync(new Uri($"https://www.pixiv.net/users/{_viewModel!.Id}")); _ = await Launcher.LaunchUriAsync(new Uri($"https://www.pixiv.net/users/{_viewModel!.Id}"));
} }
private async void FollowButton_OnTapped(object sender, TappedRoutedEventArgs e) private async void FollowButton_OnTapped(object sender, TappedRoutedEventArgs e)

View File

@ -61,7 +61,7 @@ public sealed partial class LoginPage
} }
AppContext.SaveContext(); AppContext.SaveContext();
WeakReferenceMessenger.Default.Send(new LoginCompletedMessage(this, App.AppViewModel.MakoClient.Session)); _ = WeakReferenceMessenger.Default.Send(new LoginCompletedMessage(this, App.AppViewModel.MakoClient.Session));
} }
catch (Exception exception) catch (Exception exception)
{ {
@ -101,7 +101,7 @@ public sealed partial class LoginPage
LoginPageResources.WebView2InstallationRequiredContent).ShowAsync(); LoginPageResources.WebView2InstallationRequiredContent).ShowAsync();
if (dialogResult == ContentDialogResult.Primary) if (dialogResult == ContentDialogResult.Primary)
{ {
await Launcher.LaunchUriAsync(new Uri("https://go.microsoft.com/fwlink/p/?LinkId=2124703")); _ = await Launcher.LaunchUriAsync(new Uri("https://go.microsoft.com/fwlink/p/?LinkId=2124703"));
} }
App.ExitWithPushNotification(); App.ExitWithPushNotification();

View File

@ -152,7 +152,7 @@ public partial class LoginPageViewModel : AutoActivateObservableRecipient
} }
else else
{ {
await MessageDialogBuilder.CreateAcknowledgement( _ = await MessageDialogBuilder.CreateAcknowledgement(
CurrentContext.Window, CurrentContext.Window,
LoginPageResources.RefreshingSessionIsNotPresentTitle, LoginPageResources.RefreshingSessionIsNotPresentTitle,
LoginPageResources.RefreshingSessionIsNotPresentContent) LoginPageResources.RefreshingSessionIsNotPresentContent)
@ -188,10 +188,7 @@ public partial class LoginPageViewModel : AutoActivateObservableRecipient
await WebView.LoginWebView2.EnsureCoreWebView2Async(); await WebView.LoginWebView2.EnsureCoreWebView2Async();
WebView.LoginWebView2.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All); WebView.LoginWebView2.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);
WebView.LoginWebView2.CoreWebView2.WebResourceRequested += (_, args) => WebView.LoginWebView2.CoreWebView2.WebResourceRequested += (_, args) => args.Request.Headers.SetHeader("Accept-Language", args.Request.Uri.Contains("recaptcha") ? "zh-cn" : CultureInfo.CurrentUICulture.Name);
{
args.Request.Headers.SetHeader("Accept-Language", args.Request.Uri.Contains("recaptcha") ? "zh-cn" : CultureInfo.CurrentUICulture.Name);
};
var verifier = PixivAuthSignature.GetCodeVerify(); var verifier = PixivAuthSignature.GetCodeVerify();
WebView.LoginWebView2.Source = new Uri(PixivAuthSignature.GenerateWebPageUrl(verifier)); WebView.LoginWebView2.Source = new Uri(PixivAuthSignature.GenerateWebPageUrl(verifier));
@ -221,7 +218,7 @@ public partial class LoginPageViewModel : AutoActivateObservableRecipient
("grant_type", "authorization_code"), ("grant_type", "authorization_code"),
("include_policy", "true"), ("include_policy", "true"),
("redirect_uri", "https://app-api.pixiv.net/web/v1/users/auth/pixiv/callback")); ("redirect_uri", "https://app-api.pixiv.net/web/v1/users/auth/pixiv/callback"));
result.EnsureSuccessStatusCode(); _ = result.EnsureSuccessStatusCode();
var session = (await result.Content.ReadAsStringAsync()).FromJson<TokenResponse>()!.ToSession() with var session = (await result.Content.ReadAsStringAsync()).FromJson<TokenResponse>()!.ToSession() with
{ {
Cookie = cookie, Cookie = cookie,

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval #region Copyright (c) Pixeval/Pixeval
// GPL v3 License // GPL v3 License
// //
// Pixeval/Pixeval // Pixeval/Pixeval
@ -33,7 +33,7 @@ public static class PixivAuthSignature
private static string ToUrlSafeBase64String(this byte[] bytes) private static string ToUrlSafeBase64String(this byte[] bytes)
{ {
return Convert.ToBase64String(bytes).TrimEnd(new[] { '=' }).Replace("+", "-").Replace("/", "_"); return Convert.ToBase64String(bytes).TrimEnd(['=']).Replace("+", "-").Replace("/", "_");
} }
public static string GenerateWebPageUrl(string codeVerify, bool signUp = false) public static string GenerateWebPageUrl(string codeVerify, bool signUp = false)

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