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
# ReSharper properties
resharper_max_initializer_elements_on_line = 1

1
.gitattributes vendored
View File

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

View File

@ -30,17 +30,18 @@
---
**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,
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/)
which is the WPF version has been deprecated and expecting no more supports from developers.**
> 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
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
1. Install [Visual Studio 2022](https://visualstudio.microsoft.com/vs) (Roslyn 4.x requires VS17.x, i.e. VS2022)
@ -108,10 +109,9 @@ If this project meets your requirements perfectly, welcome the buy me a coffee a
## JetBrains Open Source License
<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>
<br/>
The Jetbrains™ ReSharper is heavily used during the development of this project. Thank JetBrains s.r.o for providing the [JetBrains Open Source License]((https://www.jetbrains.com/community/opensource/#support)), If you are one of the passionate developers who often put JetBrains products into use, you can try to apply the JetBrains Open Source License from the [official channel](https://www.jetbrains.com/shop/eform/opensource) to help you and your developer teammates to significantly improve the productivities
</div>
</div>

View File

@ -36,7 +36,7 @@
更多详细信息请前往 [项目主页](https://sora.ink/pixeval) 查看
**WinUI3版本提供了更好的UI更好的项目结构以及更好的开发体验如果你想要了解目前的开发进度可以通过以下方法来下载并编译该项目**
**WinUI3版本提供了更好的UI更好的项目结构以及更好的开发体验如果你想要了解目前的开发进度可以通过以下方法来下载并编译该项目**
## 环境要求
@ -108,4 +108,4 @@
<br/>
本项目重度依赖于 [JetBrains](https://www.jetbrains.com/?from=ImageSharp) ReSharper感谢JetBrains s.r.o为本项目提供 [开源许可证](https://www.jetbrains.com/community/opensource/#support)如果你同样对开发充满热情并且经常使用JetBrains s.r.o的产品你也可以尝试通过JetBrains官方渠道 [申请](https://www.jetbrains.com/shop/eform/opensource) 开源许可证以供核心开发者使用
</div>
</div>

View File

@ -25,17 +25,12 @@ namespace Pixeval.Controls;
/// <summary>
/// AutomationPeer for CardControl
/// </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>
/// Gets the control type for the element that is associated with the UI Automation peer.
/// </summary>

View File

@ -43,6 +43,6 @@ public partial class PersonView : UserControl
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">
<PropertyGroup>
<TargetFramework>net8.0-windows10.0.19041.0</TargetFramework>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
<TargetPlatformMinVersion>10.0.19041.0</TargetPlatformMinVersion>
<RootNamespace>Pixeval.Controls</RootNamespace>
<Platforms>x86;x64;arm64</Platforms>
<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)
{
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/>.
#endregion
namespace Pixeval.Controls.Windowing;
public interface ISupportCustomTitleBarDragRegion

View File

@ -34,7 +34,7 @@ public static class WindowFactory
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;

View File

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

View File

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

View File

@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion
namespace Pixeval.CoreApi.Engine;
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
//
// Pixeval/Pixeval.CoreApi
@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion
namespace Pixeval.CoreApi.Engine;
/// <summary>
@ -29,4 +28,4 @@ namespace Pixeval.CoreApi.Engine;
public interface IEngineHandleSource
{
EngineHandle EngineHandle { get; }
}
}

View File

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

View File

@ -31,20 +31,15 @@ namespace Pixeval.CoreApi.Engine.Implements;
/// only supposed to be used by caching systems
/// </summary>
/// <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;
/// <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;
}
private readonly IEnumerable<T> _outer = outer;
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
//
// Pixeval/Pixeval.CoreApi
@ -30,31 +30,24 @@ namespace Pixeval.CoreApi.Engine.Implements;
/// <summary>
/// An <see cref="IFetchEngine{E}" /> that fetches the bookmark of a specific user
/// </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 TargetFilter _targetFilter;
private readonly string _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;
}
private readonly PrivacyPolicy _privacyPolicy = privacyPolicy;
private readonly TargetFilter _targetFilter = targetFilter;
private readonly string _uid = uid;
public override IAsyncEnumerator<Illustration> GetAsyncEnumerator(CancellationToken cancellationToken = new())
{
@ -64,4 +57,4 @@ internal class BookmarkEngine : AbstractPixivFetchEngine<Illustration>
+ $"&restrict={engine._privacyPolicy.GetDescription()}"
+ $"&filter={engine._targetFilter.GetDescription()}")!;
}
}
}

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi
#region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License
//
// Pixeval/Pixeval.CoreApi
@ -33,20 +33,19 @@ using Pixeval.Utilities;
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())
{
return new UserFeedsAsyncEnumerator(this, MakoApiKind.WebApi)!;
}
private class UserFeedsAsyncEnumerator
private partial class UserFeedsAsyncEnumerator
(FeedEngine pixivFetchEngine, MakoApiKind apiKind) : AbstractPixivAsyncEnumerator<Feed, string, FeedEngine>(pixivFetchEngine, apiKind)
{
private FeedRequestContext? _feedRequestContext;
private string? _tt;
public override async ValueTask<bool> MoveNextAsync()
{
if (_feedRequestContext is null)
@ -57,7 +56,7 @@ internal class FeedEngine(MakoClient makoClient, EngineHandle? engineHandle) : A
if (TryParsePreloadJsonFromHtml(response, out var result))
{
await UpdateAsync(result).ConfigureAwait(false);
_tt = Regex.Match(response, "tt: \"(?<tt>.*)\"").Groups["tt"].Value;
_tt = TtRegex().Match(response).Groups["tt"].Value;
_feedRequestContext = ExtractRequestContextFromHtml(response);
}
else
@ -147,7 +146,7 @@ internal class FeedEngine(MakoClient makoClient, EngineHandle? engineHandle) : A
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)
{
json = match.Groups["json"].Value;
@ -296,10 +295,15 @@ internal class FeedEngine(MakoClient makoClient, EngineHandle? engineHandle) : A
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>
/// Required parameters established from multiple tests, I don't know what do they mean
/// </summary>
private record FeedRequestContext(string UnifyToken, string Sid, string Mode, bool IsLastPage);
}
}

