Skip to content

Commit

Permalink
Preview 1.80.4 Hotfix Release #463 from CollapseLauncher/main
Browse files Browse the repository at this point in the history
  • Loading branch information
bagusnl authored May 9, 2024
2 parents 95acda8 + 1398a16 commit 110db3e
Show file tree
Hide file tree
Showing 18 changed files with 109 additions and 108 deletions.
2 changes: 1 addition & 1 deletion CollapseLauncher/Classes/CachesManagement/Honkai/Update.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ private async void _httpClient_UpdateAssetProgress(object sender, DownloadEvent
{
// Update current activity status
_status!.IsProgressTotalIndetermined = false;
string timeLeftString = string.Format(Lang!._Misc!.TimeRemainHMSFormat!, TimeSpan.FromSeconds((_progressTotalSizeCurrent - _progressTotalSize) / ConverterTool.Unzeroed(speed)));
string timeLeftString = string.Format(Lang!._Misc!.TimeRemainHMSFormat!, ((_progressTotalSizeCurrent - _progressTotalSize) / ConverterTool.Unzeroed(speed)).ToTimeSpanNormalized());
_status.ActivityTotal = string.Format(Lang!._Misc!.Downloading + ": {0}/{1} ", _progressTotalCountCurrent, _progressTotalCount)
+ string.Format($"({Lang._Misc.SpeedPerSec})", ConverterTool.SummarizeSizeSimple(speed))
+ $" | {timeLeftString}";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ private async void _httpClient_UpdateAssetProgress(object sender, DownloadEvent
{
// Update current activity status
_status.IsProgressTotalIndetermined = false;
string timeLeftString = string.Format(Lang._Misc.TimeRemainHMSFormat, TimeSpan.FromSeconds((_progressTotalSizeCurrent - _progressTotalSize) / ConverterTool.Unzeroed(speed)));
string timeLeftString = string.Format(Lang._Misc.TimeRemainHMSFormat, ((_progressTotalSizeCurrent - _progressTotalSize) / ConverterTool.Unzeroed(speed)).ToTimeSpanNormalized());
_status.ActivityTotal = string.Format(Lang._Misc.Downloading + ": {0}/{1} ", _progressTotalCountCurrent, _progressTotalCount)
+ string.Format($"({Lang._Misc.SpeedPerSec})", ConverterTool.SummarizeSizeSimple(speed))
+ $" | {timeLeftString}";
Expand Down
20 changes: 9 additions & 11 deletions CollapseLauncher/Classes/FileMigrationProcess/Events.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Hi3Helper;
using Hi3Helper.Data;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace CollapseLauncher
Expand All @@ -9,25 +10,22 @@ internal partial class FileMigrationProcess
{
private void UpdateCountProcessed(FileMigrationProcessUIRef uiRef, string currentPathProcessed)
{
lock (this) { this.CurrentFileCountMoved++; }
Interlocked.Add(ref this.CurrentFileCountMoved, 1);

string fileCountProcessedString = string.Format(Locale.Lang!._Misc!.PerFromTo!,
this.CurrentFileCountMoved,
this.TotalFileCount);
this.CurrentFileCountMoved,
this.TotalFileCount);

lock (uiRef.fileCountIndicatorSubtitle)
parentUI!.DispatcherQueue!.TryEnqueue(() =>
{
parentUI!.DispatcherQueue!.TryEnqueue(() =>
{
uiRef.fileCountIndicatorSubtitle.Text = fileCountProcessedString;
uiRef.pathActivitySubtitle.Text = currentPathProcessed;
});
}
uiRef.fileCountIndicatorSubtitle.Text = fileCountProcessedString;
uiRef.pathActivitySubtitle.Text = currentPathProcessed;
});
}

private async void UpdateSizeProcessed(FileMigrationProcessUIRef uiRef, long currentRead)
{
lock (this) { this.CurrentSizeMoved += currentRead; }
Interlocked.Add(ref this.CurrentSizeMoved, currentRead);

if (await CheckIfNeedRefreshStopwatch())
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.UI.Xaml;
using Hi3Helper.Shared.Region;
using Microsoft.UI.Xaml;
using System;
using System.Diagnostics;
using System.IO;
Expand Down Expand Up @@ -124,7 +125,11 @@ private async Task<string> MoveDirectory(FileMigrationProcessUIRef uiRef)

await Parallel.ForEachAsync(
inputPathInfo.EnumerateFiles("*", SearchOption.AllDirectories),
this.tokenSource?.Token ?? default,
new ParallelOptions
{
CancellationToken = this.tokenSource?.Token ?? default,
MaxDegreeOfParallelism = LauncherConfig.AppCurrentThread
},
async (inputFileInfo, cancellationToken) =>
{
int _parentInputPathLength = inputPathInfo.Parent!.FullName.Length + 1;
Expand All @@ -151,7 +156,7 @@ await Parallel.ForEachAsync(
FileInfo outputFileInfo = new FileInfo(outputTargetPath);
await MoveWriteFile(uiRef, inputFileInfo, outputFileInfo, cancellationToken);
}
});
}).ConfigureAwait(false);

inputPathInfo.Delete(true);
return outputDirPath;
Expand Down
96 changes: 43 additions & 53 deletions CollapseLauncher/Classes/FileMigrationProcess/IO.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using Hi3Helper.Data;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Buffers;
using System.IO;
using System.Linq;
using System.Threading;
Expand All @@ -21,71 +20,62 @@ private async Task MoveWriteFile(FileMigrationProcessUIRef uiRef, FileInfo input
if (inputFile!.Length < bufferSize)
bufferSize = (int)inputFile.Length;

bool isUseArrayPool = Environment.ProcessorCount * bufferSize > 2 << 20;
byte[] buffer = isUseArrayPool ? ArrayPool<byte>.Shared.Rent(bufferSize) : new byte[bufferSize];
byte[] buffer = new byte[bufferSize];

try
await using (FileStream inputStream = inputFile.OpenRead())
await using (FileStream outputStream = outputFile!.Exists && outputFile.Length <= inputFile.Length ?
outputFile.Open(FileMode.Open) : outputFile.Create())
{
await using (FileStream inputStream = inputFile.OpenRead())
await using (FileStream outputStream = outputFile!.Exists && outputFile.Length <= inputFile.Length ?
outputFile.Open(FileMode.Open) : outputFile.Create())
// Just in-case if the previous move is incomplete, then update and seek to the last position.
if (outputFile.Length <= inputStream.Length && outputFile.Length >= bufferSize)
{
// Do check by comparing the first and last 128K data of the file
Memory<byte> firstCompareInputBytes = new byte[bufferSize];
Memory<byte> firstCompareOutputBytes = new byte[bufferSize];
Memory<byte> lastCompareInputBytes = new byte[bufferSize];
Memory<byte> lastCompareOutputBytes = new byte[bufferSize];

// Seek to the first data
inputStream.Position = 0;
await inputStream.ReadExactlyAsync(firstCompareInputBytes);
outputStream.Position = 0;
await outputStream.ReadExactlyAsync(firstCompareOutputBytes);

// Seek to the last data
long lastPos = outputStream.Length - bufferSize;
inputStream.Position = lastPos;
await inputStream.ReadExactlyAsync(lastCompareInputBytes);
outputStream.Position = lastPos;
await outputStream.ReadExactlyAsync(lastCompareOutputBytes);

bool isMatch = firstCompareInputBytes.Span.SequenceEqual(firstCompareOutputBytes.Span)
&& lastCompareInputBytes.Span.SequenceEqual(lastCompareOutputBytes.Span);

// If the buffers don't match, then start the copy from the beginning
if (!isMatch)
{
inputStream.Position = 0;
outputStream.Position = 0;
}
else
{
// Just in-case if the previous move is incomplete, then update and seek to the last position.
if (outputFile.Length <= inputStream.Length && outputFile.Length >= bufferSize)
{
// Do check by comparing the first and last 128K data of the file
Memory<byte> firstCompareInputBytes = new byte[bufferSize];
Memory<byte> firstCompareOutputBytes = new byte[bufferSize];
Memory<byte> lastCompareInputBytes = new byte[bufferSize];
Memory<byte> lastCompareOutputBytes = new byte[bufferSize];

// Seek to the first data
inputStream.Position = 0;
await inputStream.ReadExactlyAsync(firstCompareInputBytes);
outputStream.Position = 0;
await outputStream.ReadExactlyAsync(firstCompareOutputBytes);

// Seek to the last data
long lastPos = outputStream.Length - bufferSize;
inputStream.Position = lastPos;
await inputStream.ReadExactlyAsync(lastCompareInputBytes);
outputStream.Position = lastPos;
await outputStream.ReadExactlyAsync(lastCompareOutputBytes);

bool isMatch = firstCompareInputBytes.Span.SequenceEqual(firstCompareOutputBytes.Span)
&& lastCompareInputBytes.Span.SequenceEqual(lastCompareOutputBytes.Span);

// If the buffers don't match, then start the copy from the beginning
if (!isMatch)
{
inputStream.Position = 0;
outputStream.Position = 0;
}
else
{
UpdateSizeProcessed(uiRef, outputStream.Length);
}
}

await MoveWriteFileInner(uiRef, inputStream, outputStream, buffer, token);
UpdateSizeProcessed(uiRef, outputStream.Length);
}
}

inputFile.IsReadOnly = false;
inputFile.Delete();
}
catch { throw; } // Re-throw to
finally
{
if (isUseArrayPool) ArrayPool<byte>.Shared.Return(buffer);
await MoveWriteFileInner(uiRef, inputStream, outputStream, buffer, token);
}

inputFile.IsReadOnly = false;
inputFile.Delete();
}

private async Task MoveWriteFileInner(FileMigrationProcessUIRef uiRef, FileStream inputStream, FileStream outputStream, byte[] buffer, CancellationToken token)
{
int read;
while ((read = await inputStream!.ReadAsync(buffer!, 0, buffer!.Length, token)) > 0)
{
await outputStream!.WriteAsync(buffer, 0, read, token);
outputStream!.Write(buffer, 0, read);
UpdateSizeProcessed(uiRef, read);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -823,7 +823,7 @@ private async Task ExtractUsingNativeZipWorker(IEnumerable<int> entriesIndex, Li
_progress.ProgressTotalPercentage = Math.Round(((double)_progressTotalSizeCurrent / _progressTotalSize) * 100, 2);
_progress.ProgressPerFilePercentage = Math.Round(((double)_progressPerFileSizeCurrent / _progressPerFileSize) * 100, 2);
// Calculate the timelapse
_progress.ProgressTotalTimeLeft = TimeSpan.FromSeconds((_progressTotalSize - _progressTotalSizeCurrent) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed));
_progress.ProgressTotalTimeLeft = ((_progressTotalSize - _progressTotalSizeCurrent) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed)).ToTimeSpanNormalized();

UpdateAll();
}
Expand Down Expand Up @@ -1229,7 +1229,7 @@ await Task.Run(() =>
_progress.ProgressTotalPercentage = Math.Round(((double)_progress.ProgressTotalDownload / _progress.ProgressTotalSizeToDownload) * 100, 2);
_progress.ProgressTotalSpeed = _progress.ProgressTotalDownload / _stopwatch.Elapsed.TotalSeconds;

_progress.ProgressTotalTimeLeft = TimeSpan.FromSeconds((_progress.ProgressTotalSizeToDownload - _progress.ProgressTotalDownload) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed));
_progress.ProgressTotalTimeLeft = ((_progress.ProgressTotalSizeToDownload - _progress.ProgressTotalDownload) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed)).ToTimeSpanNormalized();
UpdateProgress();
}
finally
Expand Down Expand Up @@ -1262,7 +1262,7 @@ private async void EventListener_PatchEvent(object sender, PatchEvent e)
_progress.ProgressTotalPercentage = Math.Round(((double)_progress.ProgressTotalDownload / _progress.ProgressTotalSizeToDownload) * 100, 2);
_progress.ProgressTotalSpeed = _progress.ProgressTotalDownload / _stopwatch.Elapsed.TotalSeconds;

