Skip to content

Commit

Permalink
Major CodeQA - 20250119 (#673)
Browse files Browse the repository at this point in the history
# Main Goal
This PR contains huge CodeQA and some code refactoring for some
functionalities, which hopefully improve the maintainability of the
codebase further.

## What's changed?
- **[Imp]** CodeQA based on Qodana and ReSharper suggestions
- **[New]** Introducing ``Hash`` extension for hashing ``FileStream``,
``string``, ``Span<T>`` and ``FileInfo`` with both synchronous and
asynchronous version of the methods. The methods uses generic type of
any member of ``HashAlgorithm`` (Such as: ``MD5``, ``SHA*``,
``HMACSHA*``, etc.) and ``NonCryptographicHashAlgorithm`` (Such as:
``Crc32``, ``XxHash*``, etc.) to specify which kind of hash to be used.
- **[Imp]** Separating ``InternalAppJSONContext`` members into its own
``JsonContext``es.
- **[Imp]** Update H.NotifyIcon to work with CsWin32 v0.3.162.
- **[Imp]** Update NuGet packages.
- **[Imp]** Recompile and Update StaticLibs for NativeAOT libraries
link.
- Update Rust compiler for ``csharp_bindings`` to rustc 1.84.0
(9fc6b4312 2025-01-07) (Stable)
- Remove dependency to ``MSVCRT`` library (Manual VC++ 2019/2022 Redist
installation should no longer be needed) and fully utilize ``UCRT`` as
its runtime library.
- Update libwebp libraries to:
https://github.com/webmproject/libwebp/tree/f8f241071001e1a3807f34a26a03a742ea843458
  - Favor speed + inline optimizaton build (/O2 + /Ob2 + /Oi + /Ot)
- Recompile all static libraries using Microsoft Visual C++ 2022
(19.43.34618) compiler.
  - Optimize Rust library, ``csharp_bindings`` to use full LTO.
- **[Imp]** Update Hi3Helper.Sophon submodule.

## PR Status :
- Overall Status : Done
- Commits : Done
- Synced to base (Collapse:main) : Not yet
- Build status : OK
- Crashing : No
- Bug found caused by PR : {int}

### Templates

<details>
  <summary>Changelog Prefixes</summary>
  
  ```
    **[New]**
    **[Imp]**
    **[Fix]**
    **[Loc]**
    **[Doc]**
  ```

</details>
  • Loading branch information
neon-nyan authored Jan 26, 2025
2 parents 381e4a4 + c1a666e commit 1b2d110
Show file tree
Hide file tree
Showing 328 changed files with 10,305 additions and 9,693 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
packages/*

CollapseLauncher/Deps/*
CollapseLauncher/StaticLib/*.lib
CollapseLauncher/StaticLib/**/*.lib
CollapseLauncher/Invoker/*
**/Generated Files/**
*.psd
Expand Down
13 changes: 6 additions & 7 deletions CollapseLauncher/App.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:animatedvisuals="using:Microsoft.UI.Xaml.Controls.AnimatedVisuals"
xmlns:conv="using:CollapseLauncher.Pages"
xmlns:interactions="using:Microsoft.Xaml.Interactions.Core"
xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:controls="using:Microsoft.UI.Xaml.Controls"
xmlns:primitives="using:Microsoft.UI.Xaml.Controls.Primitives"
Expand Down Expand Up @@ -2190,13 +2189,13 @@
<!-- Force ShouldConstrainToRootBounds to True -->
<!-- Fix https://github.com/microsoft/microsoft-ui-xaml/issues/8657 -->
<interactivity:Interaction.Behaviors>
<interactions:DataTriggerBehavior Binding="{Binding ShouldConstrainToRootBounds, ElementName=Popup}"
<interactivity:DataTriggerBehavior Binding="{Binding ShouldConstrainToRootBounds, ElementName=Popup}"
ComparisonCondition="Equal"
Value="False">
<interactions:ChangePropertyAction PropertyName="ShouldConstrainToRootBounds"
<interactivity:ChangePropertyAction PropertyName="ShouldConstrainToRootBounds"
TargetObject="{Binding ElementName=Popup}"
Value="True" />
</interactions:DataTriggerBehavior>
</interactivity:DataTriggerBehavior>
</interactivity:Interaction.Behaviors>
<Border x:Name="PopupBorder"
Margin="0,-0.5,0,-1"
Expand Down Expand Up @@ -2627,13 +2626,13 @@
<!-- Force ShouldConstrainToRootBounds to True -->
<!-- Fix https://github.com/microsoft/microsoft-ui-xaml/issues/8657 -->
<interactivity:Interaction.Behaviors>
<interactions:DataTriggerBehavior Binding="{Binding ShouldConstrainToRootBounds, ElementName=Popup}"
<interactivity:DataTriggerBehavior Binding="{Binding ShouldConstrainToRootBounds, ElementName=Popup}"
ComparisonCondition="Equal"
Value="False">
<interactions:ChangePropertyAction PropertyName="ShouldConstrainToRootBounds"
<interactivity:ChangePropertyAction PropertyName="ShouldConstrainToRootBounds"
TargetObject="{Binding ElementName=Popup}"
Value="True" />
</interactions:DataTriggerBehavior>
</interactivity:DataTriggerBehavior>
</interactivity:Interaction.Behaviors>
<Border x:Name="PopupBorder"
Margin="0,-0.5,0,-1"
Expand Down
11 changes: 7 additions & 4 deletions CollapseLauncher/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,23 @@
using Windows.UI;
using static CollapseLauncher.InnerLauncherConfig;
using static Hi3Helper.Logger;
// ReSharper disable SwitchStatementMissingSomeEnumCasesNoDefault
// ReSharper disable CommentTypo
// ReSharper disable StringLiteralTypo

namespace CollapseLauncher
{
public partial class App
{
public static bool IsAppKilled = false;
public static bool IsAppKilled { get; set; } = false;

Check warning on line 25 in CollapseLauncher/App.xaml.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Auto-property accessor is never used (non-private accessibility)

Auto-property accessor 'IsAppKilled.get' is never used

Check warning

Code scanning / QDNET

Auto-property accessor is never used (non-private accessibility) Warning

Auto-property accessor 'IsAppKilled.get' is never used

public App()
{
if (DebugSettings != null)
{
#if ENABLEFRAMECOUNTER
#if ENABLEFRAMECOUNTER
DebugSettings.EnableFrameRateCounter = true;
#endif
#endif
#if DEBUG
DebugSettings.LayoutCycleDebugBreakLevel = LayoutCycleDebugBreakLevel.High;
DebugSettings.LayoutCycleTracingLevel = LayoutCycleTracingLevel.High;
Expand Down Expand Up @@ -68,7 +71,7 @@ public App()
RequestedTheme = IsAppThemeLight ? ApplicationTheme.Light : ApplicationTheme.Dark;
PInvoke.SetPreferredAppMode(PInvoke.ShouldAppsUseDarkMode() ? PreferredAppMode.AllowDark : PreferredAppMode.Default);

this.InitializeComponent();
InitializeComponent();
}

protected override void OnLaunched(LaunchActivatedEventArgs args)
Expand Down
112 changes: 60 additions & 52 deletions CollapseLauncher/Classes/CachesManagement/Honkai/Check.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using CollapseLauncher.Interfaces;
using Hi3Helper;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand All @@ -10,6 +11,7 @@
using System.Threading.Tasks;
using static Hi3Helper.Locale;
using static Hi3Helper.Logger;
// ReSharper disable CommentTypo

namespace CollapseLauncher
{
Expand All @@ -18,20 +20,20 @@ internal partial class HonkaiCache
private async Task<List<CacheAsset>> Check(List<CacheAsset> assetIndex, CancellationToken token)
{
// Initialize asset index for the return
List<CacheAsset> returnAsset = new List<CacheAsset>();
List<CacheAsset> returnAsset = [];

// Set Indetermined status as false
_status.IsProgressAllIndetermined = false;
Status.IsProgressAllIndetermined = false;

// Show the asset entry panel
_status.IsAssetEntryPanelShow = true;
Status.IsAssetEntryPanelShow = true;

try
{
// Create the cache directory if it doesn't exist
if (!Directory.Exists(_gamePath))
if (!Directory.Exists(GamePath))
{
Directory.CreateDirectory(_gamePath!);
Directory.CreateDirectory(GamePath!);
}

// Check for unused files
Expand All @@ -40,7 +42,7 @@ private async Task<List<CacheAsset>> Check(List<CacheAsset> assetIndex, Cancella
// Do check in parallelization.
await Parallel.ForEachAsync(assetIndex!, new ParallelOptions
{
MaxDegreeOfParallelism = _threadCount,
MaxDegreeOfParallelism = ThreadCount,
CancellationToken = token
}, async (asset, localToken) =>
{
Expand All @@ -56,10 +58,19 @@ private async Task<List<CacheAsset>> Check(List<CacheAsset> assetIndex, Cancella
return returnAsset;
}

private readonly SearchValues<string> _unusedSearchValues = SearchValues.Create([
"output_log",
"Crashes",
"Verify.txt",
"APM",
"FBData",
"asb.dat"
], StringComparison.OrdinalIgnoreCase);

private void CheckUnusedAssets(List<CacheAsset> assetIndex, List<CacheAsset> returnAsset)
{
// Directory info and if the directory doesn't exist, return
DirectoryInfo directoryInfo = new DirectoryInfo(_gamePath);
DirectoryInfo directoryInfo = new DirectoryInfo(GamePath);
if (!directoryInfo.Exists)
{
return;
Expand All @@ -69,54 +80,51 @@ private void CheckUnusedAssets(List<CacheAsset> assetIndex, List<CacheAsset> ret
foreach (FileInfo fileInfo in directoryInfo.EnumerateFiles("*", SearchOption.AllDirectories)
.EnumerateNoReadOnly())
{
string filePath = fileInfo.FullName;

if (!filePath.Contains("output_log", StringComparison.OrdinalIgnoreCase)
&& !filePath.Contains("Crashes", StringComparison.OrdinalIgnoreCase)
&& !filePath.Contains("Verify.txt", StringComparison.OrdinalIgnoreCase)
&& !filePath.Contains("APM", StringComparison.OrdinalIgnoreCase)
&& !filePath.Contains("FBData", StringComparison.OrdinalIgnoreCase)
&& !filePath.Contains("asb.dat", StringComparison.OrdinalIgnoreCase)
&& !assetIndex.Exists(x => x.ConcatPath == fileInfo.FullName))
ReadOnlySpan<char> filePath = fileInfo.FullName;

if (filePath.ContainsAny(_unusedSearchValues)
|| assetIndex.Exists(x => x.ConcatPath == fileInfo.FullName))
{
// Increment the total found count
_progressAllCountFound++;

// Add asset to the returnAsset
CacheAsset asset = new CacheAsset()
{
BasePath = Path.GetDirectoryName(filePath),
N = Path.GetFileName(filePath),
DataType = CacheAssetType.Unused,
CS = fileInfo.Length,
CRC = null,
Status = CacheAssetStatus.Unused,
IsUseLocalPath = true
};
returnAsset!.Add(asset);

// Add to asset entry display
Dispatch(() => AssetEntry!.Add(new AssetProperty<CacheAssetType>(
asset.N,
asset.DataType,
asset.BasePath,
asset.CS,
null,
null
))
);

LogWriteLine($"File: {asset.ConcatPath} is unused!", LogType.Warning, true);
continue;
}

// Increment the total found count
ProgressAllCountFound++;

// Add asset to the returnAsset
CacheAsset asset = new CacheAsset
{
BasePath = Path.GetDirectoryName(fileInfo.FullName),
N = Path.GetFileName(fileInfo.FullName),
DataType = CacheAssetType.Unused,
CS = fileInfo.Length,
CRC = null,
Status = CacheAssetStatus.Unused,
IsUseLocalPath = true
};
returnAsset!.Add(asset);

// Add to asset entry display
Dispatch(() => AssetEntry!.Add(new AssetProperty<CacheAssetType>(
asset.N,
asset.DataType,
asset.BasePath,
asset.CS,
null,
null
))
);

LogWriteLine($"File: {asset.ConcatPath} is unused!", LogType.Warning, true);
}
}

private async ValueTask CheckAsset(CacheAsset asset, List<CacheAsset> returnAsset, CancellationToken token)
{
// Increment the count and update the status
Interlocked.Add(ref _progressAllCountCurrent, 1);
_status.ActivityStatus = string.Format(Lang!._CachesPage!.CachesStatusChecking!, asset!.DataType, asset.N);
_status.ActivityAll = string.Format(Lang._CachesPage.CachesTotalStatusChecking!, _progressAllCountCurrent, _progressAllCountTotal);
Interlocked.Add(ref ProgressAllCountCurrent, 1);
Status.ActivityStatus = string.Format(Lang!._CachesPage!.CachesStatusChecking!, asset!.DataType, asset.N);
Status.ActivityAll = string.Format(Lang._CachesPage.CachesTotalStatusChecking!, ProgressAllCountCurrent, ProgressAllCountTotal);

// Assign the file info.
FileInfo fileInfo = new FileInfo(asset.ConcatPath).EnsureNoReadOnly(out bool isExist);
Expand All @@ -136,15 +144,15 @@ private async ValueTask CheckAsset(CacheAsset asset, List<CacheAsset> returnAsse
}

// Skip CRC check if fast method is used
if (_useFastMethod)
if (UseFastMethod)
{
return;
}

// If above passes, then run the CRC check
await using FileStream fs = await NaivelyOpenFileStreamAsync(fileInfo, FileMode.Open, FileAccess.Read, FileShare.Read);
// Calculate the asset CRC (SHA1)
byte[] hashArray = await GetCryptoHashAsync<HMACSHA1>(fs, _gameSalt, true, true, token);
byte[] hashArray = await GetCryptoHashAsync<HMACSHA1>(fs, GameSalt, true, true, token);

// If the asset CRC doesn't match, then add the file to asset index.
if (!IsArrayMatch(asset.CRCArray, hashArray))
Expand All @@ -159,9 +167,9 @@ private void AddGenericCheckAsset(CacheAsset asset, CacheAssetStatus assetStatus
lock (this)
{
// Set Indetermined status as false
_status.IsProgressAllIndetermined = false;
_progressAllCountFound++;
_progressAllSizeFound += asset!.CS;
Status.IsProgressAllIndetermined = false;
ProgressAllCountFound++;
ProgressAllSizeFound += asset!.CS;
}

// Add file into asset index
Expand Down
Loading

0 comments on commit 1b2d110

Please sign in to comment.