View File

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

View File

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

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi
#region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License
//
// Pixeval/Pixeval.CoreApi
@ -18,8 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System.Runtime.Serialization;
namespace Pixeval.CoreApi.Global.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)
{
}
@ -39,4 +33,4 @@ public class MakoException : System.Exception
public MakoException(string? message, System.Exception? innerException) : base(message, innerException)
{
}
}
}

View File

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

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.CoreApi
#region Copyright (c) Pixeval/Pixeval.CoreApi
// GPL v3 License
//
// Pixeval/Pixeval.CoreApi
@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System.Runtime.Serialization;
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)
{
}
@ -42,4 +37,4 @@ public class RankingDateOutOfRangeException : MakoException
public RankingDateOutOfRangeException(string? message, System.Exception? innerException) : base(message, innerException)
{
}
}
}

View File

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

View File

@ -312,7 +312,7 @@ public partial class MakoClient
public IFetchEngine<Novel> NovelBookmarks(string uid, PrivacyPolicy privacyPolicy, TargetFilter targetFilter)
{
EnsureNotCancelled();
CheckPrivacyPolicy(uid, privacyPolicy);
_ = CheckPrivacyPolicy(uid, privacyPolicy);
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
//
// Pixeval/Pixeval.CoreApi
@ -28,7 +28,7 @@ namespace Pixeval.CoreApi;
public partial class MakoClient
{
private readonly List<IEngineHandleSource> _runningInstances = new();
private readonly List<IEngineHandleSource> _runningInstances = [];
/// <summary>
/// The globally unique ID of current <see cref="MakoClient" />
@ -47,4 +47,4 @@ public partial class MakoClient
internal IContainer MakoServices { get; init; }
public bool IsCancelled { get; set; }
}
}

View File