_progress.ProgressTotalTimeLeft = TimeSpan.FromSeconds((_progress.ProgressTotalSizeToDownload - _progress.ProgressTotalDownload) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed));
_progress.ProgressTotalTimeLeft = ((_progress.ProgressTotalSizeToDownload - _progress.ProgressTotalDownload) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed)).ToTimeSpanNormalized();
UpdateProgress();
}
}
Expand Down Expand Up @@ -2149,7 +2149,7 @@ private async void ZipProgressAdapter(object sender, ExtractProgressProp e)
_progress.ProgressTotalPercentage = Math.Round(((double)_progressTotalSizeCurrent / _progressTotalSize) * 100, 2);
_progress.ProgressPerFilePercentage = Math.Round(((double)_progressPerFileSizeCurrent / _progressPerFileSize) * 100, 2);
// Calculate the timelapse
_progress.ProgressTotalTimeLeft = TimeSpan.FromSeconds((_progressTotalSize - _progressTotalSizeCurrent) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed));
_progress.ProgressTotalTimeLeft = ((_progressTotalSize - _progressTotalSizeCurrent) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed)).ToTimeSpanNormalized();

UpdateAll();
}
Expand Down Expand Up @@ -2199,7 +2199,7 @@ private async void HttpClientDownloadProgressAdapter(object sender, DownloadEven
_progress.ProgressTotalPercentage = Math.Round(_progressTotalSizeCurrent / (double)_progressTotalSize * 100, 2);

// Calculate the timelapse
_progress.ProgressTotalTimeLeft = TimeSpan.FromSeconds((_progressTotalSize - _progressTotalSizeCurrent) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed));
_progress.ProgressTotalTimeLeft = ((_progressTotalSize - _progressTotalSizeCurrent) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed)).ToTimeSpanNormalized();
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ public ConvertProgress(long StartSize, long EndSize, int StartCount, int EndCoun
Math.Round((StartSize / (double)EndSize) * 100, 2);
public long ProgressSpeed => (long)(StartSize / _TimeSecond);
public TimeSpan RemainingTime => UseCountUnit ? TimeSpan.FromSeconds(0f) :
TimeSpan.FromSeconds((EndSize - StartSize) / Unzeroed(ProgressSpeed));
((EndSize - StartSize) / Unzeroed(ProgressSpeed)).ToTimeSpanNormalized();
private double Unzeroed(double i) => i == 0 ? 1 : i;
public string ProgressStatus => _StatusMsg;
public string ProgressDetail => string.Format(
Expand Down
17 changes: 4 additions & 13 deletions CollapseLauncher/Classes/Interfaces/Class/ProgressBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ protected virtual async void _httpClient_RepairAssetProgress(object sender, Down
// Calculate speed
long speed = (long)(_progressTotalSizeCurrent / _stopwatch!.Elapsed.TotalSeconds);
_progress.ProgressTotalSpeed = speed;
_progress.ProgressTotalTimeLeft =
TimeSpan.FromSeconds((_progressTotalSizeCurrent - _progressTotalSize) / ConverterTool.Unzeroed(speed));
_progress.ProgressTotalTimeLeft = ((_progressTotalSizeCurrent - _progressTotalSize) / ConverterTool.Unzeroed(speed))
.ToTimeSpanNormalized();

// Update current progress percentages
_progress.ProgressTotalPercentage = _progressTotalSizeCurrent != 0 ?
Expand Down Expand Up @@ -213,16 +213,7 @@ protected virtual async void UpdateProgressCRC()
_progress.ProgressTotalSpeed = _progressTotalSizeCurrent / _stopwatch!.Elapsed.TotalSeconds;

// Calculate the timelapse
double seconds = (_progressTotalSize - _progressTotalSizeCurrent) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed);
if (seconds <= TimeSpan.MaxValue.TotalSeconds && seconds >= TimeSpan.MinValue.TotalSeconds)
{
_progress.ProgressTotalTimeLeft = TimeSpan.FromSeconds(seconds);
}
else
{
// Fallback mechanism when seconds are out of range
_progress.ProgressTotalTimeLeft = TimeSpan.MaxValue;
}
_progress.ProgressTotalTimeLeft = ((_progressTotalSize - _progressTotalSizeCurrent) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed)).ToTimeSpanNormalized();
}