@ -87,64 +87,64 @@ public partial class MakoClient : ICancellable
private IContainer BuildContainer()
{
var builder = new ContainerBuilder();
builder.RegisterInstance(this).SingleInstance();
_ = builder.RegisterInstance(this).SingleInstance();
builder.RegisterType<PixivApiNameResolver>().SingleInstance();
builder.RegisterType<PixivImageNameResolver>().SingleInstance();
builder.RegisterType<LocalMachineNameResolver>().SingleInstance();
_ = builder.RegisterType<PixivApiNameResolver>().SingleInstance();
_ = builder.RegisterType<PixivImageNameResolver>().SingleInstance();
_ = builder.RegisterType<LocalMachineNameResolver>().SingleInstance();
builder.RegisterType<PixivApiHttpMessageHandler>().SingleInstance();
builder.RegisterType<PixivImageHttpMessageHandler>().SingleInstance();
_ = builder.RegisterType<PixivApiHttpMessageHandler>().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))
.As<HttpMessageHandler>()
.PropertiesAutowired(static (info, _) => info.PropertyType == typeof(MakoClient))
.SingleInstance();
builder.Register(static c => new MakoRetryHttpClientHandler(c.Resolve<PixivImageHttpMessageHandler>()))
_ = builder.Register(static c => new MakoRetryHttpClientHandler(c.Resolve<PixivImageHttpMessageHandler>()))
.Keyed<HttpMessageHandler>(typeof(PixivImageHttpMessageHandler))
.As<HttpMessageHandler>()
.PropertiesAutowired(static (info, _) => info.PropertyType == typeof(MakoClient))
.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)))
.Keyed<HttpClient>(MakoApiKind.AppApi)
.As<HttpClient>()
.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)))
.Keyed<HttpClient>(MakoApiKind.WebApi)
.As<HttpClient>()
.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)))
.Keyed<HttpClient>(MakoApiKind.AuthApi)
.As<HttpClient>()
.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 =>
{
client.DefaultRequestHeaders.TryAddWithoutValidation("Referer", "https://www.pixiv.net");
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PixivIOSApp/5.8.7");
_ = client.DefaultRequestHeaders.TryAddWithoutValidation("Referer", "https://www.pixiv.net");
_ = client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PixivIOSApp/5.8.7");
}))
.Keyed<HttpClient>(MakoApiKind.ImageApi)
.As<HttpClient>()
.SingleInstance();
builder.Register(static c => MakoHttpOptions.CreateHttpMessageInvoker(c.Resolve<PixivApiNameResolver>()))
_ = builder.Register(static c => MakoHttpOptions.CreateHttpMessageInvoker(c.Resolve<PixivApiNameResolver>()))
.Keyed<HttpMessageInvoker>(typeof(PixivApiNameResolver))
.As<HttpMessageInvoker>()
.SingleInstance();
builder.Register(static c => MakoHttpOptions.CreateHttpMessageInvoker(c.Resolve<PixivImageNameResolver>()))
_ = builder.Register(static c => MakoHttpOptions.CreateHttpMessageInvoker(c.Resolve<PixivImageNameResolver>()))
.Keyed<HttpMessageInvoker>(typeof(PixivImageNameResolver))
.As<HttpMessageInvoker>()
.SingleInstance();
builder.Register(static _ => MakoHttpOptions.CreateDirectHttpMessageInvoker())
_ = builder.Register(static _ => MakoHttpOptions.CreateDirectHttpMessageInvoker())
.Keyed<HttpMessageInvoker>(typeof(LocalMachineNameResolver))
.As<HttpMessageInvoker>()
.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
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
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
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
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

View File

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

View File

@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion
namespace Pixeval.CoreApi.Model;
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
//
// Pixeval/Pixeval.CoreApi
@ -18,7 +18,6 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion
namespace Pixeval.CoreApi.Net;
/// <summary>
@ -30,4 +29,4 @@ public enum MakoApiKind
WebApi,
AuthApi,
ImageApi
}
}

View File

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

View File

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

View File

@ -30,7 +30,7 @@ namespace Pixeval.SourceGen;
[Generator]
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 SettingMetadataAttributeFqName = "Pixeval.Attributes.SettingMetadata";
private const string SettingEntryFqName = "global::Pixeval.SettingEntry";
@ -42,7 +42,7 @@ public class SettingsEntryGenerator : IIncrementalGenerator
transform: static (ctx, _) =>
{
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))
.Select(property => (property, property.GetAttribute(ctx.SemanticModel, SettingMetadataAttributeFqName)))
.Where(tuple => tuple.Item2 is not null))
@ -96,8 +96,8 @@ public class SettingsEntryGenerator : IIncrementalGenerator
ctx.ReportDiagnostic(
Diagnostic.Create(new DiagnosticDescriptor(
"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",
DiagnosticSeverity.Error,
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
{
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)]
public static T? FirstOrNull<T>(this IEnumerable<T> enumerable) where T : struct
{
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)
@ -183,7 +183,7 @@ public static class Enumerates
public static void ReplaceByUpdate<T>(this IList<T> dest, IEnumerable<T> source)
{
var enumerable = source as T[] ?? source.ToArray();
if (enumerable.Any())
if (enumerable.Length != 0)
{
_ = dest.RemoveAll(x => !enumerable.Contains(x));
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)
{
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.AddRange(enumerable);

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval.Utilities
#region Copyright (c) Pixeval/Pixeval.Utilities
// GPL v3 License
//
// Pixeval/Pixeval.Utilities
@ -117,7 +117,7 @@ public class ObservableHashSet<T>
void ICollection<T>.Add(T item)
{
Add(item);
_ = Add(item);
}
/// <summary>
@ -183,7 +183,7 @@ public class ObservableHashSet<T>
OnCountPropertyChanging();
_set.Remove(item);
_ = _set.Remove(item);
OnCollectionChanged(NotifyCollectionChangedAction.Remove, item);
@ -233,7 +233,7 @@ public class ObservableHashSet<T>
OnCountPropertyChanging();
_set.Add(item);
_ = _set.Add(item);
OnCollectionChanged(NotifyCollectionChangedAction.Add, item);
@ -555,5 +555,5 @@ internal static class ObservableHashSetSingletons
public static readonly PropertyChangedEventArgs CountPropertyChanged = 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>
{
private readonly HashSet<object> _keys = new();
private readonly HashSet<object> _keys = [];
public T Value { get; init; }

View File

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

View File

@ -93,7 +93,7 @@ public class ReenterableAwaiter(bool initialSignal) : INotifyCompletion
}
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
{
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 readonly List<IAppActivationHandler> FeatureHandlers = new();
public static readonly List<IAppActivationHandler> FeatureHandlers = [];
static ActivationRegistrar()
{
@ -39,7 +39,7 @@ public static class ActivationRegistrar
if (args is { Kind: ExtendedActivationKind.Protocol, Data: IProtocolActivatedEventArgs { Uri: var activationUri } } &&
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()
{
WeakReferenceMessenger.Default.Send(new ApplicationExitingMessage());
_ = WeakReferenceMessenger.Default.Send(new ApplicationExitingMessage());
CurrentContext.App.Exit();
}
}

View File

@ -56,7 +56,7 @@ public static partial class AppContext
public static readonly string AppVersion = GitVersionInformation.AssemblySemVer;
private static readonly ApplicationDataContainer SessionContainer;
private static readonly ApplicationDataContainer _sessionContainer;
private static SoftwareBitmapSource? _imageNotAvailable;
@ -70,14 +70,14 @@ public static partial class AppContext
{
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
// For more detailed information see https://docs.microsoft.com/en-us/windows/apps/design/app-settings/store-and-retrieve-app-data
InitializeConfigurationContainer();
SessionContainer = ApplicationData.Current.LocalSettings.Containers[SessionContainerKey];
_sessionContainer = ApplicationData.Current.LocalSettings.Containers[SessionContainerKey];
}
public static async Task<SoftwareBitmapSource> GetNotAvailableImageAsync()
@ -160,7 +160,7 @@ public static partial class AppContext
using var scope = App.AppViewModel.AppServicesScope;
var downloadHistoryManager = scope.ServiceProvider.GetRequiredService<DownloadHistoryPersistentManager>();
// 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.Created ||
entry.State == DownloadState.Paused);
@ -201,7 +201,7 @@ public static partial class AppContext
{
if (App.AppViewModel.MakoClient.Session is { } session)
{
var values = SessionContainer.Values;
var values = _sessionContainer.Values;
values[nameof(Session.AccessToken)] = session.AccessToken;
values[nameof(Session.Account)] = session.Account;
values[nameof(Session.AvatarUrl)] = session.AvatarUrl;
@ -219,7 +219,7 @@ public static partial class AppContext
{
try
{
var values = SessionContainer.Values;
var values = _sessionContainer.Values;
return new Session
{
AccessToken = values[nameof(Session.AccessToken)].CastOrThrow<string>(),

View File

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

View File

@ -88,7 +88,7 @@ public class AppViewModel(App app) : AutoActivateObservableRecipient, IRecipient
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)

View File

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

View File

@ -22,4 +22,4 @@ using System;
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 WinUI3Utilities.Attributes;
namespace Pixeval.Controls.IllustratorView;
[TemplatePart(Name = PartContentContainer, Type = typeof(CardControl))]

View File

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

View File

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

View File

@ -42,12 +42,12 @@ public class DownloadHistoryPersistentManager(ILiteDatabase collection, int maxi
Purge(MaximumRecords);
}
Collection.Insert(t);
_ = Collection.Insert(t);
t.PropertyChanged += (_, _) =>
{
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)
{
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()
{
Collection.DeleteAll();
_ = Collection.DeleteAll();
App.AppViewModel.DownloadManager.ClearTasks();
}

View File

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

View File

@ -47,7 +47,7 @@ public abstract class SimplePersistentManager<T>(ILiteDatabase db, int maximumRe
Purge(MaximumRecords);
}
Collection.Insert(t);
_ = Collection.Insert(t);
}
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)
{
var last = Collection.FindAll().Take(^limit..).ToHashSet();
Delete(e => !last.Contains(e!));
_ = Delete(e => !last.Contains(e!));
}
}
public void Clear()
{
Collection.DeleteAll();
_ = Collection.DeleteAll();
}
}

View File

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

View File

@ -43,6 +43,6 @@ public sealed partial class ReverseSearchApiKeyNotPresentDialog
private void SetApiKeyHyperlinkButton_OnTapped(object sender, TappedRoutedEventArgs e)
{
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 var ugoiraStream = await IOHelper.GetStreamFromZipStreamAsync(stream.AsStreamForRead(), _metadata);
await IOHelper.CreateAndWriteToFileAsync(ugoiraStream, Destination);
using var ugoiraStream = await IoHelper.GetStreamFromZipStreamAsync(stream.AsStreamForRead(), _metadata);
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)
{
_httpClient = httpClient ?? new HttpClient();
_queuedTasks = new();
_queuedTasks = [];
_taskQuerySet = new HashSet<TDownloadTask>();
_throttle = new(true, true);
_downloadTaskChannel = Channel.CreateUnbounded<TDownloadTask>();
@ -79,7 +79,7 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
return;
}
_taskQuerySet.Add(task);
_ = _taskQuerySet.Add(task);
_queuedTasks.Add(task);
// Start the task only if it is created and is ready-to-run
if (task.CurrentState == DownloadState.Created)
@ -102,8 +102,8 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
public void RemoveTask(TDownloadTask task)
{
_taskQuerySet.Remove(task);
_queuedTasks.Remove(task);
_ = _taskQuerySet.Remove(task);
_ = _queuedTasks.Remove(task);
}
public void ClearTasks()
@ -134,7 +134,7 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
private void QueueDownloadTask(TDownloadTask task)
{
_downloadTaskChannel.Writer.WriteAsync(task);
_ = _downloadTaskChannel.Writer.WriteAsync(task);
}
private async Task Download(TDownloadTask task)
@ -161,10 +161,10 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
private async Task DecrementCounterAsync()
{
Interlocked.Decrement(ref _workingTasks);
_ = Interlocked.Decrement(ref _workingTasks);
await _semaphoreSlim.WaitAsync();
_throttle.SetResult(true);
_semaphoreSlim.Release();
_ = _semaphoreSlim.Release();
}
private async Task DownloadInternal(TDownloadTask task)
@ -187,7 +187,7 @@ public class DownloadManager<TDownloadTask> : IDisposable where TDownloadTask :
{
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;
case Result<IRandomAccessStream>.Failure(var exception):
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);
SetState(task, DownloadState.Error);

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval
#region Copyright (c) Pixeval/Pixeval
// GPL v3 License
//
// Pixeval/Pixeval
@ -19,7 +19,6 @@
#endregion
using System;
using System.Runtime.Serialization;
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)
{
}
@ -40,4 +35,4 @@ public class DownloadTaskInitializationException : Exception
public DownloadTaskInitializationException(string? message, Exception? innerException) : base(message, innerException)
{
}
}
}

View File

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

View File

@ -41,11 +41,11 @@ public class IllustrationDownloadTaskFactory : IDownloadTaskFactory<Illustration
{
using var scope = App.AppViewModel.AppServicesScope;
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())
{
// delete the original entry
manager.Delete(entry => entry.Destination == path);
_ = manager.Delete(entry => entry.Destination == path);
}
var task = Functions.Block<ObservableDownloadTask>(() =>

View File

@ -25,22 +25,16 @@ using Pixeval.UserControls.IllustrationView;
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>
/// 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 IRandomAccessStream Stream { get; } = imageStream;
public override async void DownloadStarting(DownloadStartingEventArgs args)
{
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)
{
var metadata = await App.AppViewModel.MakoClient.GetUgoiraMetadataAsync(_illustId);
using var ugoiraStream = await IOHelper.GetStreamFromZipStreamAsync(stream.AsStreamForRead(), metadata);
await IOHelper.CreateAndWriteToFileAsync(ugoiraStream, Destination);
using var ugoiraStream = await IoHelper.GetStreamFromZipStreamAsync(stream.AsStreamForRead(), metadata);
await IoHelper.CreateAndWriteToFileAsync(ugoiraStream, Destination);
}
}

View File

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

View File

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

View File

@ -104,12 +104,12 @@ public class MacroParser<TContext>
private Macro<TContext> Macro()
{
EatToken(TokenKind.At);
EatToken(TokenKind.LBrace);
_ = EatToken(TokenKind.At);
_ = EatToken(TokenKind.LBrace);
var macroName = PlainText();
_expectContextualColon = true;
var node = new Macro<TContext>(macroName, OptionalMacroParameter());
EatToken(TokenKind.RBrace);
_ = EatToken(TokenKind.RBrace);
return node;
}
@ -128,7 +128,7 @@ public class MacroParser<TContext>
throw new MacroParseException(MacroParserResources.UnexpectedTokenFormatted.Format(_currentToken.Position.Start));
}
EatToken(TokenKind.Colon);
_ = EatToken(TokenKind.Colon);
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)
{
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)
{
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)
{
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)
{
ReplyBar.FindDescendant<RichEditBox>()?.Focus(FocusState.Programmatic);
_ = (ReplyBar.FindDescendant<RichEditBox>()?.Focus(FocusState.Programmatic));
}
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)
{
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
//
// Pixeval/Pixeval
@ -19,7 +19,6 @@
#endregion
using System;
using System.Runtime.Serialization;
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)
{
}
@ -40,4 +35,4 @@ public class IllustrationSourceNotFoundException : Exception
public IllustrationSourceNotFoundException(string? message, Exception? innerException) : base(message, innerException)
{
}
}
}