lock (_status!)
Expand Down Expand Up @@ -261,7 +252,7 @@ protected virtual async void UpdateProgressCopyStream(long currentPosition, int
_progress.ProgressTotalSpeed = currentPosition / _stopwatch!.Elapsed.TotalSeconds;

// Calculate the timelapse
_progress.ProgressTotalTimeLeft = TimeSpan.FromSeconds((totalReadSize - currentPosition) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed));
_progress.ProgressTotalTimeLeft = ((totalReadSize - currentPosition) / ConverterTool.Unzeroed(_progress.ProgressTotalSpeed)).ToTimeSpanNormalized();
}

lock (_status!)
Expand Down
7 changes: 7 additions & 0 deletions CollapseLauncher/Classes/RegionManagement/RegionManagement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ async void CancelLoadEvent(object sender, RoutedEventArgs args)
ChangeRegionConfirmBtnNoWarning.IsEnabled = true;
ChangeRegionBtn.IsEnabled = true;

IsFirstStartup = false;
DisableKbShortcuts();
}

Expand All @@ -116,6 +117,12 @@ void ActionOnTimeOutRetry(int retryAttemptCount, int retryAttemptTotal, int time

await preset.GameLauncherApi.LoadAsync(BeforeLoadRoutine, AfterLoadRoutine, ActionOnTimeOutRetry, OnErrorRoutine, tokenSource.Token);

if (tokenSource.IsCancelled || tokenSource.Token.IsCancellationRequested)
{
LogWriteLine($"Game: {regionToChangeName} failed to initialize!", LogType.Error, true);
return false;
}

LogWriteLine($"Game: {regionToChangeName} has been completely initialized!", LogType.Scheme, true);
FinalizeLoadRegion(gameName, gameRegion);
ChangeBackgroundImageAsRegionAsync();
Expand Down
Loading

0 comments on commit 110db3e

Please sign in to comment.