View File

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

View File

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

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval
#region Copyright (c) Pixeval/Pixeval
// GPL v3 License
//
// 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)
{
}
@ -43,4 +39,4 @@ public class LoginProxyException : Exception
public LoginProxyException(string? message, Exception? innerException) : base(message, innerException)
{
}
}
}

View File

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

View File

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

View File

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

View File

@ -50,7 +50,7 @@ public sealed partial class BookmarksPage : ISortedIllustrationContainerPageHelp
{
PrivacyPolicyComboBox.SelectedItem = PrivacyPolicyComboBoxPublicItem;
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();
}

View File

@ -62,7 +62,7 @@ public sealed partial class FollowingsPage
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));
}
@ -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)
{
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;
await ThreadingHelper.SpinWaitAsync(() => !ViewModel.DataProvider.Source.Any() && !ViewModel.HasNoItems);
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();
RankOptionComboBox.SelectedItem = LocalizedBoxHelper.Of<RankOption, RankOptionWrapper>(RankOption.Day);
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();
}

View File

@ -50,7 +50,7 @@ public sealed partial class RecentPostsPage : ISortedIllustrationContainerPageHe
{
PrivacyPolicyComboBox.SelectedItem = PrivacyPolicyComboBoxPublicItem;
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();
}

View File

@ -52,7 +52,7 @@ public sealed partial class RecommendationPage : ISortedIllustrationContainerPag
{
ModeSelectionComboBox.SelectedItem = ModeSelectionComboBoxIllustComboBoxItem;
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();
}

View File

@ -50,7 +50,7 @@ public sealed partial class SearchResultsPage : ISortedIllustrationContainerPage
{
SortOptionComboBox.SelectedItem = MakoHelper.GetAppSettingDefaultSortOptionWrapper();
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)

View File

@ -78,7 +78,7 @@ public sealed partial class DownloadListEntry
case DownloadState.Error:
case DownloadState.Cancelled:
case DownloadState.Completed:
await Launcher.LaunchUriAsync(new(ViewModel.DownloadTask.Destination));
_ = await Launcher.LaunchUriAsync(new(ViewModel.DownloadTask.Destination));
break;
case DownloadState.Paused:
ViewModel.DownloadTask.CancellationHandle.Resume();
@ -101,14 +101,14 @@ public sealed partial class DownloadListEntry
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 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();
}
}

View File

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

View File

@ -107,7 +107,7 @@ public sealed partial class DownloadListPage
{
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);
}
private void DownloadListEntryOnEffectiveViewportChanged(FrameworkElement sender, EffectiveViewportChangedEventArgs args)
{
var context = sender.GetDataContext<IllustrationViewModel>();

View File

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

View File

@ -51,7 +51,7 @@ public sealed partial class CommentsPage
public override void OnPageActivated(NavigationEventArgs e)
{
// 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();
WeakReferenceMessenger.Default.UnregisterAll(this);

View File

@ -52,7 +52,7 @@ public sealed partial class IllustrationInfoPage
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)
@ -64,7 +64,7 @@ public sealed partial class IllustrationInfoPage
{
if (_viewModel.Illustrator is { } userInfo)
{
ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ForwardConnectedAnimation", (UIElement)sender);
_ = ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ForwardConnectedAnimation", (UIElement)sender);
// todo IllustratorPage use Navigate
// 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:
{
Window.ShowShareUI();
Window.ShowShareUi();
break;
}
case nameof(IllustrationViewerPageViewModel.IsInfoPaneOpen):

View File

@ -359,7 +359,7 @@ public partial class IllustrationViewerPageViewModel : DetailedObservableObject,
RestoreResolutionCommand.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.ExecuteRequested += PlayGifCommandOnExecuteRequested;
@ -461,13 +461,13 @@ public partial class IllustrationViewerPageViewModel : DetailedObservableObject,
GenerateLinkTeachingTip.IsOpen = true;
}
UIHelper.ClipboardSetText(MakoHelper.GenerateIllustrationAppUri(CurrentIllustration.Id).ToString());
UiHelper.ClipboardSetText(MakoHelper.GenerateIllustrationAppUri(CurrentIllustration.Id).ToString());
}
private void GenerateWebLinkCommandOnExecuteRequested(XamlUICommand sender, ExecuteRequestedEventArgs args)
{
var link = MakoHelper.GenerateIllustrationWebUri(CurrentIllustration.Id).ToString();
UIHelper.ClipboardSetText(link);
UiHelper.ClipboardSetText(link);
SnackBarTeachingTip.ShowAndHide(IllustrationViewerPageResources.WebLinkCopiedToClipboardToastTitle);
}
@ -484,7 +484,7 @@ public partial class IllustrationViewerPageViewModel : DetailedObservableObject,
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;
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));
visualizer.Illustrations = collection;
await collection.LoadMoreItemsAsync(20);
_ = await collection.LoadMoreItemsAsync(20);
visualizer.Illustrations.CollectionChanged += CollectionChanged;
return visualizer.Illustrations.Count > 0;
}
@ -48,7 +48,7 @@ public class IllustrationVisualizationController(IIllustrationVisualizer visuali
public async Task FillAsync(IFetchEngine<Illustration?>? newEngine, int itemsLimit = -1)
{
FetchEngine = newEngine;
await FillAsync(itemsLimit);
_ = await FillAsync(itemsLimit);
}
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;
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 });
}
@ -158,10 +158,7 @@ public partial class ImageViewerPageViewModel : ObservableObject, IDisposable
_disposed = false;
const ThumbnailUrlOption option = ThumbnailUrlOption.Medium;
_ = IllustrationViewModel.TryLoadThumbnail(this, option).ContinueWith(
_ =>
{
OriginalImageSources ??= new[] { IllustrationViewModel.ThumbnailStreams[option] };
},
_ => OriginalImageSources ??= [IllustrationViewModel.ThumbnailStreams[option]],
TaskScheduler.FromCurrentSynchronizationContext());
AddHistory();
await LoadOriginalImage();
@ -198,7 +195,7 @@ public partial class ImageViewerPageViewModel : ObservableObject, IDisposable
{
case Result<Stream>.Success(var zipStream):
AdvancePhase(LoadingPhase.MergingGifFrames);
OriginalImageSources = await IOHelper.GetStreamsFromZipStreamAsync(zipStream);
OriginalImageSources = await IoHelper.GetStreamsFromZipStreamAsync(zipStream);
MsIntervals = ugoiraMetadata.UgoiraMetadataInfo.Frames?.Select(x => (int)x.Delay)?.ToList();
break;
case Result<Stream>.Failure(OperationCanceledException):

View File

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

View File

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

View File

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

View File

@ -41,7 +41,7 @@ public sealed partial class RelatedWorksPage
public override async void OnPageActivated(NavigationEventArgs e)
{
// 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();
WeakReferenceMessenger.Default.UnregisterAll(this);

View File

@ -93,8 +93,8 @@ public sealed partial class IllustratorPage
switch (navigationEventArgs.Parameter)
{
case (UIElement sender, IllustratorViewModel viewModel):
WeakReferenceMessenger.Default.Send(new MainPageFrameSetConnectedAnimationTargetMessage(sender));
ConnectedAnimationService.GetForCurrentView().GetAnimation("ForwardConnectedAnimation")?.TryStart(ProfileImage);
_ = WeakReferenceMessenger.Default.Send(new MainPageFrameSetConnectedAnimationTargetMessage(sender));
_ = (ConnectedAnimationService.GetForCurrentView().GetAnimation("ForwardConnectedAnimation")?.TryStart(ProfileImage));
_viewModel = viewModel;
break;
case IllustratorViewModel viewModel1:
@ -102,7 +102,7 @@ public sealed partial class IllustratorPage
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();
}
@ -217,7 +217,7 @@ public sealed partial class IllustratorPage
public void GoBack()
{
ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ForwardConnectedAnimation", ProfileImage);
_ = ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ForwardConnectedAnimation", ProfileImage);
Parent.To<Frame>().GoBack(new SuppressNavigationTransitionInfo());
}
@ -228,7 +228,7 @@ public sealed partial class IllustratorPage
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)

View File

@ -61,7 +61,7 @@ public sealed partial class LoginPage
}
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)
{
@ -101,7 +101,7 @@ public sealed partial class LoginPage
LoginPageResources.WebView2InstallationRequiredContent).ShowAsync();
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();

View File

@ -152,7 +152,7 @@ public partial class LoginPageViewModel : AutoActivateObservableRecipient
}
else
{
await MessageDialogBuilder.CreateAcknowledgement(
_ = await MessageDialogBuilder.CreateAcknowledgement(
CurrentContext.Window,
LoginPageResources.RefreshingSessionIsNotPresentTitle,
LoginPageResources.RefreshingSessionIsNotPresentContent)
@ -188,10 +188,7 @@ public partial class LoginPageViewModel : AutoActivateObservableRecipient
await WebView.LoginWebView2.EnsureCoreWebView2Async();
WebView.LoginWebView2.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);
WebView.LoginWebView2.CoreWebView2.WebResourceRequested += (_, args) =>
{
args.Request.Headers.SetHeader("Accept-Language", args.Request.Uri.Contains("recaptcha") ? "zh-cn" : CultureInfo.CurrentUICulture.Name);
};
WebView.LoginWebView2.CoreWebView2.WebResourceRequested += (_, args) => args.Request.Headers.SetHeader("Accept-Language", args.Request.Uri.Contains("recaptcha") ? "zh-cn" : CultureInfo.CurrentUICulture.Name);
var verifier = PixivAuthSignature.GetCodeVerify();
WebView.LoginWebView2.Source = new Uri(PixivAuthSignature.GenerateWebPageUrl(verifier));
@ -221,7 +218,7 @@ public partial class LoginPageViewModel : AutoActivateObservableRecipient
("grant_type", "authorization_code"),
("include_policy", "true"),
("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
{
Cookie = cookie,

View File

@ -1,4 +1,4 @@
#region Copyright (c) Pixeval/Pixeval
#region Copyright (c) Pixeval/Pixeval
// GPL v3 License
//
// Pixeval/Pixeval
@ -33,7 +33,7 @@ public static class PixivAuthSignature
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)
@ -48,4 +48,4 @@ public static class PixivAuthSignature
{
return SHA256.HashData(Encoding.ASCII.GetBytes(code)).ToUrlSafeBase64String();
}
}
}

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