diff --git a/.gitignore b/.gitignore index f9a2ae71..e19bfd2a 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ *.userosscache *.sln.docstates CompactGUI.TestingGround/ +CompactGUI.Tests/ # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs diff --git a/CompactGUI.Core/Analyser.cs b/CompactGUI.Core/Analyser.cs index 68fe9cec..7b0f4337 100644 --- a/CompactGUI.Core/Analyser.cs +++ b/CompactGUI.Core/Analyser.cs @@ -15,6 +15,7 @@ public sealed class Analyser : IDisposable public bool HasFolderChanged => _folderMonitor.HasChanged; public DateTime LastFolderChanged => _folderMonitor.LastChanged; + public bool IsDirectStorage { get; private set; } public Analyser(string folder, ILogger logger) { @@ -65,7 +66,7 @@ private static bool GetContainsCompressedFiles(List fileCom { List? AnalysedFileDetails; - + IsDirectStorage = false; AnalyserLog.StartingAnalysis(_logger, FolderName); Stopwatch sw = Stopwatch.StartNew(); try @@ -78,6 +79,8 @@ private static bool GetContainsCompressedFiles(List fileCom .OfType() .ToList(); + IsDirectStorage = allFiles.Any(f => Path.GetFileName(f).Equals("dstorage.dll", StringComparison.OrdinalIgnoreCase)); + AnalysedFileDetails = fileDetails; } catch (Exception ex) @@ -113,7 +116,7 @@ private static bool GetContainsCompressedFiles(List fileCom ? WOFCompressionAlgorithm.NO_COMPRESSION : WOFHelper.DetectCompression(fileInfo); - return new AnalysedFileDetails { FileName = file, CompressedSize = compressedSize, UncompressedSize = uncompressedSize, CompressionMode = compressionMode, FileInfo = fileInfo }; + return new AnalysedFileDetails { FileName = file, Attributes = fileInfo.Attributes, CompressedSize = compressedSize, UncompressedSize = uncompressedSize, CompressionMode = compressionMode}; } catch (IOException ex) { @@ -148,7 +151,7 @@ public List GetPoorlyCompressedExtensions() public void Dispose() { _folderMonitor.Dispose(); - _analysedFileDetails?.Clear(); + _analysedFileDetails = null; } } diff --git a/CompactGUI.Core/CompactGUI.Core.csproj b/CompactGUI.Core/CompactGUI.Core.csproj index a60df545..74189814 100644 --- a/CompactGUI.Core/CompactGUI.Core.csproj +++ b/CompactGUI.Core/CompactGUI.Core.csproj @@ -1,7 +1,7 @@  - net9.0-windows + net10.0-windows enable enable @@ -14,6 +14,7 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/CompactGUI.Core/Compactor.cs b/CompactGUI.Core/Compactor.cs index 0c6071f9..7cd3108c 100644 --- a/CompactGUI.Core/Compactor.cs +++ b/CompactGUI.Core/Compactor.cs @@ -3,10 +3,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Win32.SafeHandles; -using System.Collections.Concurrent; using System.Diagnostics; -using System.IO.Enumeration; -using System.Runtime.InteropServices; using Windows.Win32; namespace CompactGUI.Core; @@ -15,69 +12,67 @@ public sealed class Compactor : ICompressor, IDisposable { private readonly string workingDirectory; - private readonly HashSet excludedFileExtensions; + private readonly HashSet exclusionList; private readonly WOFCompressionAlgorithm wofCompressionAlgorithm; - - - private IntPtr compressionInfoPtr; - private UInt32 compressionInfoSize; - - private long totalProcessedBytes = 0; - private readonly SemaphoreSlim pauseSemaphore = new SemaphoreSlim(1, 2); - private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + private readonly bool bypassLowDiskSpaceProtection; + private readonly ParallelFileRunner runner; private ILogger _logger; private Analyser _analyser; - public Compactor(string folderPath, WOFCompressionAlgorithm compressionLevel, string[] excludedFileTypes, Analyser analyser, ILogger? logger = null) + public Compactor(string folderPath, WOFCompressionAlgorithm compressionLevel, string[] excludedFileTypes, Analyser analyser, bool bypassLowDiskSpaceProtection, ILogger? logger = null) { workingDirectory = folderPath; - excludedFileExtensions = new HashSet(excludedFileTypes); + exclusionList = new HashSet(excludedFileTypes, StringComparer.OrdinalIgnoreCase); wofCompressionAlgorithm = compressionLevel; + this.bypassLowDiskSpaceProtection = bypassLowDiskSpaceProtection; _logger = logger ?? NullLogger.Instance; _analyser = analyser; - InitializeCompressionInfoPointer(); - } - - - private void InitializeCompressionInfoPointer() - { - var _EFInfo = new WOFHelper.WOF_FILE_COMPRESSION_INFO_V1 { Algorithm = (UInt32)wofCompressionAlgorithm, Flags = 0 }; - compressionInfoPtr = Marshal.AllocHGlobal(Marshal.SizeOf(_EFInfo)); - compressionInfoSize = (UInt32)Marshal.SizeOf(_EFInfo); - Marshal.StructureToPtr(_EFInfo, compressionInfoPtr, true); - + runner = new ParallelFileRunner(new ParallelFileRunnerOptions + { + GetFileName = file => file.FileName, + GetProgressWeight = file => file.UncompressedSize, + ProcessFile = file => WOFCompressFile(file.FileName), + OnProcessing = file => CompactorLog.ProcessingFile(_logger, file.FileName, file.UncompressedSize), + RecoveryMode = DiskSpaceRecoveryMode.RepeatWhileProgress + }); } - public async Task RunAsync(List filesList, IProgress progressMonitor = null, int maxParallelism = 1) + public async Task RunAsync(IProgress? progressMonitor = null, int maxParallelism = 1) { - if(cancellationTokenSource.IsCancellationRequested) { return false; } + if (runner.IsCancellationRequested) return false; CompactorLog.BuildingWorkingFilesList(_logger, workingDirectory); var workingFiles = await BuildWorkingFilesList().ConfigureAwait(false); + if (workingFiles is null) + { + CompactorLog.CompressionFailed(_logger, "Unable to build the compression file list."); + return false; + } + long totalFilesSize = workingFiles.Sum((f) => f.UncompressedSize); - totalProcessedBytes = 0; + if (totalFilesSize == 0) + { + CompactorLog.CompressionCompleted(_logger, 0); + progressMonitor?.Report(new CompressionProgress(100, "")); + return true; + } var sw = Stopwatch.StartNew(); - if (maxParallelism <= 0) maxParallelism = Environment.ProcessorCount; - ParallelOptions parallelOptions = new() { MaxDegreeOfParallelism = maxParallelism, CancellationToken = cancellationTokenSource.Token }; - + maxParallelism = GetWorkerCount(maxParallelism, workingFiles, bypassLowDiskSpaceProtection); + Debug.WriteLine($"Compactor: Using {maxParallelism} parallel workers for compression."); CompactorLog.StartingCompression(_logger, workingDirectory, wofCompressionAlgorithm.ToString(), maxParallelism); + int failedFileCount; try { - await Parallel.ForEachAsync(workingFiles, parallelOptions, - (file, ctx) => - { - ctx.ThrowIfCancellationRequested(); - - return new ValueTask(PauseAndProcessFile(file, totalFilesSize, cancellationTokenSource.Token, progressMonitor)); - }).ConfigureAwait(false); + failedFileCount = await runner.RunAsync(workingFiles, totalFilesSize, maxParallelism, progressMonitor).ConfigureAwait(false); } catch (OperationCanceledException){ CompactorLog.CompressionCanceled(_logger); + runner.ReportProgress(progressMonitor, force: true); return false; } catch (Exception ex){ @@ -86,97 +81,124 @@ await Parallel.ForEachAsync(workingFiles, parallelOptions, } finally { sw.Stop();} + if (failedFileCount > 0) + { + CompactorLog.CompressionFailed(_logger, $"{failedFileCount} file operation(s) failed."); + runner.ReportProgress(progressMonitor, force: true); + return true; + } CompactorLog.CompressionCompleted(_logger, Math.Round(sw.Elapsed.TotalSeconds, 3)); + runner.ReportProgress(progressMonitor, force: true); return true; } - private async Task PauseAndProcessFile(FileDetails file, long totalFilesSize, CancellationToken token, IProgress progressMonitor) + private unsafe FileOperationResult WOFCompressFile(string filePath) { - CompactorLog.ProcessingFile(_logger, file.FileName, file.UncompressedSize); - - await pauseSemaphore.WaitAsync(token).ConfigureAwait(false); - pauseSemaphore.Release(); - - var res = WOFCompressFile(file.FileName); - Interlocked.Add(ref totalProcessedBytes, file.UncompressedSize); - progressMonitor?.Report(new CompressionProgress((int)((double)totalProcessedBytes / totalFilesSize * 100.0), file.FileName)); + const int ErrorCompressionNotBeneficialHResult = unchecked((int)0x80070158); - } - - private unsafe int? WOFCompressFile(string filePath) - { try { using (SafeFileHandle fs = File.OpenHandle(filePath)) { - return PInvoke.WofSetFileDataLocation(fs, (uint)WOFHelper.WOF_PROVIDER_FILE, compressionInfoPtr.ToPointer(), compressionInfoSize); + WOFHelper.WOF_FILE_COMPRESSION_INFO_V1 compressionInfo = new() + { + Algorithm = (uint)wofCompressionAlgorithm, + Flags = 0 + }; + + int result = PInvoke.WofSetFileDataLocation(fs,(uint)WOFHelper.WOF_PROVIDER_FILE, &compressionInfo, (uint)sizeof(WOFHelper.WOF_FILE_COMPRESSION_INFO_V1)); + + if (result >= 0 || result == ErrorCompressionNotBeneficialHResult) return FileOperationResult.Success; + if (FileOperationRecovery.IsInsufficientDiskSpaceHResult(result)) return FileOperationResult.InsufficientDiskSpace; + + return FileOperationResult.Failed; } } - catch (Exception ex) + catch (Exception) { - CompactorLog.FileCompressionFailed(_logger, filePath, ex.Message); - return null; + return FileOperationResult.Failed; } } - public async Task> BuildWorkingFilesList() + public async Task?> BuildWorkingFilesList() { uint clusterSize = SharedMethods.GetClusterSize(workingDirectory); - var analysedFiles = await _analyser.GetAnalysedFilesAsync(cancellationTokenSource.Token); - - var filesList = analysedFiles? - .Where(fl => - fl.CompressionMode != wofCompressionAlgorithm - && fl.UncompressedSize > clusterSize - && ((fl.FileInfo != null && !excludedFileExtensions.Contains(fl.FileInfo.Extension)) || excludedFileExtensions.Contains(fl.FileName)) - ) - .Select(fl => new FileDetails(fl.FileName, fl.UncompressedSize)) - .ToList(); - - return filesList; + var analysedFiles = await _analyser.GetAnalysedFilesAsync(runner.Token); + + if (analysedFiles is null) return null; + + var excludedFiles = SkipListMatcher.GetExcludedFiles(workingDirectory, analysedFiles.Select(f => f.FileName), exclusionList); + + return [.. analysedFiles + .Where(fl => + fl.CompressionMode != wofCompressionAlgorithm + && fl.UncompressedSize > clusterSize + && !fl.Attributes.HasFlag(FileAttributes.SparseFile) + && !excludedFiles.Contains(fl.FileName) + ) + .Select(fl => new FileDetails(fl.FileName, fl.UncompressedSize, fl.CompressedSize))]; } + private int GetWorkerCount(int requestedWorkerCount, IReadOnlyList files, bool bypassLowDiskSpaceProtection) + { + int workerCount = requestedWorkerCount <= 0 ? Environment.ProcessorCount : requestedWorkerCount; + + if (bypassLowDiskSpaceProtection) return workerCount; + + long totalAllocatedSize = 0; + long largestAllocatedSize = 0; + bool containsDiskImage = false; + + foreach (FileDetails file in files) + { + totalAllocatedSize = checked(totalAllocatedSize + file.AllocatedSize); + largestAllocatedSize = Math.Max(largestAllocatedSize, file.AllocatedSize); + containsDiskImage |= SharedMethods.IsDiskImage(file.FileName); + } + + try + { + var root = Path.GetPathRoot(workingDirectory); + if (string.IsNullOrWhiteSpace(root)) return workerCount; + + long reserveBytes = totalAllocatedSize / 2 + largestAllocatedSize; + bool lowFreeSpace = new DriveInfo(root).AvailableFreeSpace < reserveBytes * 2; + return lowFreeSpace || containsDiskImage ? 1 : workerCount; + } + catch (IOException) + { + return containsDiskImage ? 1 : workerCount; + } + } + + public void Pause() { CompactorLog.CompressionPaused(_logger); - pauseSemaphore.Wait(cancellationTokenSource.Token); + runner.Pause(); } public void Resume() { - if (pauseSemaphore.CurrentCount == 0) pauseSemaphore.Release(); + runner.Resume(); CompactorLog.CompressionResumed(_logger); } - public void Cancel() - { - Resume(); - cancellationTokenSource.Cancel(); - } - + public int Cancel() => runner.Cancel(); - public void Dispose() - { - cancellationTokenSource?.Dispose(); - pauseSemaphore?.Dispose(); - if (compressionInfoPtr != IntPtr.Zero) - { - Marshal.FreeHGlobal(compressionInfoPtr); - compressionInfoPtr = IntPtr.Zero; - } - } + public void Dispose() => runner.Dispose(); - public readonly record struct FileDetails(string FileName, long UncompressedSize); + public readonly record struct FileDetails(string FileName, long UncompressedSize, long AllocatedSize); } diff --git a/CompactGUI.Core/FileOperationRecovery.cs b/CompactGUI.Core/FileOperationRecovery.cs new file mode 100644 index 00000000..4a9e2bf4 --- /dev/null +++ b/CompactGUI.Core/FileOperationRecovery.cs @@ -0,0 +1,22 @@ +namespace CompactGUI.Core; + +internal enum FileOperationResult +{ + Success, + InsufficientDiskSpace, + Failed +} + +internal static class FileOperationRecovery +{ + private const int ErrorHandleDiskFull = 39; + private const int ErrorDiskFull = 112; + private const int ErrorDiskQuotaExceeded = 1295; + + public static bool IsInsufficientDiskSpaceError(int errorCode) => + errorCode is ErrorHandleDiskFull or ErrorDiskFull or ErrorDiskQuotaExceeded; + + public static bool IsInsufficientDiskSpaceHResult(int hResult) => + IsInsufficientDiskSpaceError(hResult & 0xFFFF) + && (hResult & unchecked((int)0xFFFF0000)) == unchecked((int)0x80070000); +} diff --git a/CompactGUI.Core/ICompressor.cs b/CompactGUI.Core/ICompressor.cs index e9c3c8fc..c224f3e4 100644 --- a/CompactGUI.Core/ICompressor.cs +++ b/CompactGUI.Core/ICompressor.cs @@ -2,13 +2,11 @@ public interface ICompressor : IDisposable { - Task RunAsync(List filesList, - IProgress progressMonitor = null, - int maxParallelism = 1); + Task RunAsync(IProgress? progressMonitor = null, int maxParallelism = 1); void Pause(); void Resume(); - void Cancel(); + int Cancel(); -} \ No newline at end of file +} diff --git a/CompactGUI.Core/ParallelFileRunner.cs b/CompactGUI.Core/ParallelFileRunner.cs new file mode 100644 index 00000000..4c4925c9 --- /dev/null +++ b/CompactGUI.Core/ParallelFileRunner.cs @@ -0,0 +1,183 @@ +using System.Collections.Concurrent; +using System.Diagnostics; + +namespace CompactGUI.Core; + +internal enum DiskSpaceRecoveryMode +{ + SinglePass, + RepeatWhileProgress +} + +internal record ParallelFileRunnerOptions +{ + public required Func GetFileName { get; init; } + public required Func GetProgressWeight { get; init; } + public required Func ProcessFile { get; init; } + public Action? OnProcessing { get; init; } + public Func? GetRecoveryOrder { get; init; } + public TimeSpan ProgressInterval { get; init; } = TimeSpan.FromMilliseconds(100); + public DiskSpaceRecoveryMode RecoveryMode { get; init; } = DiskSpaceRecoveryMode.SinglePass; +} + + +//apparently i should seal everything https://www.meziantou.net/performance-benefits-of-sealed-class.htm +internal sealed class ParallelFileRunner(ParallelFileRunnerOptions options) : IDisposable +{ + private readonly Func recoveryOrderSelector = options.GetRecoveryOrder ?? options.GetProgressWeight; + private readonly long progressIntervalTicks = (long)(options.ProgressInterval.TotalSeconds * Stopwatch.Frequency); + private readonly ManualResetEventSlim pauseGate = new(initialState: true); + private readonly CancellationTokenSource cancellationTokenSource = new(); + private readonly object cancellationGate = new(); + private readonly ConcurrentDictionary activeFiles = new(); + private int activeFileOperations; + private bool cancellationRequested; + private long processedWeight; + private long totalWeight; + private long lastProgressReportTicks; + private CompressionProgressStatus? status; + + public CancellationToken Token => cancellationTokenSource.Token; + public bool IsCancellationRequested => cancellationTokenSource.IsCancellationRequested; + + public async Task RunAsync(IReadOnlyCollection files, long totalWeight, int maxParallelism, IProgress? progressMonitor) + { + cancellationTokenSource.Token.ThrowIfCancellationRequested(); + this.totalWeight = totalWeight; + Interlocked.Exchange(ref processedWeight, 0); + Interlocked.Exchange(ref lastProgressReportTicks, 0); + status = null; + + if (files.Count == 0 || totalWeight == 0) + { + progressMonitor?.Report(new CompressionProgress(100, "")); + return 0; + } + + int failedFileCount = 0; + ConcurrentBag diskSpaceFailures = new(); + ParallelOptions parallelOptions = new() { MaxDegreeOfParallelism = maxParallelism, CancellationToken = cancellationTokenSource.Token }; + + await Parallel.ForEachAsync(files, parallelOptions, (file, ctx) => + { + ctx.ThrowIfCancellationRequested(); + + FileOperationResult result = PauseAndProcessFile(file, progressMonitor, cancellationTokenSource.Token); + if (result == FileOperationResult.InsufficientDiskSpace) diskSpaceFailures.Add(file); + else if (result == FileOperationResult.Failed) Interlocked.Increment(ref failedFileCount); + + return ValueTask.CompletedTask; + }).ConfigureAwait(false); + + Debug.WriteLine($"Disk space failures: {diskSpaceFailures.Count}"); + if (!diskSpaceFailures.IsEmpty) ReportStatus(progressMonitor, CompressionProgressStatus.LowDiskSpaceRetryingSequentially); + return failedFileCount + RetryDiskSpaceFailures(diskSpaceFailures, progressMonitor); + } + + private FileOperationResult PauseAndProcessFile(T file, IProgress? progressMonitor, CancellationToken token) + { + options.OnProcessing?.Invoke(file); + pauseGate.Wait(token); + + string fileName = options.GetFileName(file); + lock (cancellationGate) + { + if (cancellationRequested) return FileOperationResult.Success; + activeFileOperations++; + activeFiles.TryAdd(fileName, 0); + } + ReportProgress(progressMonitor, fileName); + + try + { + FileOperationResult result = options.ProcessFile(file); + if (result == FileOperationResult.Success) Interlocked.Add(ref processedWeight, options.GetProgressWeight(file)); + return result; + } + finally + { + lock (cancellationGate) + { + activeFileOperations--; + activeFiles.TryRemove(fileName, out _); + } + } + } + + private int RetryDiskSpaceFailures(IEnumerable failures, IProgress? progressMonitor) + { + List pending = [.. failures.OrderBy(recoveryOrderSelector)]; + int failedFileCount = 0; + + while (pending.Count > 0) + { + bool madeProgress = false; + List remaining = new(pending.Count); + + foreach (T file in pending) + { + cancellationTokenSource.Token.ThrowIfCancellationRequested(); + + FileOperationResult result = PauseAndProcessFile(file, progressMonitor, cancellationTokenSource.Token); + if (result == FileOperationResult.Success) madeProgress = true; + else if (result == FileOperationResult.InsufficientDiskSpace) remaining.Add(file); + else failedFileCount++; + } + + if (remaining.Count == 0) break; + + if (options.RecoveryMode == DiskSpaceRecoveryMode.SinglePass || !madeProgress) + { + failedFileCount += remaining.Count; + break; + } + + pending = remaining; + } + + return failedFileCount; + } + + public void ReportProgress(IProgress? progressMonitor, string fileName = "", bool force = false) + { + if (totalWeight == 0) + { + if (force) progressMonitor?.Report(new CompressionProgress(100, fileName, activeFiles.Keys.ToArray(), status)); + return; + } + + long now = Stopwatch.GetTimestamp(); + if (!force && now - Interlocked.Read(ref lastProgressReportTicks) < progressIntervalTicks) return; + + Interlocked.Exchange(ref lastProgressReportTicks, now); + progressMonitor?.Report(new CompressionProgress((int)((double)Interlocked.Read(ref processedWeight) / totalWeight * 100.0), fileName, activeFiles.Keys.ToArray(), status)); + } + + public void ReportStatus(IProgress? progressMonitor, CompressionProgressStatus? status) + { + this.status = status; + ReportProgress(progressMonitor, force: true); + } + + public void Pause() => pauseGate.Reset(); + public void Resume() => pauseGate.Set(); + + public int Cancel() + { + int activeOperations; + lock (cancellationGate) + { + cancellationRequested = true; + activeOperations = activeFileOperations; + } + pauseGate.Set(); + cancellationTokenSource.Cancel(); + return activeOperations; + } + + public void Dispose() + { + cancellationTokenSource.Dispose(); + pauseGate.Dispose(); + } +} diff --git a/CompactGUI.Core/Properties/AssemblyInfo.cs b/CompactGUI.Core/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..cf01371e --- /dev/null +++ b/CompactGUI.Core/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("CompactGUI.Tests")] diff --git a/CompactGUI.Core/Settings/Settings.cs b/CompactGUI.Core/Settings/Settings.cs index 2716e23c..93ca02a4 100644 --- a/CompactGUI.Core/Settings/Settings.cs +++ b/CompactGUI.Core/Settings/Settings.cs @@ -46,7 +46,14 @@ public partial class Settings : ObservableRecipient [ObservableProperty] private WindowState windowState = WindowState.Normal; [ObservableProperty] private bool alwaysShowDetailedCompressionMode = false; - [ObservableProperty] private string language = "en-US"; + [ObservableProperty] private string language = "en-AU"; + + [ObservableProperty] private bool bypassLowSpaceProtection = false; + + [ObservableProperty] private bool disableHardwareRendering = false; + + [ObservableProperty] private bool hideSteamLibraryTab = false; + [ObservableProperty] private bool hideCompressionDbTab = false; partial void OnScheduledBackgroundIntervalChanged(int value) => UpdateNextScheduledBackgroundRun(); diff --git a/CompactGUI.Core/SharedMethods.cs b/CompactGUI.Core/SharedMethods.cs index 910e39c6..6ebf1176 100644 --- a/CompactGUI.Core/SharedMethods.cs +++ b/CompactGUI.Core/SharedMethods.cs @@ -26,9 +26,11 @@ public enum FolderVerificationResult public static FolderVerificationResult VerifyFolder(string folder) { + folder = NormalizeLocalPath(folder); + if (!Directory.Exists(folder)) return FolderVerificationResult.DirectoryDoesNotExist; - else if (folder.ToLowerInvariant().Contains(Environment.GetFolderPath(Environment.SpecialFolder.Windows).ToLowerInvariant())) + else if (IsPathWithinDirectory(folder, Environment.GetFolderPath(Environment.SpecialFolder.Windows))) return FolderVerificationResult.SystemDirectory; else if (folder.EndsWith(":\\")) return FolderVerificationResult.RootDirectory; @@ -36,7 +38,7 @@ public static FolderVerificationResult VerifyFolder(string folder) return FolderVerificationResult.DirectoryEmptyOrUnauthorized; else if (IsOneDriveFolder(folder)) return FolderVerificationResult.OneDriveFolder; - else if (DriveInfo.GetDrives().First(f => folder.StartsWith(f.Name)).DriveFormat != "NTFS") + else if (!IsSupportedLocalNtfsDrive(folder)) return FolderVerificationResult.NonNTFSDrive; else if (!HasDirectoryWritePermission(folder)) return FolderVerificationResult.InsufficientPermission; @@ -46,6 +48,40 @@ public static FolderVerificationResult VerifyFolder(string folder) return FolderVerificationResult.Valid; } + public static string NormalizeLocalPath(string folder) + { + try + { + return NormalizeLocalDrivePath(new DirectoryInfo(folder).FullName); + } + catch (ArgumentException) + { + return folder; + } + } + + private static string NormalizeLocalDrivePath(string folder) + { + if (folder.Length < 2 || folder[1] != ':' || !char.IsAsciiLetter(folder[0])) return folder; + + return char.ToUpperInvariant(folder[0]) + folder[1..]; + } + + internal static bool IsPathWithinDirectory(string path, string directory) + { + string normalizedPath = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + string normalizedDirectory = Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + + return normalizedPath.Equals(normalizedDirectory, StringComparison.OrdinalIgnoreCase) + || normalizedPath.StartsWith(normalizedDirectory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); + } + + private static bool IsSupportedLocalNtfsDrive(string folder) + { + var drive = DriveInfo.GetDrives().FirstOrDefault(f => folder.StartsWith(f.Name, StringComparison.OrdinalIgnoreCase)); + return drive is not null && drive.DriveType != DriveType.Network && drive.DriveFormat == "NTFS"; + } + public static string GetFolderVerificationMessage(FolderVerificationResult result) { return result switch @@ -88,13 +124,23 @@ static bool IsOneDriveFolder(string folderPath) Path.Combine(userProfile, "OneDrive - Business") // Alternative OneDrive for Business }; - string normalizedFolderPath = Path.GetFullPath(folderPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).ToLowerInvariant(); + return oneDrivePaths.Any(oneDrivePath => IsPathWithinDirectory(folderPath, oneDrivePath)); - return oneDrivePaths.Any(oneDrivePath => - normalizedFolderPath.StartsWith(Path.GetFullPath(oneDrivePath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).ToLowerInvariant())); + } + public static bool IsDiskImage(string fileName) + { + ReadOnlySpan extension = Path.GetExtension(fileName.AsSpan()); + return extension.Equals(".vhd", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".vhdx", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".vmdk", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".qcow2", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".img", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".iso", StringComparison.OrdinalIgnoreCase); } + + public static void PreventSleep() { PInvoke.SetThreadExecutionState( @@ -166,6 +212,46 @@ public static unsafe uint GetClusterSize(string folderPath) } + public static bool HasSufficientFreeSpaceForCompression(string workingDirectory, IEnumerable analysedFiles, WOFCompressionAlgorithm compressionAlgorithm, IEnumerable exclusionList) + { + long requiredBytes; + if (compressionAlgorithm == WOFCompressionAlgorithm.NO_COMPRESSION) + { + long largestCandidateSize = 0; + requiredBytes = 0; + + foreach (AnalysedFileDetails file in analysedFiles) + { + if (file.CompressedSize >= file.UncompressedSize) continue; + requiredBytes += file.UncompressedSize - file.CompressedSize; + largestCandidateSize = Math.Max(largestCandidateSize, file.UncompressedSize); + } + + requiredBytes += largestCandidateSize; + } + else + { + uint clusterSize = GetClusterSize(workingDirectory); + var excludedFiles = SkipListMatcher.GetExcludedFiles(workingDirectory, analysedFiles.Select(file => file.FileName), exclusionList); + requiredBytes = analysedFiles.Where(file => + file.CompressionMode != compressionAlgorithm && + file.UncompressedSize > clusterSize && + !file.Attributes.HasFlag(FileAttributes.SparseFile) && + !excludedFiles.Contains(file.FileName)) + .Select(file => file.UncompressedSize).DefaultIfEmpty().Max() * 2; + } + + try + { + var root = Path.GetPathRoot(workingDirectory); + return !string.IsNullOrWhiteSpace(root) && requiredBytes <= new DriveInfo(root).AvailableFreeSpace; + } + catch (IOException) + { + return false; + } + } + public static unsafe long GetFileSizeOnDisk(string file) { @@ -221,26 +307,5 @@ public static bool IsFolderLZNT1Compressed(string folderPath) return attributes.HasFlag(FileAttributes.Compressed); } - public static bool IsDirectStorageGameFolder(string folderPath) - { - if (string.IsNullOrWhiteSpace(folderPath) || !Directory.Exists(folderPath)) return false; - - // List of possible DirectStorage DLL relative paths from https://github.com/SteamDatabase/FileDetectionRuleSets/blob/main/tests/types/SDK.DirectStorage.txt - string[] directStoragePaths = new[] - { - "dstorage.dll", - Path.Combine("Bin64", "dstorage.dll"), - Path.Combine("Engine", "Binaries", "ThirdParty", "Windows", "DirectStorage", "x64", "dstorage.dll") - }; - - foreach (var relativePath in directStoragePaths) - { - string fullPath = Path.Combine(folderPath, relativePath); - if (File.Exists(fullPath)) return true; - } - - return false; - } - } diff --git a/CompactGUI.Core/SharedObjects.cs b/CompactGUI.Core/SharedObjects.cs index 61f67fe9..45701262 100644 --- a/CompactGUI.Core/SharedObjects.cs +++ b/CompactGUI.Core/SharedObjects.cs @@ -4,10 +4,10 @@ public sealed class AnalysedFileDetails { public required string FileName { get; set; } + public FileAttributes Attributes { get; set; } public long UncompressedSize { get; set; } public long CompressedSize { get; set; } public WOFCompressionAlgorithm CompressionMode { get; set; } - public FileInfo? FileInfo { get; set; } } @@ -26,16 +26,25 @@ public sealed class ExtensionResult public struct CompressionProgress { - public int ProgressPercent; - public string FileName; + public int ProgressPercent { get; set; } + public string FileName { get; set; } + public string[] ActiveFiles { get; set; } + public CompressionProgressStatus? Status { get; set; } - public CompressionProgress(int progressPercent, string fileName) + public CompressionProgress(int progressPercent, string fileName, string[]? activeFiles = null, CompressionProgressStatus? status = null) { ProgressPercent = progressPercent; FileName = fileName; + ActiveFiles = activeFiles ?? Array.Empty(); + Status = status; } } +public enum CompressionProgressStatus +{ + LowDiskSpaceRetryingSequentially +} + public enum CompressionMode: int { @@ -55,4 +64,4 @@ public enum WOFCompressionAlgorithm: int LZX = 1, XPRESS8K = 2, XPRESS16K = 3 -} \ No newline at end of file +} diff --git a/CompactGUI.Core/SkipListMatcher.cs b/CompactGUI.Core/SkipListMatcher.cs new file mode 100644 index 00000000..7d4c4cab --- /dev/null +++ b/CompactGUI.Core/SkipListMatcher.cs @@ -0,0 +1,79 @@ +using Microsoft.Extensions.FileSystemGlobbing; + +namespace CompactGUI.Core; + +public static class SkipListMatcher +{ + public static HashSet GetExcludedFiles(string rootDirectory, IEnumerable allFiles, IEnumerable patterns) + { + var excluded = new HashSet(StringComparer.OrdinalIgnoreCase); + if (!patterns.Any()) return excluded; + + var matcher = new Matcher(StringComparison.OrdinalIgnoreCase); + foreach (string glob in NormalisePatterns(patterns, rootDirectory)) + { + matcher.AddInclude(glob); + } + + var relativeFiles = allFiles.Select(f => Path.GetRelativePath(rootDirectory, f).Replace('\\', '/')); + + foreach (FilePatternMatch match in matcher.Match(relativeFiles).Files) + { + excluded.Add(Path.GetFullPath(Path.Combine(rootDirectory, match.Path))); + } + + return excluded; + } + + private static IEnumerable NormalisePatterns(IEnumerable entries, string rootDirectory) + { + foreach (string entry in entries) + { + string pattern = entry.Trim().Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + if (pattern.Length == 0) continue; + + // Absolute path entries (e.g. estimator full file names for non-Steam folders): + // relativize against the root so they match the relative paths the matcher sees. + if (Path.IsPathRooted(pattern)) + { + try + { + string relative = Path.GetRelativePath(rootDirectory, pattern).Replace('\\', '/'); + if (!relative.StartsWith("../", StringComparison.Ordinal) && relative != "..") + { + pattern = relative; + } + } + catch (ArgumentException) + { + // Unrelated roots; leave as-is (won't match). + } + } + + bool hasWildcard = pattern.Contains('*') || pattern.Contains('?'); + bool hasSeparator = pattern.Contains(Path.DirectorySeparatorChar) || pattern.Contains(Path.AltDirectorySeparatorChar); + + if (!hasSeparator && IsExtensionPattern(pattern)) + { + // Extension patterns (".mp4", "*.mp4") match any file with that extension at any depth to keep existnig skips working. + yield return "**/*" + (pattern.StartsWith('.') ? pattern : pattern[1..]); + } + else if (!hasWildcard && !hasSeparator) + { + // Legacy exact file names ("Thumbs.db"), matched at any depth. + yield return "**/" + pattern; + } + else + { + yield return NormalisePath(pattern); + } + } + } + + private static bool IsExtensionPattern(string pattern) + { + return pattern.StartsWith('.') || pattern.StartsWith("*."); + } + + private static string NormalisePath(string path) => path.Replace(Path.DirectorySeparatorChar, '/').Replace(Path.AltDirectorySeparatorChar, '/'); +} diff --git a/CompactGUI.Core/Uncompactor.cs b/CompactGUI.Core/Uncompactor.cs index 17f9a52a..9768a31c 100644 --- a/CompactGUI.Core/Uncompactor.cs +++ b/CompactGUI.Core/Uncompactor.cs @@ -2,118 +2,122 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Win32.SafeHandles; -using System.Collections.Concurrent; using Windows.Win32; using CompactGUI.Logging.Core; using System.Diagnostics; +using System.Runtime.InteropServices; namespace CompactGUI.Core; public sealed class Uncompactor : ICompressor, IDisposable { - private SemaphoreSlim pauseSemaphore = new SemaphoreSlim(1, 2); - private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); - private ConcurrentDictionary processedFileCount = new ConcurrentDictionary(); - + private readonly IReadOnlyList filesList; private readonly ILogger _logger; + private readonly ParallelFileRunner runner; - public Uncompactor(ILogger? logger = null) + public Uncompactor(IReadOnlyList filesList, ILogger? logger = null) { + this.filesList = filesList ?? throw new ArgumentNullException(nameof(filesList)); _logger = logger ?? NullLogger.Instance; + runner = new ParallelFileRunner(new ParallelFileRunnerOptions + { + GetFileName = file => file, + GetProgressWeight = _ => 1, + ProcessFile = WOFDecompressFile, + OnProcessing = file => UncompactorLog.ProcessingFile(_logger, file), + GetRecoveryOrder = GetFileLength, + ProgressInterval = TimeSpan.FromMilliseconds(200) + }); } - public async Task RunAsync(List filesList, IProgress? progressMonitor = null, int maxParallelism = 1) + public async Task RunAsync(IProgress? progressMonitor = null, int maxParallelism = 1) { int totalFiles = filesList.Count; + int failedFileCount = 0; if (maxParallelism <= 0) maxParallelism = Environment.ProcessorCount; - ParallelOptions parallelOptions = new() { MaxDegreeOfParallelism = maxParallelism }; - processedFileCount.Clear(); UncompactorLog.StartingDecompression(_logger, totalFiles, maxParallelism); Stopwatch sw = Stopwatch.StartNew(); try { - await Parallel.ForEachAsync(filesList, parallelOptions, - (file, ctx) => - { - ctx.ThrowIfCancellationRequested(); - return new ValueTask(PauseAndProcessFile(file, totalFiles, progressMonitor, cancellationTokenSource.Token)); - }); + failedFileCount = await runner.RunAsync(filesList, totalFiles, maxParallelism, progressMonitor).ConfigureAwait(false); } catch (OperationCanceledException) { UncompactorLog.DecompressionCanceled(_logger); + runner.ReportProgress(progressMonitor, force: true); return false; } + catch (Exception ex) + { + UncompactorLog.DecompressionFailed(_logger, ex.Message); + return false; + } finally { sw.Stop(); } + if (failedFileCount > 0) + { + UncompactorLog.DecompressionFailed(_logger, $"{failedFileCount} file operation(s) failed."); + runner.ReportProgress(progressMonitor, force: true); + return true; + } + UncompactorLog.DecompressionCompleted(_logger, Math.Round(sw.Elapsed.TotalSeconds, 3)); + runner.ReportProgress(progressMonitor, force: true); return true; } - private async Task PauseAndProcessFile(string file, int totalFiles, IProgress? progressMonitor, CancellationToken ctx) + private unsafe FileOperationResult WOFDecompressFile(string file) { - UncompactorLog.ProcessingFile(_logger, file); try { - await pauseSemaphore.WaitAsync(ctx).ConfigureAwait(false); - pauseSemaphore.Release(); - } - catch (OperationCanceledException) { throw; } - ctx.ThrowIfCancellationRequested(); - - var _ = WOFDecompressFile(file); - processedFileCount.TryAdd(file, 1); - progressMonitor?.Report(new CompressionProgress( - (int)(processedFileCount.Count / (float)totalFiles * 100), - file) - ); + using (SafeFileHandle fs = File.OpenHandle(file)) + { + uint bytesReturned; + if (PInvoke.DeviceIoControl(fs, WOFHelper.FSCTL_DELETE_EXTERNAL_BACKING, null, 0, null, 0, &bytesReturned, null)) return FileOperationResult.Success; + int errorCode = Marshal.GetLastPInvokeError(); + return FileOperationRecovery.IsInsufficientDiskSpaceError(errorCode) + ? FileOperationResult.InsufficientDiskSpace + : FileOperationResult.Failed; + } + } + catch (Exception) { + return FileOperationResult.Failed; + } } - private unsafe bool? WOFDecompressFile(string file) + private static long GetFileLength(string file) { try { - using (SafeFileHandle fs = File.OpenHandle(file)) - { - var res = PInvoke.DeviceIoControl(fs, WOFHelper.FSCTL_DELETE_EXTERNAL_BACKING, null, 0, null, 0, null, null); - return res; - } + return new FileInfo(file).Length; } - catch (Exception ex) { - UncompactorLog.FileDecompressionFailed(_logger, file, ex.Message); - return null; + catch + { + return long.MaxValue; } } public void Pause() { UncompactorLog.DecompressionPaused(_logger); - pauseSemaphore.Wait(); + runner.Pause(); } public void Resume() { - if (pauseSemaphore.CurrentCount == 0) pauseSemaphore.Release(); + runner.Resume(); UncompactorLog.DecompressionResumed(_logger); } - public void Cancel() - { - Resume(); - cancellationTokenSource.Cancel(); - } + public int Cancel() => runner.Cancel(); - public void Dispose() - { - pauseSemaphore.Dispose(); - cancellationTokenSource.Dispose(); - } + public void Dispose() => runner.Dispose(); diff --git a/CompactGUI.CoreVB/Analyser.vb b/CompactGUI.CoreVB/Analyser.vb deleted file mode 100644 index e303a457..00000000 --- a/CompactGUI.CoreVB/Analyser.vb +++ /dev/null @@ -1,172 +0,0 @@ -Imports System.IO -Imports System.Security.AccessControl -Imports System.Security.Principal -Imports System.Threading - -Public Class Analyser - - Public Property FolderName As String - Public Property UncompressedBytes As Long - Public Property CompressedBytes As Long - Public Property ContainsCompressedFiles As Boolean - Public Property FileCompressionDetailsList As List(Of AnalysedFileDetails) - - Public Sub New(folder As String) - FolderName = folder - End Sub - - - Public Async Function AnalyseFolder(cancellationToken As CancellationToken) As Task(Of Boolean) - Dim allFiles = Await Task.Run(Function() Directory.EnumerateFiles(FolderName, "*", New EnumerationOptions() With {.RecurseSubdirectories = True, .IgnoreInaccessible = True}).AsShortPathNames, cancellationToken).ConfigureAwait(False) - Dim fileDetails As New List(Of AnalysedFileDetails) - Dim compressedFilesCount As Integer = 0 - - ' Use local variables to reduce contention - Dim localCompressedBytes As Long = 0 - Dim localUncompressedBytes As Long = 0 - - Try - Parallel.ForEach(allFiles, New ParallelOptions With {.CancellationToken = cancellationToken}, - Sub(file) - Dim details = AnalyseFile(file) - If details IsNot Nothing Then - SyncLock fileDetails - fileDetails.Add(details) - End SyncLock - If details.CompressionMode <> WOFCompressionAlgorithm.NO_COMPRESSION Then - Interlocked.Increment(compressedFilesCount) - End If - Interlocked.Add(localCompressedBytes, details.CompressedSize) - Interlocked.Add(localUncompressedBytes, details.UncompressedSize) - End If - End Sub) - - ' Update the shared state after the parallel loop to minimize contention - CompressedBytes = localCompressedBytes - UncompressedBytes = localUncompressedBytes - Catch ex As OperationCanceledException - Debug.WriteLine(ex.Message) - Return Nothing - End Try - - ContainsCompressedFiles = compressedFilesCount > 0 - FileCompressionDetailsList = fileDetails - Return ContainsCompressedFiles - End Function - - - Private Function AnalyseFile(file As String) As AnalysedFileDetails - Try - Dim fInfo As New FileInfo(file) - Dim unCompSize = fInfo.Length - Dim compSize = GetFileSizeOnDisk(file) - If compSize < 0 Then - compSize = unCompSize ' GetFileSizeOnDisk failed, fall back to unCompSize - End If - Dim cLevel As WOFCompressionAlgorithm = If(compSize = unCompSize, WOFCompressionAlgorithm.NO_COMPRESSION, DetectCompression(fInfo)) - - Return New AnalysedFileDetails With {.FileName = file, .CompressedSize = compSize, .UncompressedSize = unCompSize, .CompressionMode = cLevel, .FileInfo = fInfo} - Catch ex As IOException - Debug.WriteLine($"Error analysing file {file}: {ex.Message}") - Return Nothing - End Try - End Function - - - Public Async Function GetPoorlyCompressedExtensions() As Task(Of List(Of ExtensionResult)) - Dim extClassResults As New List(Of ExtensionResult) - Await Task.Run( - Sub() - Dim extRes As New Concurrent.ConcurrentDictionary(Of String, ExtensionResult) - Parallel.ForEach(FileCompressionDetailsList, - Sub(fl) - Dim xt = New FileInfo(fl.FileName).Extension - If fl.UncompressedSize = 0 Then Return - - extRes.AddOrUpdate(xt, - Function(addKey) ' Add value factory - Return New ExtensionResult With { - .extension = xt, - .totalFiles = 1, - .uncompressedBytes = fl.UncompressedSize, - .compressedBytes = fl.CompressedSize - } - End Function, - Function(updateKey, oldValue) ' Update value factory - Return New ExtensionResult With { - .extension = xt, - .totalFiles = oldValue.totalFiles + 1, - .uncompressedBytes = oldValue.uncompressedBytes + fl.UncompressedSize, - .compressedBytes = oldValue.compressedBytes + fl.CompressedSize - } - End Function) - End Sub) - - ' Filter and convert to list after aggregation - extClassResults = extRes.Values.Where(Function(f) f.cRatio > 0.95).ToList() - End Sub) - - Return extClassResults - End Function - - - Private Function DetectCompression(fInfo As FileInfo) As WOFCompressionAlgorithm - - Dim isextFile As Integer - Dim prov As ULong - Dim info As WOF_FILE_COMPRESSION_INFO_V1 - Dim buf As UInt16 = 8 - - Dim ret = WofIsExternalFile(fInfo.FullName, isextFile, prov, info, buf) - - Dim algorithm As WOFCompressionAlgorithm = info.Algorithm - - If isextFile = 0 Then algorithm = WOFCompressionAlgorithm.NO_COMPRESSION - If (fInfo.Attributes And 2048) <> 0 Then algorithm = WOFCompressionAlgorithm.LZNT1 - Return algorithm - - End Function - - - Public Shared Function HasDirectoryWritePermission(FolderName As String) As Boolean - Try - Dim directoryInfo = New DirectoryInfo(FolderName) - Dim directorySecurity = directoryInfo.GetAccessControl() - - Dim user = WindowsIdentity.GetCurrent() - Dim userSID = user.User - Dim userGroupSIDs = user.Groups - - Dim accessRules = directorySecurity.GetAccessRules(True, True, GetType(SecurityIdentifier)) - - Dim writeAllowed = False - Dim writeDenied = False - - For Each rule As FileSystemAccessRule In accessRules - Dim fileSystemRights = rule.FileSystemRights - If (fileSystemRights And FileSystemRights.Write) > 0 Then - Dim ruleSID = DirectCast(rule.IdentityReference, SecurityIdentifier) - - ' Check if the rule applies to the user or any of the user's groups - If ruleSID.Equals(userSID) OrElse userGroupSIDs.Contains(ruleSID) Then - If rule.AccessControlType = AccessControlType.Allow Then - writeAllowed = True - ElseIf rule.AccessControlType = AccessControlType.Deny Then - writeDenied = True - Exit For - End If - End If - End If - Next - - ' Write permission is considered available if it's explicitly allowed and not explicitly denied - Return writeAllowed And Not writeDenied - Catch ex As UnauthorizedAccessException - - Return False - End Try - End Function - - - -End Class diff --git a/CompactGUI.CoreVB/CompactGUI.CoreVB.vbproj b/CompactGUI.CoreVB/CompactGUI.CoreVB.vbproj deleted file mode 100644 index 27416f26..00000000 --- a/CompactGUI.CoreVB/CompactGUI.CoreVB.vbproj +++ /dev/null @@ -1,23 +0,0 @@ - - - - CompactGUI.CoreVB - net9.0-windows - - - - none - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - diff --git a/CompactGUI.CoreVB/Compactor.vb b/CompactGUI.CoreVB/Compactor.vb deleted file mode 100644 index c17435d7..00000000 --- a/CompactGUI.CoreVB/Compactor.vb +++ /dev/null @@ -1,159 +0,0 @@ -Imports System.IO -Imports System.Runtime.InteropServices -Imports System.Threading - -Imports Microsoft.Win32.SafeHandles - - -Public Class Compactor : Implements IDisposable, ICompressor - - Private ReadOnly workingDirectory As String - Private ReadOnly excludedFileExtensions() As String - Private ReadOnly wofCompressionAlgorithm As WOFCompressionAlgorithm - - Private compressionInfoPtr As IntPtr - Private compressionInfoSize As UInteger - - Private totalProcessedBytes As Long = 0 - Private ReadOnly pauseSemaphore As New SemaphoreSlim(1, 2) - Private ReadOnly cancellationTokenSource As New CancellationTokenSource - - - Public Sub New(folder As String, compressionLevel As WOFCompressionAlgorithm, excludedFilesTypes As String()) - - workingDirectory = folder - wofCompressionAlgorithm = compressionLevel - excludedFileExtensions = excludedFilesTypes - - InitializeCompressionInfoPointer() - - End Sub - - - Private Sub InitializeCompressionInfoPointer() - Dim _EFInfo As New WOF_FILE_COMPRESSION_INFO_V1 With {.Algorithm = wofCompressionAlgorithm, .Flags = 0} - compressionInfoPtr = Marshal.AllocHGlobal(Marshal.SizeOf(_EFInfo)) - compressionInfoSize = CUInt(Marshal.SizeOf(_EFInfo)) - Marshal.StructureToPtr(_EFInfo, compressionInfoPtr, True) - End Sub - - - Public Async Function RunAsync(filesList As List(Of String), Optional progressMonitor As IProgress(Of CompressionProgress) = Nothing, Optional MaxParallelism As Integer = 1) As Task(Of Boolean) Implements ICompressor.RunAsync - - If cancellationTokenSource.IsCancellationRequested Then Return False - - Dim workingFiles = Await BuildWorkingFilesList().ConfigureAwait(False) - Dim totalFilesSize As Long = workingFiles.Sum(Function(f) f.UncompressedSize) - totalProcessedBytes = 0 - - If MaxParallelism <= 0 Then MaxParallelism = Environment.ProcessorCount - - Dim paraOptions As New ParallelOptions With {.MaxDegreeOfParallelism = MaxParallelism} - - Try - Await Parallel.ForEachAsync(workingFiles, paraOptions, - Function(file, _ctx) As ValueTask - _ctx.ThrowIfCancellationRequested() - Return New ValueTask(PauseAndProcessFile(file, totalFilesSize, cancellationTokenSource.Token, progressMonitor)) - End Function).ConfigureAwait(False) - Catch ex As OperationCanceledException - ' Swallow cancellation, return false - Return False - End Try - - Return Not cancellationTokenSource.IsCancellationRequested - - End Function - - Private Async Function PauseAndProcessFile(details As FileDetails, totalFilesSize As Long, _ctx As CancellationToken, Optional progressMonitor As IProgress(Of CompressionProgress) = Nothing) As Task - - Try - Await pauseSemaphore.WaitAsync(_ctx).ConfigureAwait(False) - pauseSemaphore.Release() - Catch ex As OperationCanceledException - Throw - Return - End Try - - _ctx.ThrowIfCancellationRequested() - - Dim res = WOFCompressFile(details.FileName) - Interlocked.Add(totalProcessedBytes, details.UncompressedSize) - progressMonitor?.Report(New CompressionProgress(totalProcessedBytes / totalFilesSize * 100, details.FileName)) - - - End Function - - - - Public Sub Pause() Implements ICompressor.Pause - pauseSemaphore.Wait() - End Sub - - - Public Sub [Resume]() Implements ICompressor.Resume - If pauseSemaphore.CurrentCount = 0 Then pauseSemaphore.Release() - End Sub - - Public Sub Cancel() Implements ICompressor.Cancel - [Resume]() - cancellationTokenSource.Cancel() - End Sub - - - - Private Function WOFCompressFile(path As String) As Integer - - Try - Using fs As SafeFileHandle = File.OpenHandle(path) - Return WofSetFileDataLocation(fs, WOF_PROVIDER_FILE, compressionInfoPtr, compressionInfoSize) - End Using - Catch ex As Exception - Debug.WriteLine(ex.Message) - Return Nothing - End Try - - End Function - - Private Async Function BuildWorkingFilesList() As Task(Of IEnumerable(Of FileDetails)) - - Dim clusterSize As Integer = GetClusterSize(workingDirectory) - - Dim _filesList As New Concurrent.ConcurrentBag(Of FileDetails) - 'TODO: if the user has already analysed within the last minute, then skip creating a new one and use the old one - Dim ax As New Analyser(workingDirectory) - Dim ret = Await ax.AnalyseFolder(Nothing) - - Parallel.ForEach(ax.FileCompressionDetailsList, Sub(fl) - Dim ft = fl.FileInfo - If Not (excludedFileExtensions.Contains(ft.Extension) OrElse excludedFileExtensions.Contains(fl.FileName)) AndAlso - ft.Length > clusterSize AndAlso - fl.CompressionMode <> wofCompressionAlgorithm Then - _filesList.Add((New FileDetails With {.FileName = fl.FileName, .UncompressedSize = fl.UncompressedSize})) - End If - End Sub) - - - Return _filesList.ToList - End Function - - - Public Sub Dispose() Implements IDisposable.Dispose - cancellationTokenSource?.Dispose() - pauseSemaphore?.Dispose() - If Not compressionInfoPtr.Equals(IntPtr.Zero) Then - Marshal.FreeHGlobal(compressionInfoPtr) - compressionInfoPtr = IntPtr.Zero - End If - End Sub - - - - Private Structure FileDetails - Public Property FileName As String - Public Property UncompressedSize As Long - - End Structure - - -End Class diff --git a/CompactGUI.CoreVB/Estimator.vb b/CompactGUI.CoreVB/Estimator.vb deleted file mode 100644 index 87e7903d..00000000 --- a/CompactGUI.CoreVB/Estimator.vb +++ /dev/null @@ -1,232 +0,0 @@ -Imports System.IO -Imports System.IO.Compression -Imports System.Runtime.InteropServices - -Imports K4os.Compression.LZ4 - -Imports K4os.Compression.LZ4.Streams - -Imports Microsoft.Win32.SafeHandles - - -'https://unix.stackexchange.com/questions/155901/estimate-compressibility-of-file - -Public Class Estimator - Private Const BlockSize As Integer = 8192 '16K? Should I get it from the ClusterSize? - Private Const ZScore As Single = 1.96 - Private Const ErrorMargin As Single = 0.1 - Private Const SampleSize As Single = 100 '0.25 * (ZScore / ErrorMargin) ^ 2 - - Private DiskClusterSize As Integer = 4096 - Private IsHDD As Boolean = False - - Public Sub New() - End Sub - - - Public Delegate Function CompressionStreamFactory(output As Stream) As Stream - - - Public Class FileDetails - Public AnalysedFile As AnalysedFileDetails - Public CompressionRatio As Single - End Class - - Public Shared IsAlternate As Boolean = False - - Public Function EstimateCompressability(analysisResult As List(Of AnalysedFileDetails), ishdd As Boolean, Optional MaxParallelism As Integer = 1, Optional clusterSize As Integer = 4096, Optional cancellationToken As Threading.CancellationToken = Nothing) As List(Of (AnalysedFile As AnalysedFileDetails, CompressionRatio As Single)) - - DiskClusterSize = clusterSize - Dim _filesList As New Concurrent.ConcurrentBag(Of FileDetails) - If MaxParallelism <= 0 Then MaxParallelism = Environment.ProcessorCount - - Me.IsHDD = ishdd - - - 'Filter the files based on the cluster size and sort them by cluster location if it's an HDD to minimize seek time - Dim filteredList = analysisResult.Where(Function(f) f.UncompressedSize > clusterSize) - - Dim sw = Stopwatch.StartNew() - - If ishdd Then filteredList = filteredList.OrderBy(Function(f) GetFirstLcn(f.FileName)) - Dim finalList = filteredList.ToList - sw.Stop() - Debug.WriteLine($"Filtered and sorted {finalList.Count} files in {sw.ElapsedMilliseconds} ms") - If IsAlternate Then Debug.WriteLine("Alternate mode enabled, using different handle method.") - - - Dim paraOptions As New ParallelOptions With {.MaxDegreeOfParallelism = MaxParallelism} - - Parallel.ForEach(finalList, parallelOptions:=paraOptions, Sub(fl) - cancellationToken.ThrowIfCancellationRequested() - - Dim estimatedRatio = EstimateCompressabilityLZ4(fl.FileName, fl.UncompressedSize, cancellationToken) - - _filesList.Add((New FileDetails With {.AnalysedFile = fl, .CompressionRatio = estimatedRatio})) - End Sub) - - Dim retList As New List(Of (AnalysedFile As AnalysedFileDetails, CompressionRatio As Single)) - - For Each item In _filesList - retList.Add((item.AnalysedFile, item.CompressionRatio)) - Next - - IsAlternate = Not IsAlternate ' Toggle the alternate mode for next run - - Return retList - - End Function - - - Public Function EstimateCompressabilityGZip(path As String, filesize As Long) As Double - - Using fs As FileStream = File.OpenRead(path) - Return EstimateCompressability(fs, filesize, Function(output) New GZipStream(output, CompressionLevel.Fastest, True)) - End Using - - End Function - - - Public Function EstimateCompressabilitySnappy(path As String, filesize As Long) As Double - - Using fs As FileStream = File.OpenRead(path) - Return EstimateCompressability(fs, filesize, Function(output) New Snappier.SnappyStream(output, Compression.CompressionMode.Compress, True)) - End Using - - End Function - - Public Function EstimateCompressabilityLZ4(path As String, filesize As Long, Optional cancellationToken As Threading.CancellationToken = Nothing) As Double - Try - Using fs As FileStream = File.OpenRead(path) - If IsHDD Then - Return EstimateCompressabilityHDD(fs, filesize, Function(output) LZ4Stream.Encode(output, LZ4Level.L00_FAST, 0, True), cancellationToken) - End If - Return EstimateCompressability(fs, filesize, Function(output) LZ4Stream.Encode(output, LZ4Level.L00_FAST, 0, True), cancellationToken) - End Using - Catch cancelledEx As OperationCanceledException - Throw - Catch ex As Exception - Return 1.0 ' If there's an error, assume it's incompressible - End Try - - End Function - - - Private Function EstimateCompressability(input As FileStream, fileSize As Long, compressionFactory As CompressionStreamFactory, Optional cancellationToken As Threading.CancellationToken = Nothing) As Double - - Dim totalBlocks As Long = fileSize \ BlockSize - Dim samplesNeeded As Integer = Math.Ceiling((totalBlocks * SampleSize) / (SampleSize + totalBlocks - 1)) - Dim totalWritten As Long = 0 - - Dim compressed = New MemoryStream() - Using compressionStream As Stream = compressionFactory(compressed) - - ' If file is small or sample count is zero, compress the whole file - If samplesNeeded = 0 OrElse fileSize < samplesNeeded * BlockSize * 2 Then - - Dim buffer(BlockSize - 1) As Byte - input.Position = 0 - Dim bytesRead As Integer = input.Read(buffer, 0, BlockSize) - - While bytesRead > 0 - cancellationToken.ThrowIfCancellationRequested() - compressionStream.Write(buffer, 0, bytesRead) - totalWritten += bytesRead - bytesRead = input.Read(buffer, 0, BlockSize) - End While - - Else - ' Sample evenly spaced blocks - Dim stepSize As Long = BlockSize * (totalBlocks \ samplesNeeded) - Dim buffer(BlockSize - 1) As Byte - For i As Integer = 0 To samplesNeeded - 1 - cancellationToken.ThrowIfCancellationRequested() - input.Position = stepSize * i - Dim bytesRead As Integer = input.Read(buffer, 0, BlockSize) - compressionStream.Write(buffer, 0, bytesRead) - totalWritten += bytesRead - Next - End If - End Using - - Return Math.Min(compressed.Length / Math.Max(totalWritten, 1), 1.0) - End Function - - - Private Function EstimateCompressabilityHDD(input As FileStream, fileSize As Long, compressionFactory As CompressionStreamFactory, Optional cancellationToken As Threading.CancellationToken = Nothing) As Double - Dim NumClusters As Integer = SampleSize ' or any small number you want to sample - Dim clusterSize As Integer = DiskClusterSize - - Dim middleCluster As Long = (fileSize \ 2) \ clusterSize - Dim alignedStart As Long = middleCluster * clusterSize - Dim chunkSize As Integer = CInt(Math.Min(clusterSize * NumClusters, fileSize - alignedStart)) - - Dim totalWritten As Long = 0 - Dim compressed = New MemoryStream() - - Using compressionStream As Stream = compressionFactory(compressed) - Dim buffer(chunkSize - 1) As Byte - input.Position = alignedStart - Dim bytesRead As Integer = input.Read(buffer, 0, chunkSize) - - If cancellationToken <> Nothing AndAlso cancellationToken.IsCancellationRequested Then - Throw New OperationCanceledException(cancellationToken) - End If - - If bytesRead > 0 Then - compressionStream.Write(buffer, 0, bytesRead) - totalWritten += bytesRead - End If - End Using - - Return Math.Min(compressed.Length / Math.Max(totalWritten, 1), 1.0) - End Function - - Public Function GetFirstLcn(filePath As String) As Long - - Dim handle As SafeFileHandle = File.OpenHandle(filePath) - - If handle.IsInvalid Then Throw New IOException("Failed to open file handle.") - - - Dim inBuffer As NtfsInterop.STARTING_VCN_INPUT_BUFFER - inBuffer.StartingVcn = 0 - Dim inBufferSize = Marshal.SizeOf(inBuffer) - Dim inBufferPtr = Marshal.AllocHGlobal(inBufferSize) - Marshal.StructureToPtr(inBuffer, inBufferPtr, False) - - Dim outBufferSize = 4096 - Dim outBufferPtr = Marshal.AllocHGlobal(outBufferSize) - Dim bytesReturned As Integer = 0 - - Try - Dim result = WOFHelper.DeviceIoControl( - handle, - NtfsInterop.FSCTL_GET_RETRIEVAL_POINTERS, - inBufferPtr, - inBufferSize, - outBufferPtr, - outBufferSize, - bytesReturned, - IntPtr.Zero - ) - - - - 'Probably errors because the file is empty - If Not result Then Return Long.MaxValue - - - ' Marshal the output buffer to get the first LCN - Dim extentOffset As Integer = Marshal.OffsetOf(Of RETRIEVAL_POINTERS_BUFFER)("Extents").ToInt32() - Dim lcn As Long = Marshal.ReadInt64(outBufferPtr, extentOffset + 8) - Return lcn - - Finally - Marshal.FreeHGlobal(inBufferPtr) - Marshal.FreeHGlobal(outBufferPtr) - handle.Close() - End Try - End Function - -End Class diff --git a/CompactGUI.CoreVB/FodyWeavers.xml b/CompactGUI.CoreVB/FodyWeavers.xml deleted file mode 100644 index 003b8f77..00000000 --- a/CompactGUI.CoreVB/FodyWeavers.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/CompactGUI.CoreVB/ICompressor.vb b/CompactGUI.CoreVB/ICompressor.vb deleted file mode 100644 index 0fadeabb..00000000 --- a/CompactGUI.CoreVB/ICompressor.vb +++ /dev/null @@ -1,7 +0,0 @@ -Public Interface ICompressor : Inherits IDisposable - Function RunAsync(filesList As List(Of String), Optional progressMonitor As IProgress(Of CompressionProgress) = Nothing, Optional maxParallelism As Integer = 1) As Task(Of Boolean) - Sub Pause() - Sub [Resume]() - Sub Cancel() - -End Interface diff --git a/CompactGUI.CoreVB/NtfsInterop.vb b/CompactGUI.CoreVB/NtfsInterop.vb deleted file mode 100644 index 560566b0..00000000 --- a/CompactGUI.CoreVB/NtfsInterop.vb +++ /dev/null @@ -1,42 +0,0 @@ -Imports System.Runtime.InteropServices - -Imports Microsoft.Win32.SafeHandles - -Friend Module NtfsInterop - Public Const FSCTL_GET_RETRIEVAL_POINTERS As UInteger = &H90073 - Public Const OPEN_EXISTING As Integer = 3 - Public Const FILE_FLAG_BACKUP_SEMANTICS As Integer = &H2000000 - Public Const FILE_SHARE_READ As Integer = 1 - Public Const FILE_SHARE_WRITE As Integer = 2 - Public Const GENERIC_READ As Integer = &H80000000 - - - Public Function CreateFile( - lpFileName As String, - dwDesiredAccess As Integer, - dwShareMode As Integer, - lpSecurityAttributes As IntPtr, - dwCreationDisposition As Integer, - dwFlagsAndAttributes As Integer, - hTemplateFile As IntPtr - ) As SafeFileHandle - End Function - - - Public Structure STARTING_VCN_INPUT_BUFFER - Public StartingVcn As Long - End Structure - - - Public Structure RETRIEVAL_POINTERS_BUFFER - Public ExtentCount As Integer - Public StartingVcn As Long - Public Extents As LCN_EXTENT ' This is actually an array, but we only need the first. ?Perhaps I should get the LCN of the middle cluster in future? - End Structure - - - Public Structure LCN_EXTENT - Public NextVcn As Long - Public Lcn As Long - End Structure -End Module \ No newline at end of file diff --git a/CompactGUI.CoreVB/SharedMethods.vb b/CompactGUI.CoreVB/SharedMethods.vb deleted file mode 100644 index 85214b29..00000000 --- a/CompactGUI.CoreVB/SharedMethods.vb +++ /dev/null @@ -1,199 +0,0 @@ -Imports System.IO -Imports System.Runtime.CompilerServices -Imports System.Runtime.InteropServices -Imports System.Text -Public Module SharedMethods - Public Enum FolderVerificationResult - Valid = 0 - DirectoryDoesNotExist - SystemDirectory - RootDirectory - DirectoryEmptyOrUnauthorized - OneDriveFolder - NonNTFSDrive - InsufficientPermission - End Enum - - Function verifyFolder(folder As String) As FolderVerificationResult - - If Not Directory.Exists(folder) Then : Return FolderVerificationResult.DirectoryDoesNotExist - ElseIf folder.ToLowerInvariant.Contains((Environment.GetFolderPath(Environment.SpecialFolder.Windows)).ToLowerInvariant) Then : Return FolderVerificationResult.SystemDirectory - ElseIf folder.EndsWith(":\") Then : Return FolderVerificationResult.RootDirectory - ElseIf IsDirectoryEmptySafe(folder) Then : Return FolderVerificationResult.DirectoryEmptyOrUnauthorized - ElseIf IsOneDriveFolder(folder) Then : Return FolderVerificationResult.OneDriveFolder - ElseIf DriveInfo.GetDrives().First(Function(f) folder.StartsWith(f.Name)).DriveFormat <> "NTFS" Then : Return FolderVerificationResult.NonNTFSDrive - ElseIf Not Analyser.HasDirectoryWritePermission(folder) Then : Return FolderVerificationResult.InsufficientPermission - End If - - Return FolderVerificationResult.Valid - - End Function - - - Function GetFolderVerificationMessage(result As FolderVerificationResult) As String - Select Case result - Case FolderVerificationResult.Valid - Return "" - Case FolderVerificationResult.DirectoryDoesNotExist - Return "Directory does not exist" - Case FolderVerificationResult.SystemDirectory - Return "Cannot compress system directory" - Case FolderVerificationResult.RootDirectory - Return "Cannot compress root directory" - Case FolderVerificationResult.DirectoryEmptyOrUnauthorized - Return "This directory is either empty or you are not authorized to access its files." - Case FolderVerificationResult.OneDriveFolder - Return "Files synced with OneDrive cannot be compressed as they use a different storage structure" - Case FolderVerificationResult.NonNTFSDrive - Return "Cannot compress a directory on a non-NTFS drive" - Case FolderVerificationResult.InsufficientPermission - Return "Insufficient permission to access this folder." - Case Else - Return "Unknown error" - End Select - End Function - - - - Function IsDirectoryEmptySafe(folder As String) - - Try - Return Not Directory.EnumerateFileSystemEntries(folder).Any() - - - Catch ex As UnauthorizedAccessException - Return False - - Catch ex As Exception - Return False - End Try - - End Function - - Function GetFileSizeOnDisk(file As String) As Long - Dim hosize As UInteger - Dim losize As UInteger = GetCompressedFileSizeW(file, hosize) - 'INVALID_FILE_SIZE (0xFFFFFFFF) - If losize = 4294967295 Then - Dim errCode As Integer - errCode = Marshal.GetLastPInvokeError() - If errCode <> 0 Then - Return -1 - End If - End If - Return CLng(hosize) << 32 Or losize - End Function - - - - Function AsShortPathNames(filesList As IEnumerable(Of String)) As List(Of String) - - Return filesList.Select(Of String) _ - (Function(fl) - If fl.Length >= 255 Then - Dim sfp = GetShortPath(fl) - If sfp IsNot Nothing Then Return sfp - End If - Return fl - End Function).ToList - - End Function - - - Function GetShortPath(filePath As String) As String - - If String.IsNullOrWhiteSpace(filePath) Then Return Nothing - Dim hasPrefix As Boolean = False - - If filePath.Length >= 255 AndAlso Not filePath.StartsWith("\\?\") Then - filePath = "\\?\" & filePath - hasPrefix = True - End If - - Dim shortPath = New StringBuilder(1024) - Dim res As Integer = GetShortPathName(filePath, shortPath, 1024) - If res = 0 Then Return Nothing - filePath = shortPath.ToString() - If hasPrefix Then filePath = filePath.Substring(4) - Return filePath - - End Function - - - Function GetClusterSize(folderPath As String) - - Dim lpSectorsPerCluster As UInteger - Dim lpBytesPerSector As UInteger - Dim res As Integer = GetDiskFreeSpace(New DirectoryInfo(folderPath).Root.ToString, lpSectorsPerCluster, lpBytesPerSector, Nothing, Nothing) - Return lpSectorsPerCluster * lpBytesPerSector - - End Function - - Function IsOneDriveFolder(folderPath As String) As Boolean - Dim userProfile As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) - Dim oneDrivePaths As New List(Of String) From { - Path.Combine(userProfile, "OneDrive"), ' Personal OneDrive - Path.Combine(userProfile, "OneDrive - Personal"), ' Alternative Personal OneDrive - Path.Combine(userProfile, "OneDrive for Business"), ' OneDrive for Business - Path.Combine(userProfile, "OneDrive - Business") ' Alternative OneDrive for Business - } - - ' Normalize the folder path to compare - Dim normalizedFolderPath As String = Path.GetFullPath(folderPath).TrimEnd(Path.DirectorySeparatorChar).ToLowerInvariant() - - ' Check if the folder path starts with any of the known OneDrive paths - Return oneDrivePaths.Any(Function(odPath) normalizedFolderPath.StartsWith(Path.GetFullPath(odPath).TrimEnd(Path.DirectorySeparatorChar).ToLowerInvariant())) - End Function - - Public Sub PreventSleep() - SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS Or EXECUTION_STATE.ES_SYSTEM_REQUIRED Or EXECUTION_STATE.ES_DISPLAY_REQUIRED) - End Sub - Public Sub RestoreSleep() - SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS) - End Sub - - -#Region "DLL Imports" - - - Private Function GetCompressedFileSizeW( - <[In](), MarshalAs(UnmanagedType.LPWStr)> lpFileName As String, - ByRef lpFileSizeHigh As UInteger) _ - As UInteger - End Function - - - Private Function GetShortPathName( - path As String, - shortPath As StringBuilder, shortPathLength As Integer) As Integer - - End Function - - - - - Private Function GetDiskFreeSpace( - lpRootPathName As String, - ByRef lpSectorsPerCluster As UInteger, - ByRef lpBytesPerSector As UInteger, - ByRef lpNumberOfFreeClusters As UInteger, - ByRef lpTotalNumberOfClusters As UInteger) As Boolean - End Function - - - - Private Function SetThreadExecutionState(esFlags As EXECUTION_STATE) As EXECUTION_STATE - End Function - - - Private Enum EXECUTION_STATE As UInteger - ES_AWAYMODE_REQUIRED = &H40 - ES_CONTINUOUS = &H80000000UI - ES_DISPLAY_REQUIRED = &H2 - ES_SYSTEM_REQUIRED = &H1 - End Enum - -#End Region - - -End Module diff --git a/CompactGUI.CoreVB/SharedObjects.vb b/CompactGUI.CoreVB/SharedObjects.vb deleted file mode 100644 index b0ddb85b..00000000 --- a/CompactGUI.CoreVB/SharedObjects.vb +++ /dev/null @@ -1,54 +0,0 @@ -Public Class AnalysedFileDetails - - Public Property FileName As String - Public Property UncompressedSize As Long - Public Property CompressedSize As Long - Public Property CompressionMode As WOFCompressionAlgorithm - Public Property FileInfo As IO.FileInfo -End Class - - -'Used to track efficiency of compression and built results for submission to wiki -Public Class ExtensionResult - - Public Property extension As String - Public Property uncompressedBytes As Long - Public Property compressedBytes As Long - Public Property totalFiles As Integer - ReadOnly Property cRatio As Decimal - Get - Return Math.Round(compressedBytes / uncompressedBytes, 2) - End Get - End Property - -End Class - -Public Structure CompressionProgress - Public ProgressPercent As Integer - Public FileName As String - - Public Sub New(_progressPercent As Integer, _fileName As String) - ProgressPercent = _progressPercent - FileName = _fileName - End Sub - -End Structure - - - -Public Enum CompressionMode - XPRESS4K - XPRESS8K - XPRESS16K - LZX - None -End Enum - -Public Enum WOFCompressionAlgorithm - NO_COMPRESSION = -2 - LZNT1 = -1 - XPRESS4K = 0 - LZX = 1 - XPRESS8K = 2 - XPRESS16K = 3 -End Enum \ No newline at end of file diff --git a/CompactGUI.CoreVB/Uncompactor.vb b/CompactGUI.CoreVB/Uncompactor.vb deleted file mode 100644 index 6d6aae15..00000000 --- a/CompactGUI.CoreVB/Uncompactor.vb +++ /dev/null @@ -1,85 +0,0 @@ -Imports System.IO -Imports System.Threading - -Imports Microsoft.Win32.SafeHandles - -Public Class Uncompactor : Implements ICompressor, IDisposable - - - Private _pauseSemaphore As New SemaphoreSlim(1, 2) - Private _processedFileCount As New Concurrent.ConcurrentDictionary(Of String, Integer) - Private _cancellationTokenSource As New CancellationTokenSource - - - Public Async Function RunAsync(filesList As List(Of String), Optional progressMonitor As IProgress(Of CompressionProgress) = Nothing, Optional MaxParallelism As Integer = 1) As Task(Of Boolean) Implements ICompressor.RunAsync - - Dim totalFiles As Integer = filesList.Count - If MaxParallelism <= 0 Then MaxParallelism = Environment.ProcessorCount - Dim paraOptions As New ParallelOptions With {.MaxDegreeOfParallelism = MaxParallelism} - - _processedFileCount.Clear() - Try - Await Parallel.ForEachAsync(filesList, paraOptions, - Function(file, _ctx) As ValueTask - _ctx.ThrowIfCancellationRequested() - Return New ValueTask(PauseAndProcessFile(file, totalFiles, _cancellationTokenSource.Token, progressMonitor)) - End Function).ConfigureAwait(False) - Catch ex As OperationCanceledException - Return False - End Try - - Return True - - End Function - - Private Async Function PauseAndProcessFile(file As String, totalFiles As Integer, _ctx As CancellationToken, progressMonitor As IProgress(Of CompressionProgress)) As Task - - Try - Await _pauseSemaphore.WaitAsync(_ctx).ConfigureAwait(False) - _pauseSemaphore.Release() - Catch ex As OperationCanceledException - Throw - Return - End Try - - _ctx.ThrowIfCancellationRequested() - - Dim res = WOFDecompressFile(file) - _processedFileCount.TryAdd(file, 1) - - progressMonitor?.Report(New CompressionProgress((CInt(((_processedFileCount.Count / totalFiles) * 100))), file)) - - End Function - - Private Function WOFDecompressFile(path As String) - - Try - Using fs As SafeFileHandle = File.OpenHandle(path) - Dim res = WOFHelper.DeviceIoControl(fs, FSCTL_DELETE_EXTERNAL_BACKING, IntPtr.Zero, 0, IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero) - Return res - End Using - Catch ex As Exception - Debug.WriteLine(ex.Message) - Return Nothing - End Try - - End Function - - - Public Sub Pause() Implements ICompressor.Pause - _pauseSemaphore.Wait() - End Sub - - Public Sub [Resume]() Implements ICompressor.Resume - If _pauseSemaphore.CurrentCount = 0 Then _pauseSemaphore.Release() - End Sub - Public Sub Cancel() Implements ICompressor.Cancel - [Resume]() - _cancellationTokenSource.Cancel() - End Sub - - Public Sub Dispose() Implements IDisposable.Dispose - _pauseSemaphore?.Dispose() - _cancellationTokenSource?.Dispose() - End Sub -End Class diff --git a/CompactGUI.CoreVB/WOFHelper.vb b/CompactGUI.CoreVB/WOFHelper.vb deleted file mode 100644 index 36ff9f8b..00000000 --- a/CompactGUI.CoreVB/WOFHelper.vb +++ /dev/null @@ -1,83 +0,0 @@ -Imports System.Runtime.InteropServices - -Imports Microsoft.Win32.SafeHandles - -Public Module WOFHelper - - Public Const WOF_PROVIDER_FILE As ULong = 2 - Public Const FSCTL_DELETE_EXTERNAL_BACKING As UInteger = &H90314 - - Public Function WOFConvertCompressionLevel(compressionlevel As Integer) As Integer - - Select Case compressionlevel - Case 0 : Return WOFCompressionAlgorithm.XPRESS4K - Case 1 : Return WOFCompressionAlgorithm.XPRESS8K - Case 2 : Return WOFCompressionAlgorithm.XPRESS16K - Case 3 : Return WOFCompressionAlgorithm.LZX - Case Else : Return WOFCompressionAlgorithm.XPRESS4K - End Select - - End Function - - Public Function WOFConvertCompressionLevel(compressionlevel As CompressionMode) As Integer - Select Case compressionlevel - Case CompressionMode.XPRESS4K : Return WOFCompressionAlgorithm.XPRESS4K - Case CompressionMode.XPRESS8K : Return WOFCompressionAlgorithm.XPRESS8K - Case CompressionMode.XPRESS16K : Return WOFCompressionAlgorithm.XPRESS16K - Case CompressionMode.LZX : Return WOFCompressionAlgorithm.LZX - Case Else : Return WOFCompressionAlgorithm.XPRESS4K - End Select - End Function - - - Public Function WOFConvertBackCompressionLevel(WOFCompressionLevel As WOFCompressionAlgorithm) As Integer - - Select Case WOFCompressionLevel - Case WOFCompressionAlgorithm.XPRESS4K : Return 0 - Case WOFCompressionAlgorithm.XPRESS8K : Return 1 - Case WOFCompressionAlgorithm.XPRESS16K : Return 2 - Case WOFCompressionAlgorithm.LZX : Return 3 - Case Else : Return 0 - End Select - - End Function - - - Public Structure WOF_FILE_COMPRESSION_INFO_V1 - Public Algorithm As UInteger - Public Flags As UInteger - End Structure - - - - Friend Function WofIsExternalFile( - Filepath As String, - ByRef IsExternalFile As Integer, - ByRef Provider As UInteger, - ByRef Info As WOF_FILE_COMPRESSION_INFO_V1, - ByRef BufferLength As UInteger) As Integer - End Function - - - Friend Function WofSetFileDataLocation( - FileHandle As SafeFileHandle, - Provider As ULong, - ExternalFileInfo As IntPtr, - Length As ULong) As Integer - End Function - - 'Most of these should be optional if MS Docs are to be believed -.- - - Friend Function DeviceIoControl( - hDevice As SafeFileHandle, - dwIoControlCode As UInteger, - lpInBuffer As IntPtr, - nInBufferSize As UInteger, - lpOutBuffer As IntPtr, - nOutBufferSize As UInteger, - ByRef lpBytesReturned As IntPtr, - lpOverlapped As IntPtr) As Boolean - - End Function - -End Module diff --git a/CompactGUI.Logging/CompactGUI.Logging.csproj b/CompactGUI.Logging/CompactGUI.Logging.csproj index 2dbdff00..cb304efb 100644 --- a/CompactGUI.Logging/CompactGUI.Logging.csproj +++ b/CompactGUI.Logging/CompactGUI.Logging.csproj @@ -1,7 +1,7 @@  - net9.0 + net10.0 enable enable diff --git a/CompactGUI.Logging/Core/CompactorLog.cs b/CompactGUI.Logging/Core/CompactorLog.cs index 0033d3f7..f17f5889 100644 --- a/CompactGUI.Logging/Core/CompactorLog.cs +++ b/CompactGUI.Logging/Core/CompactorLog.cs @@ -22,6 +22,9 @@ public static partial class CompactorLog [LoggerMessage(Level = LogLevel.Warning, Message = "File compression failed for: {FileName} with error: {ErrorMessage}")] public static partial void FileCompressionFailed(ILogger logger, string fileName, string errorMessage); + [LoggerMessage(Level = LogLevel.Warning, Message = "Compression did not start because the free-space reserve was not met on {Drive}. Available: {AvailableBytes} bytes; reserve: {ReserveBytes} bytes.")] + public static partial void FreeSpaceReserveReached(ILogger logger, string drive, long availableBytes, long reserveBytes); + [LoggerMessage(Level = LogLevel.Information, Message = "Compression paused.")] public static partial void CompressionPaused(ILogger logger); diff --git a/CompactGUI.Logging/Core/UncompactorLog.cs b/CompactGUI.Logging/Core/UncompactorLog.cs index cb8a1d73..1afde2fe 100644 --- a/CompactGUI.Logging/Core/UncompactorLog.cs +++ b/CompactGUI.Logging/Core/UncompactorLog.cs @@ -27,6 +27,9 @@ public static partial class UncompactorLog [LoggerMessage(Level = LogLevel.Information, Message = "Decompression canceled.")] public static partial void DecompressionCanceled(ILogger logger); + [LoggerMessage(Level = LogLevel.Error, Message = "Decompression failed with error: {ErrorMessage}")] + public static partial void DecompressionFailed(ILogger logger, string errorMessage); + [LoggerMessage(Level = LogLevel.Information, Message = "Decompression completed successfully in {TimeTaken}s.")] public static partial void DecompressionCompleted(ILogger logger, double timeTaken); } diff --git a/CompactGUI.Tests/CompactGUI.Tests.csproj b/CompactGUI.Tests/CompactGUI.Tests.csproj new file mode 100644 index 00000000..f4aac735 --- /dev/null +++ b/CompactGUI.Tests/CompactGUI.Tests.csproj @@ -0,0 +1,27 @@ + + + + net10.0-windows + enable + enable + false + + + + + + + + + + + + + + + + + + + + diff --git a/CompactGUI.Tests/PathVerificationTests.cs b/CompactGUI.Tests/PathVerificationTests.cs new file mode 100644 index 00000000..c70c5297 --- /dev/null +++ b/CompactGUI.Tests/PathVerificationTests.cs @@ -0,0 +1,17 @@ +using CompactGUI.Core; + +namespace CompactGUI.Tests; + +public class PathVerificationTests +{ + [Theory] + [InlineData(@"C:\Windows", @"C:\Windows", true)] + [InlineData(@"C:\Windows\System32", @"C:\Windows", true)] + [InlineData(@"C:\WindowsBackup", @"C:\Windows", false)] + [InlineData(@"C:\Users\Sam\OneDrive - Personal\Games", @"C:\Users\Sam\OneDrive - Personal", true)] + [InlineData(@"C:\Users\Sam\OneDrive - Personal Backup", @"C:\Users\Sam\OneDrive - Personal", false)] + public void DirectoryMatchRequiresPathBoundary(string path, string directory, bool expected) + { + Assert.Equal(expected, SharedMethods.IsPathWithinDirectory(path, directory)); + } +} diff --git a/CompactGUI.Tests/WatcherAutostartTests.cs b/CompactGUI.Tests/WatcherAutostartTests.cs new file mode 100644 index 00000000..0b2dac38 --- /dev/null +++ b/CompactGUI.Tests/WatcherAutostartTests.cs @@ -0,0 +1,44 @@ +using Microsoft.Win32; + +namespace CompactGUI.Tests; + +public class WatcherAutostartTests +{ + [Fact] + public void RunEntryFollowsWatchedFolderCountAndQuotesExecutablePath() + { + var subkeyPath = $@"Software\CompactGUI.WatcherTests.{Guid.NewGuid():N}"; + try + { + using var testRoot = Registry.CurrentUser.CreateSubKey(subkeyPath); + Assert.NotNull(testRoot); + const string executablePath = @"C:\Program Files\CompactGUI\CompactGUI.exe"; + + Assert.True(CompactGUI.Watcher.Watcher.UpdateRegistryBasedOnWatchedFolders(testRoot, "Run", 0, executablePath)); + Assert.Null(testRoot.OpenSubKey("Run")); + + Assert.True(CompactGUI.Watcher.Watcher.UpdateRegistryBasedOnWatchedFolders(testRoot, "Run", 1, executablePath)); + using var testKey = testRoot.OpenSubKey("Run"); + Assert.NotNull(testKey); + Assert.Equal(@"""C:\Program Files\CompactGUI\CompactGUI.exe"" -tray", testKey.GetValue("CompactGUI")); + + Assert.True(CompactGUI.Watcher.Watcher.UpdateRegistryBasedOnWatchedFolders(testRoot, "Run", 2, executablePath)); + Assert.Equal(@"""C:\Program Files\CompactGUI\CompactGUI.exe"" -tray", testKey.GetValue("CompactGUI")); + + Assert.True(CompactGUI.Watcher.Watcher.UpdateRegistryBasedOnWatchedFolders(testRoot, "Run", 1, executablePath)); + Assert.Equal(@"""C:\Program Files\CompactGUI\CompactGUI.exe"" -tray", testKey.GetValue("CompactGUI")); + + Assert.True(CompactGUI.Watcher.Watcher.UpdateRegistryBasedOnWatchedFolders(testRoot, "Run", 0, executablePath)); + Assert.Null(testKey.GetValue("CompactGUI")); + + using var readOnlyRoot = Registry.CurrentUser.OpenSubKey(subkeyPath, writable: false); + Assert.NotNull(readOnlyRoot); + Assert.False(CompactGUI.Watcher.Watcher.UpdateRegistryBasedOnWatchedFolders(readOnlyRoot, "Denied", 1, executablePath)); + Assert.Null(testRoot.OpenSubKey("Denied")); + } + finally + { + Registry.CurrentUser.DeleteSubKeyTree(subkeyPath, throwOnMissingSubKey: false); + } + } +} diff --git a/CompactGUI.Watcher/BackgroundCompactor.vb b/CompactGUI.Watcher/BackgroundCompactor.vb index 2b23b322..e9f3791b 100644 --- a/CompactGUI.Watcher/BackgroundCompactor.vb +++ b/CompactGUI.Watcher/BackgroundCompactor.vb @@ -26,6 +26,8 @@ Public Class BackgroundCompactor Private isCompactingPaused As Boolean = False ' Track if compacting is paused Private _compactor As Core.Compactor + Private _compactorAnalyser As Core.Analyser + Private _settingsService As Core.Settings.ISettingsService Private _excludedFileTypes As String() @@ -35,114 +37,163 @@ Public Class BackgroundCompactor Public Event IsCompactingEvent As EventHandler(Of Boolean) - Public Sub New(excludedFileTypes As String(), logger As ILogger(Of Watcher)) + Public Sub New(excludedFileTypes As String(), logger As ILogger(Of Watcher), settingsService As Core.Settings.ISettingsService) _excludedFileTypes = excludedFileTypes _logger = logger + _settingsService = settingsService End Sub - Public Function BeginCompacting(folder As String, compressionLevel As Core.WOFCompressionAlgorithm) As Task(Of Boolean) + Public Async Function BeginCompacting(folder As String, compressionLevel As Core.WOFCompressionAlgorithm, Optional excludedFileTypes As String() = Nothing) As Task(Of Boolean) - If compressionLevel = Core.WOFCompressionAlgorithm.NO_COMPRESSION Then Return Task.FromResult(False) + If compressionLevel = Core.WOFCompressionAlgorithm.NO_COMPRESSION Then Return False - _compactor = New Core.Compactor(folder, compressionLevel, _excludedFileTypes, New Core.Analyser(folder, NullLogger(Of Core.Analyser).Instance)) + Dim effectiveExclusions = If(excludedFileTypes Is Nothing, _excludedFileTypes, excludedFileTypes) - Return _compactor.RunAsync(Nothing) + _compactorAnalyser = New Core.Analyser(folder, NullLogger(Of Core.Analyser).Instance) + Dim analysedFiles = Await _compactorAnalyser.GetAnalysedFilesAsync(cancellationTokenSource.Token) + If cancellationTokenSource.IsCancellationRequested OrElse analysedFiles Is Nothing Then Return False + + Dim bypassLowSpaceProtection = _settingsService.AppSettings.BypassLowSpaceProtection + If Not bypassLowSpaceProtection AndAlso Not Core.SharedMethods.HasSufficientFreeSpaceForCompression(folder, analysedFiles, compressionLevel, effectiveExclusions) Then Return False + + _compactor = New Core.Compactor(folder, compressionLevel, effectiveExclusions, _compactorAnalyser, bypassLowSpaceProtection) + If isCompactingPaused Then _compactor.Pause() + + Return Await _compactor.RunAsync() End Function Public Async Function StartCompactingAsync(folders As IEnumerable(Of WatchedFolder)) As Task(Of Boolean) WatcherLog.BackgroundCompactingStarted(_logger) + cancellationTokenSource = New CancellationTokenSource() - IsCompactorActive = True + Dim currentProcess = Process.GetCurrentProcess() + Dim originalPriority = currentProcess.PriorityClass - Dim currentProcess As Process = Process.GetCurrentProcess() - currentProcess.PriorityClass = ProcessPriorityClass.Idle + Try + IsCompactorActive = True + isCompacting = True + currentProcess.PriorityClass = ProcessPriorityClass.Idle - isCompacting = True + For Each folder In folders.ToList() + If cancellationTokenSource.IsCancellationRequested Then Return False + If Not Await CompactFolderAsync(folder, folders) Then Return False - For Each folder In folders.ToList - folder.IsWorking = True + WatcherLog.FinishedCompactingFolder(_logger, folder.DisplayName) + Next - WatcherLog.CompactingFolder(_logger, folder.DisplayName) - Dim compactingTask = BeginCompacting(folder.Folder, folder.CompressionLevel) + WatcherLog.BackgroundCompactingFinished(_logger) + Return True + Finally + IsCompactorActive = False + isCompacting = False + isCompactingPaused = False + cancellationTokenSource.Dispose() + cancellationTokenSource = Nothing - If cancellationTokenSource.IsCancellationRequested Then - Trace.WriteLine("Compacting cancelled by user.") - folder.IsWorking = False - IsCompactorActive = False - isCompacting = False ' Ensure compacting status is reset after operation - _compactor.Dispose() - Return False - End If + currentProcess.PriorityClass = originalPriority + currentProcess.Dispose() + End Try + End Function - Dim result = Await compactingTask - If result AndAlso folders.Contains(folder) Then - ' Ensure the folder is still in the original collection before updating + Private Async Function CompactFolderAsync(folder As WatchedFolder, folders As IEnumerable(Of WatchedFolder)) As Task(Of Boolean) + folder.IsWorking = True - Dim analyser As New Core.Analyser(folder.Folder, NullLogger(Of Core.Analyser).Instance) + Try + WatcherLog.CompactingFolder(_logger, folder.DisplayName) - Dim analysed = Await analyser.GetAnalysedFilesAsync(Nothing) + Dim folderSkipList = If(folder.SkipList Is Nothing, Array.Empty(Of String)(), folder.SkipList.ToArray()) + Dim compactingTask = BeginCompacting(folder.Folder, folder.CompressionLevel, folderSkipList) - folder.LastCheckedDate = DateTime.Now - folder.LastCheckedSize = analyser.CompressedBytes - folder.LastCompressedSize = analyser.CompressedBytes - folder.LastSystemModifiedDate = DateTime.Now - Dim mainCompressionLVL = analysed.Select(Function(f) f.CompressionMode).Max - folder.CompressionLevel = mainCompressionLVL + If cancellationTokenSource.IsCancellationRequested Then _compactor?.Cancel() - folder.LastCompressedDate = DateTime.Now + Dim result = Await compactingTask - folder.HasTargetChanged = False + If cancellationTokenSource.IsCancellationRequested Then Return False + If result AndAlso folders.Contains(folder) Then + Await UpdateFolderStatisticsAsync(folder) End If + + Return True + Finally + DisposeCurrentCompactor() folder.IsWorking = False folder.RefreshProperties() - _compactor.Dispose() - WatcherLog.FinishedCompactingFolder(_logger, folder.DisplayName) - Next + End Try + End Function - IsCompactorActive = False - isCompacting = False ' Ensure compacting status is reset after operation - WatcherLog.BackgroundCompactingFinished(_logger) - currentProcess.PriorityClass = ProcessPriorityClass.Normal - Return True + Private Async Function UpdateFolderStatisticsAsync(folder As WatchedFolder) As Task + Using analyser As New Core.Analyser(folder.Folder, NullLogger(Of Core.Analyser).Instance) + Dim analysed = Await analyser.GetAnalysedFilesAsync(CancellationToken.None) + + folder.LastCheckedDate = DateTime.Now + folder.LastCheckedSize = analyser.CompressedBytes + folder.LastCompressedSize = analyser.CompressedBytes + folder.LastSystemModifiedDate = DateTime.Now + + If analysed IsNot Nothing AndAlso analysed.Count > 0 Then + folder.CompressionLevel = analysed.Max(Function(file) file.CompressionMode) + End If + + folder.LastCompressedDate = DateTime.Now + folder.HasTargetChanged = False + End Using End Function + Private Sub FinishRun(runCancellation As CancellationTokenSource, currentProcess As Process, originalPriority As ProcessPriorityClass) + If ReferenceEquals(cancellationTokenSource, runCancellation) Then cancellationTokenSource = Nothing + + runCancellation.Dispose() + + IsCompactorActive = False + isCompacting = False + isCompactingPaused = False + + Try + currentProcess.PriorityClass = originalPriority + Finally + currentProcess.Dispose() + End Try + End Sub + Public Sub PauseCompacting() - If Not isCompacting OrElse isCompactingPaused Then - Return - End If + If Not isCompacting OrElse isCompactingPaused Then Return WatcherLog.PausingBackgroundCompactor(_logger) - isCompactingPaused = True ' Indicate compacting is paused + isCompactingPaused = True _compactor?.Pause() End Sub Public Sub ResumeCompacting() - If Not isCompactingPaused OrElse Not isCompacting Then - Return - End If + If Not isCompactingPaused OrElse Not isCompacting Then Return WatcherLog.ResumingBackgroundCompactor(_logger) - isCompactingPaused = False ' Indicate compacting is no longer paused + isCompactingPaused = False _compactor?.Resume() End Sub Public Sub CancelCompacting() - If Not isCompacting Then - Return - End If + If Not isCompacting Then Return + Debug.WriteLine("Cancelling background compactor...") - cancellationTokenSource.Cancel() - cancellationTokenSource.Dispose() + + cancellationTokenSource?.Cancel() _compactor?.Cancel() - _compactor?.Dispose() - isCompacting = False - isCompactingPaused = False ' Reset pause state on cancellation + End Sub + + Private Sub DisposeCurrentCompactor() + Dim compactor = _compactor + _compactor = Nothing + compactor?.Dispose() + + Dim analyser = _compactorAnalyser + _compactorAnalyser = Nothing + analyser?.Dispose() End Sub End Class diff --git a/CompactGUI.Watcher/CompactGUI.Watcher.vbproj b/CompactGUI.Watcher/CompactGUI.Watcher.vbproj index ee9f0bd1..04e44528 100644 --- a/CompactGUI.Watcher/CompactGUI.Watcher.vbproj +++ b/CompactGUI.Watcher/CompactGUI.Watcher.vbproj @@ -2,7 +2,7 @@ CompactGUI.Watcher - net9.0-windows + net10.0-windows @@ -20,4 +20,8 @@ + + + + diff --git a/CompactGUI.Watcher/WatchedFolder.vb b/CompactGUI.Watcher/WatchedFolder.vb index 23d55821..efaf659d 100644 --- a/CompactGUI.Watcher/WatchedFolder.vb +++ b/CompactGUI.Watcher/WatchedFolder.vb @@ -20,6 +20,7 @@ Public Class WatchedFolder Private _LastCheckedDate As DateTime Private _LastCheckedSize As Long Private _CompressionLevel As Core.WOFCompressionAlgorithm + Private _SkipList As List(Of String) Private _IsWorking As Boolean @@ -27,6 +28,9 @@ Public Class WatchedFolder Private _IsEditing As Boolean = False + + Private _IsDriveUnavailable As Boolean = False + ' --- Monitoring State --- Private _HasTargetChanged As Boolean = False @@ -65,13 +69,13 @@ Public Class WatchedFolder End Sub Public Sub PauseMonitoring() - If FSWatcher IsNot Nothing Then + If FSWatcher IsNot Nothing AndAlso Not IsDriveUnavailable Then FSWatcher.EnableRaisingEvents = False End If End Sub Public Sub ResumeMonitoring() - If FSWatcher IsNot Nothing Then + If FSWatcher IsNot Nothing AndAlso Not IsDriveUnavailable Then FSWatcher.EnableRaisingEvents = True End If End Sub @@ -130,4 +134,4 @@ Public Class WatchedFolder Dispose(disposing:=True) GC.SuppressFinalize(Me) End Sub -End Class \ No newline at end of file +End Class diff --git a/CompactGUI.Watcher/Watcher.vb b/CompactGUI.Watcher/Watcher.vb index cadaf4d6..27d20480 100644 --- a/CompactGUI.Watcher/Watcher.vb +++ b/CompactGUI.Watcher/Watcher.vb @@ -20,7 +20,7 @@ Imports Microsoft.Win32 Imports Microsoft.Win32.Registry -Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipient(Of PropertyChangedMessage(Of Boolean)) +Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipient(Of PropertyChangedMessage(Of Boolean)), IRecipient(Of PropertyChangedMessage(Of BackgroundMode)) Private ReadOnly _DataFolder As IO.DirectoryInfo Private ReadOnly _parseWatchersSemaphore As New SemaphoreSlim(1, 1) @@ -63,7 +63,7 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi AddHandler WatchedFolders.CollectionChanged, AddressOf WatchedFolders_CollectionChanged - BGCompactor = New BackgroundCompactor(Array.Empty(Of String), _logger) + BGCompactor = New BackgroundCompactor(Array.Empty(Of String), _logger, settingsService) InitializeWatchedFoldersAsync() @@ -83,6 +83,7 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi If bgMode <> BackgroundMode.IdleOnly Then Return BGCompactor.ResumeCompacting() + If IsRunning Then Return Await RunWatcher(False) @@ -93,15 +94,11 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi Private _isRunning As Boolean = False Public Async Function RunWatcher(Optional runAll As Boolean = True, Optional cToken As CancellationToken = Nothing) As Task(Of Boolean) - RemoveHandler _idleDetector.IsIdle, _idleHandler - IsRunning = True - - For Each watcher In WatchedFolders - watcher.PauseMonitoring() - Next - Try + For Each watcher In WatchedFolders + watcher.PauseMonitoring() + Next _settingsService.AppSettings.ScheduledBackgroundLastRan = DateTime.Now If Not IsWatchingEnabled Then Return False @@ -127,8 +124,6 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi Catch ex As TaskCanceledException Return False Finally - - AddHandler _idleDetector.IsIdle, _idleHandler For Each watcher In WatchedFolders watcher.ResumeMonitoring() Next @@ -198,24 +193,53 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi WatchedFolders.Clear() - For Each folder In initialWatchedFolders.Where(Function(f) IO.Directory.Exists(f.Folder)) - WatchedFolders.Add(folder) + For Each folder In initialWatchedFolders + If IO.Directory.Exists(folder.Folder) Then + folder.IsDriveUnavailable = False + folder.InitializeMonitoring() + ElseIf IsRootUnavailable(folder.Folder) Then + folder.IsDriveUnavailable = True + Else + Continue For + End If + folder.LastChangedDate = folder.LastSystemModifiedDate + WatchedFolders.Add(folder) Next UpdateRegistryBasedOnWatchedFolders() End Function Private Sub UpdateRegistryBasedOnWatchedFolders() - Dim registryKey As RegistryKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True) - - If WatchedFolders.Count > 0 Then - registryKey.SetValue("CompactGUI", Environment.ProcessPath & " -tray") - Else - registryKey.DeleteValue("CompactGUI", False) + 'Autostart is best-effort; registry access should not break folder management. + If Not UpdateRegistryBasedOnWatchedFolders(Registry.CurrentUser, "Software\Microsoft\Windows\CurrentVersion\Run", WatchedFolders.Count, Environment.ProcessPath) Then + _logger.LogWarning("Could not update CompactGUI watcher autostart.") End If End Sub + Friend Shared Function UpdateRegistryBasedOnWatchedFolders(rootKey As RegistryKey, subKeyPath As String, watchedFolderCount As Integer, processPath As String) As Boolean + Try + 'Don't create the Run key just to remove an entry that may not exist. + Dim registryKey = If(watchedFolderCount > 0, + rootKey.CreateSubKey(subKeyPath), + rootKey.OpenSubKey(subKeyPath, True)) + If registryKey Is Nothing Then Return watchedFolderCount = 0 + + Using registryKey + If watchedFolderCount > 0 Then + registryKey.SetValue("CompactGUI", """" & processPath & """" & " -tray") + Else + registryKey.DeleteValue("CompactGUI", False) + End If + End Using + Return True + Catch ex As Exception When TypeOf ex Is UnauthorizedAccessException OrElse + TypeOf ex Is Security.SecurityException OrElse + TypeOf ex Is IO.IOException + Return False + End Try + End Function + Public Sub AddOrUpdateWatched(item As WatchedFolder, Optional immediateFlushToDisk As Boolean = True) @@ -228,6 +252,7 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi End If OnPropertyChanged(NameOf(TotalSaved)) If immediateFlushToDisk Then WriteToFile() + If existingItem Is Nothing Then UpdateRegistryBasedOnWatchedFolders() End Sub @@ -273,6 +298,7 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi .LastCheckedSize = newItem.LastCheckedSize .LastSystemModifiedDate = DateTime.Now .CompressionLevel = If(newItem.CompressionLevel <> WOFCompressionAlgorithm.NO_COMPRESSION, newItem.CompressionLevel, existingItem.CompressionLevel) + .SkipList = newItem.SkipList End With existingItem.HasTargetChanged = False End Sub @@ -282,6 +308,7 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi item.Dispose() WatchedFolders.Remove(item) If writeToFile Then Await WriteToFileAsync() + UpdateRegistryBasedOnWatchedFolders() End Function @@ -289,16 +316,34 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi Public Async Function DeleteWatchersWithNonExistentFolders() As Task For i As Integer = WatchedFolders.Count - 1 To 0 Step -1 - If Not IO.Directory.Exists(WatchedFolders(i).Folder) Then - WatcherLog.RemovingNonexistentFolders(_logger, 1) - Await RemoveWatched(WatchedFolders(i), False) + Dim watchedFolder = WatchedFolders(i) + + If IO.Directory.Exists(watchedFolder.Folder) Then + If watchedFolder.IsDriveUnavailable Then watchedFolder.InitializeMonitoring() + watchedFolder.IsDriveUnavailable = False + Continue For End If + + watchedFolder.IsDriveUnavailable = IsRootUnavailable(watchedFolder.Folder) + If watchedFolder.IsDriveUnavailable Then Continue For + + WatcherLog.RemovingNonexistentFolders(_logger, 1) + Await RemoveWatched(watchedFolder, False) Next Await WriteToFileAsync() End Function + Private Shared Function IsRootUnavailable(folderPath As String) As Boolean + Try + Dim rootPath = IO.Path.GetPathRoot(folderPath) + Return Not String.IsNullOrWhiteSpace(rootPath) AndAlso Not IO.Directory.Exists(rootPath) + Catch ex As Exception When TypeOf ex Is ArgumentException OrElse TypeOf ex Is IO.IOException OrElse TypeOf ex Is UnauthorizedAccessException + Return False + End Try + End Function + Private Async Function GetWatchedFoldersFromJson() As Task(Of ObservableCollection(Of WatchedFolder)) @@ -325,12 +370,6 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi Try validatedResult = JsonSerializer.Deserialize(Of (DateTime, ObservableCollection(Of WatchedFolder)))(WatcherJSON, DeserializeOptions) - If validatedResult.Item2 IsNot Nothing Then - For Each folder In validatedResult.Item2.Where(Function(f) IO.Directory.Exists(f.Folder)) - folder.InitializeMonitoring() - Next - End If - Catch ex As Exception validatedResult = (DateTime.Now, Nothing) WatcherLog.DeserializeWatcherJsonFailed(_logger, ex.Message) @@ -363,10 +402,7 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi WatcherLog.ParsingWatchers(_logger, ParseAll) Await DeleteWatchersWithNonExistentFolders() - Dim WatchersQuery = If(ParseAll, - WatchedFolders, - WatchedFolders.Where(Function(w) w.HasTargetChanged) - ).OrderBy(Function(f) f.DisplayName) + Dim WatchersQuery = WatchedFolders.Where(Function(w) Not w.IsDriveUnavailable AndAlso (ParseAll OrElse w.HasTargetChanged)).OrderBy(Function(f) f.DisplayName) If Not WatchersQuery.Any() Then Return @@ -395,10 +431,14 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi Try If watchedFolder Is Nothing Then Return If Not IO.Directory.Exists(watchedFolder.Folder) Then + watchedFolder.IsDriveUnavailable = IsRootUnavailable(watchedFolder.Folder) + If watchedFolder.IsDriveUnavailable Then Return Await RemoveWatched(watchedFolder) Return End If + If watchedFolder.IsDriveUnavailable Then watchedFolder.InitializeMonitoring() + watchedFolder.IsDriveUnavailable = False Await Analyse(watchedFolder.Folder, False) LastAnalysed = DateTime.Now Await WriteToFileAsync() @@ -422,7 +462,7 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi Dim foldersToCompress = WatchedFolders. Where(Function(folder) - Dim eligible = folder.DecayPercentage <> 0 AndAlso folder.CompressionLevel <> WOFCompressionAlgorithm.NO_COMPRESSION + Dim eligible = Not folder.IsDriveUnavailable AndAlso folder.DecayPercentage <> 0 AndAlso folder.CompressionLevel <> WOFCompressionAlgorithm.NO_COMPRESSION Dim recentlyModified = folder.LastSystemModifiedDate > recentThresholdDate AndAlso Not runAll If eligible AndAlso recentlyModified Then WatcherLog.SkippingRecentlyModifiedFolder(_logger, folder.DisplayName) @@ -490,9 +530,13 @@ Partial Public Class Watcher : Inherits ObservableRecipient : Implements IRecipi Public Sub Receive(message As PropertyChangedMessage(Of Boolean)) Implements IRecipient(Of PropertyChangedMessage(Of Boolean)).Receive If (message.Sender.GetType() IsNot GetType(Settings)) Then Return - If message.PropertyName = NameOf(Settings.EnableBackgroundWatcher) Then : IsWatchingEnabled = message.NewValue - ElseIf message.PropertyName = NameOf(Settings.BackgroundModeSelection) Then : IsBackgroundCompactingEnabled = (CType(message.NewValue, BackgroundMode) = BackgroundMode.IdleOnly) - End If + If message.PropertyName = NameOf(Settings.EnableBackgroundWatcher) Then IsWatchingEnabled = message.NewValue + End Sub + + Public Sub Receive(message As PropertyChangedMessage(Of BackgroundMode)) Implements IRecipient(Of PropertyChangedMessage(Of BackgroundMode)).Receive + If message.Sender.GetType() IsNot GetType(Settings) Then Return + + If message.PropertyName = NameOf(Settings.BackgroundModeSelection) Then IsBackgroundCompactingEnabled = message.NewValue = BackgroundMode.IdleOnly End Sub diff --git a/CompactGUI.slnx b/CompactGUI.slnx index bc4e5586..af688d98 100644 --- a/CompactGUI.slnx +++ b/CompactGUI.slnx @@ -7,15 +7,12 @@ + - + - - - - - + diff --git a/CompactGUI/Application.xaml.vb b/CompactGUI/Application.xaml.vb index 4c17cc66..56727696 100644 --- a/CompactGUI/Application.xaml.vb +++ b/CompactGUI/Application.xaml.vb @@ -17,7 +17,7 @@ Imports Coravel.Scheduling.Schedule Partial Public Class Application - Public Shared ReadOnly AppVersion As New SemVersion(4, 0, 0, "beta", 7) + Public Shared ReadOnly AppVersion As New SemVersion(4, 0, 0, "beta", 12) Public Shared ReadOnly Property AppVersionText As String Get @@ -30,7 +30,15 @@ Partial Public Class Application Private Shared ReadOnly SettingsService As ISettingsService Shared Sub New() - SettingsService = New SettingsService() + + Dim currentDir = AppContext.BaseDirectory + If New IO.DirectoryInfo(currentDir).Name.ToLower = "compactgui" Then + SettingsService = New SettingsService(True) + Else + SettingsService = New SettingsService(False) + End If + + SettingsService.LoadSettings() AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf OnDomainUnhandledException @@ -50,6 +58,7 @@ Partial Public Class Application 'Settings handler services.AddSingleton(Of ISettingsService)(SettingsService) + services.AddSingleton(Of LocalisationService)() services.AddLogging(Sub(logging) logging.SetMinimumLevel(SettingsService.AppSettings.LogLevel) @@ -95,6 +104,9 @@ Partial Public Class Application services.AddTransient(Of DatabasePage)() services.AddTransient(Of DatabaseViewModel)() + services.AddSingleton(Of SteamMonitorPage)() + services.AddTransient(Of SteamMonitorViewModel)() + 'Other services services.AddSingleton(Of TrayNotifierService)(Function(sp) Return New TrayNotifierService(sp.GetRequiredService(Of MainWindow)(), Icon.ExtractAssociatedIcon(Environment.ProcessPath), "CompactGUI") @@ -123,7 +135,6 @@ Partial Public Class Application Return TryCast(_host?.Services.GetService(GetType(T)), T) End Function - Public Shared ReadOnly mutex As New Mutex(False, "Global\CompactGUI") Private pipeServerCancellation As New CancellationTokenSource() Private pipeServerTask As Task @@ -147,9 +158,10 @@ Partial Public Class Application End If InitializeHost() - LanguageHelper.Initialize(GetService(Of ISettingsService).AppSettings) + Await GetService(Of LocalisationService).InitializeAsync() GetService(Of Watcher.Watcher)() + GetService(Of HomeViewModel)() Await _host.StartAsync() Await GetService(Of SettingsViewModel).InitializeEnvironment() @@ -337,4 +349,4 @@ Partial Public Class Application ' End If 'End Function -End Class \ No newline at end of file +End Class diff --git a/CompactGUI/CompactGUI.vbproj b/CompactGUI/CompactGUI.vbproj index 80fb0401..8aabbee5 100644 --- a/CompactGUI/CompactGUI.vbproj +++ b/CompactGUI/CompactGUI.vbproj @@ -3,7 +3,7 @@ WinExe - net9.0-windows + net10.0-windows CompactGUI true Off @@ -27,6 +27,7 @@ 41999,42016,42017,42018,42019,42020,42021,42022,42032,42036 + true @@ -45,6 +46,7 @@ + @@ -54,7 +56,11 @@ + + + + @@ -79,29 +85,8 @@ - - i18n.es-ES.resx - True - True - - - True - True - i18n.resx - - - - - - i18n - i18n.es-ES.Designer.vb - PublicResXFileCodeGenerator - - - i18n - PublicResXFileCodeGenerator - i18n.Designer.vb - + + diff --git a/CompactGUI/Components/Converters/Converters.xaml b/CompactGUI/Components/Converters/Converters.xaml index 0e0f1f11..f0279652 100644 --- a/CompactGUI/Components/Converters/Converters.xaml +++ b/CompactGUI/Components/Converters/Converters.xaml @@ -11,6 +11,10 @@ + + + + @@ -19,6 +23,7 @@ + diff --git a/CompactGUI/Components/Converters/IValueConverters.vb b/CompactGUI/Components/Converters/IValueConverters.vb index 01acbafc..f6aed9d6 100644 --- a/CompactGUI/Components/Converters/IValueConverters.vb +++ b/CompactGUI/Components/Converters/IValueConverters.vb @@ -18,18 +18,18 @@ Public Class BytesToReadableConverter : Implements IValueConverter Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert Dim suf As String() = { - LanguageHelper.GetString("SizeUnit_B"), - LanguageHelper.GetString("SizeUnit_KB"), - LanguageHelper.GetString("SizeUnit_MB"), - LanguageHelper.GetString("SizeUnit_GB"), - LanguageHelper.GetString("SizeUnit_TB"), - LanguageHelper.GetString("SizeUnit_PB"), - LanguageHelper.GetString("SizeUnit_EB") + "B".LT("File size"), + "KB".LT("File size"), + "MB".LT("File size"), + "GB".LT("File size"), + "TB".LT("File size"), + "PB".LT("File size"), + "EB".LT("File size") } If value = 1010101010101010 Then Return "?" - If value = 0 Then Return "0" & suf(0) + If value = 0 Then Return "0 " & suf(0) Dim bytes As Long = Math.Abs(value) Dim place As Integer = CInt(Math.Floor(Math.Log(bytes, 1024))) @@ -57,7 +57,7 @@ Public Class BytesToReadableConverter : Implements IValueConverter Dim decimalPlaces As Integer = Math.Max(0, roundingSigDigits - digitsBeforeDecimal) Dim roundedNum As Double = Math.Round(num, decimalPlaces) - Return (Math.Sign(value) * roundedNum).ToString() & suf(place) + Return (Math.Sign(value) * roundedNum).ToString() & " " & suf(place) End Function @@ -86,6 +86,9 @@ Public Class TokenisedFolderPathConverter : Implements IValueConverter If value Is Nothing Then Return Nothing Dim Str = CType(value, String) Dim formattedString = Str.Replace("\"c, " 🢒 ") + If parameter?.ToString() = "TrimStart" AndAlso formattedString.Length > 72 Then + Return "…" & formattedString.Substring(formattedString.Length - 71) + End If Return formattedString End Function @@ -102,16 +105,16 @@ Public Class RelativeDateConverter : Implements IValueConverter Dim ts As TimeSpan = DateTime.Now - dt If ts > TimeSpan.FromDays(19000) Then - Return LanguageHelper.GetString("Time_Unknown") + Return "Unknown".LT("Relative date") End If If ts > TimeSpan.FromDays(2) Then - Return String.Format(LanguageHelper.GetString("Time_DaysAgo"), ts.TotalDays) + Return "{0:0} days ago".LTF(ts.TotalDays) ElseIf ts > TimeSpan.FromHours(2) Then - Return String.Format(LanguageHelper.GetString("Time_HoursAgo"), ts.TotalHours) + Return "{0:0} hours ago".LTF(ts.TotalHours) ElseIf ts > TimeSpan.FromMinutes(2) Then - Return String.Format(LanguageHelper.GetString("Time_MinutesAgo"), ts.TotalMinutes) + Return "{0:0} minutes ago".LTF(ts.TotalMinutes) Else - Return LanguageHelper.GetString("Time_Now") + Return "just now".LT() End If End Function @@ -140,6 +143,90 @@ Public Class CompressionLevelAbbreviatedConverter : Implements IValueConverter End Function End Class +Public Class CompressionModeAbbreviatedConverter : Implements IValueConverter + Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert + Dim mode = CType(value, Core.CompressionMode) + Select Case mode + Case Core.CompressionMode.XPRESS4K : Return "X4" + Case Core.CompressionMode.XPRESS8K : Return "X8" + Case Core.CompressionMode.XPRESS16K : Return "X16" + Case Core.CompressionMode.LZX : Return "LZX" + Case Else : Return "NIL" + End Select + End Function + + Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack + Throw New NotImplementedException() + End Function +End Class + +Public Class QueueCompressionModeLabelConverter : Implements IValueConverter + Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert + Select Case CType(value, Core.CompressionMode) + Case Core.CompressionMode.XPRESS4K : Return "X4K" + Case Core.CompressionMode.XPRESS8K : Return "X8K" + Case Core.CompressionMode.XPRESS16K : Return "X16K" + Case Core.CompressionMode.LZX : Return "LZX" + Case Else : Return "NIL" + End Select + End Function + + Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack + Throw New NotImplementedException() + End Function +End Class + +Public Class QueueStatusToStringConverter : Implements IValueConverter + Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert + Select Case CType(value, ActionState) + Case ActionState.Idle, ActionState.Waiting : Return "Waiting".LT() + Case ActionState.Analysing : Return "Preparing".LT() + Case ActionState.Working : Return "Working".LT() + Case ActionState.Paused : Return "Paused".LT() + Case ActionState.Results : Return "Complete".LT() + Case Else : Return "Failed".LT() + End Select + End Function + + Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack + Throw New NotImplementedException() + End Function +End Class + +Public Class SelectedModeEstimatedSavingsConverter : Implements IMultiValueConverter + Public Function Convert(values() As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert + Dim results = TryCast(values(0), WikiCompressionResults) + If results Is Nothing Then Return 0L + + Dim result As CompressionResult = Nothing + Select Case CType(values(1), Core.CompressionMode) + Case Core.CompressionMode.XPRESS4K + result = results.XPress4K + Case Core.CompressionMode.XPRESS8K + result = results.XPress8K + Case Core.CompressionMode.XPRESS16K + result = results.XPress16K + Case Core.CompressionMode.LZX + result = results.LZX + End Select + + Dim savings As Long + + If parameter Is Nothing Then + savings = If(result Is Nothing, 0L, Math.Max(0, result.BytesSaved)) + ElseIf CStr(parameter) = "AB" Then + savings = If(result Is Nothing, 0L, Math.Max(0, result.AfterBytes)) + + End If + + + Return New BytesToReadableConverter().Convert(savings, GetType(String), Nothing, culture) + End Function + + Public Function ConvertBack(value As Object, targetTypes() As Type, parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack + Throw New NotImplementedException() + End Function +End Class Public Class ConfidenceIntToStringConverter : Implements IValueConverter Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert @@ -260,6 +347,22 @@ Public Class BooleanToInverseVisibilityConverter : Implements IValueConverter End Class +Public Class WidthAtMostConverter : Implements IValueConverter + Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert + Dim width As Double + Dim threshold As Double + + If value Is Nothing OrElse Not Double.TryParse(value.ToString(), NumberStyles.Float, culture, width) Then Return False + If parameter Is Nothing OrElse Not Double.TryParse(parameter.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, threshold) Then Return False + + Return width <= threshold + End Function + + Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack + Throw New NotImplementedException() + End Function +End Class + Public Class EnumToRadioButtonConverter : Implements IValueConverter Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert Dim enumValue = CType(value, [Enum]) @@ -300,15 +403,15 @@ Public Class FolderStatusToStringConverter : Implements IValueConverter Dim status = CType(value, ActionState) Select Case status Case ActionState.Idle - Return LanguageHelper.GetString("Status_AwaitingCompression") + Return "Awaiting Compression".LT() Case ActionState.Analysing - Return LanguageHelper.GetString("Status_Analysing") + Return "Analysing".LT() Case ActionState.Working, ActionState.Paused - Return LanguageHelper.GetString("Status_Working") + Return "Working".LT() Case ActionState.Results - Return LanguageHelper.GetString("Status_Compressed") + Return "Compressed".LT() Case Else - Return LanguageHelper.GetString("Status_Unknown") + Return "Unknown".LT("Folder status") End Select End Function Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack @@ -493,4 +596,4 @@ Public Class EnumToIntConverter If targetType Is Nothing OrElse Not targetType.IsEnum OrElse value Is Nothing Then Return Binding.DoNothing Return [Enum].ToObject(targetType, value) End Function -End Class \ No newline at end of file +End Class diff --git a/CompactGUI/Components/Custom/TokenizedTextBox.vb b/CompactGUI/Components/Custom/TokenizedTextBox.vb deleted file mode 100644 index 68a26f00..00000000 --- a/CompactGUI/Components/Custom/TokenizedTextBox.vb +++ /dev/null @@ -1,84 +0,0 @@ -'Credit: https://blog.pixelingene.com/2010/10/tokenizing-control-convert-text-to-tokens - -Public Class TokenizedTextBox : Inherits RichTextBox - - Public Shared ReadOnly TokenTemplateProperty As DependencyProperty = DependencyProperty.Register("TokenTemplate", GetType(DataTemplate), GetType(TokenizedTextBox)) - Public Property TokenTemplate As DataTemplate - Get - Return GetValue(TokenTemplateProperty) - End Get - Set(value As DataTemplate) - SetValue(TokenTemplateProperty, value) - End Set - End Property - - Public Property TokenMatcher As Func(Of String, Object) - - Public Sub New() - - AddHandler TextChanged, AddressOf OnTokenTextChanged - - End Sub - - Private Sub OnTokenTextChanged(sender As Object, e As TextChangedEventArgs) - Dim text = CaretPosition.GetTextInRun(LogicalDirection.Backward) - If TokenMatcher Is Nothing Then Return - - Dim token = TokenMatcher(text) - If token IsNot Nothing Then - ReplaceTextWithToken(text, token) - End If - - End Sub - - Public Sub InsertText(text As String) - text &= " " - AppendText(text) - If TokenMatcher Is Nothing Then Return - Dim token = TokenMatcher(text) - If token IsNot Nothing Then - ReplaceTextWithToken(text, token) - End If - End Sub - - Private Sub ReplaceTextWithToken(inputText As String, token As Object) - - RemoveHandler TextChanged, AddressOf OnTokenTextChanged - - Dim para = CaretPosition.Paragraph - - Dim matchedRun As Run = para.Inlines.FirstOrDefault(Function(inline) - Dim run = TryCast(inline, Run) - Return (run IsNot Nothing AndAlso run.Text.EndsWith(inputText)) - End Function) - - If matchedRun IsNot Nothing Then - - Dim tokenContainer = CreateTokenContainer(inputText, token) - para.Inlines.InsertBefore(matchedRun, tokenContainer) - - If matchedRun.Text = inputText Then - para.Inlines.Remove(matchedRun) - Else - Dim index = matchedRun.Text.IndexOf(inputText) + inputText.Length - Dim tailEnd = New Run(matchedRun.Text.Substring(index)) - para.Inlines.InsertAfter(matchedRun, tailEnd) - para.Inlines.Remove(matchedRun) - End If - - End If - - AddHandler TextChanged, AddressOf OnTokenTextChanged - - End Sub - - Private Function CreateTokenContainer(inputText As String, token As Object) As InlineUIContainer - Dim presenter = New ContentPresenter() With { - .Content = token, - .ContentTemplate = TokenTemplate - } - - Return New InlineUIContainer(presenter) With {.BaselineAlignment = BaselineAlignment.Bottom} - - End Function -End Class diff --git a/CompactGUI/Components/LiveBlurBackground.vb b/CompactGUI/Components/LiveBlurBackground.vb new file mode 100644 index 00000000..03e0de47 --- /dev/null +++ b/CompactGUI/Components/LiveBlurBackground.vb @@ -0,0 +1,331 @@ +Imports System.Windows +Imports System.Windows.Controls +Imports System.Windows.Media +Imports System.Windows.Media.Effects +Imports System.Windows.Shapes + +Public NotInheritable Class LiveBlurBackground + + Public Shared ReadOnly EnableBlurProperty As DependencyProperty = DependencyProperty.RegisterAttached("EnableBlur", GetType(Boolean), GetType(LiveBlurBackground), New PropertyMetadata(False, AddressOf OnEnableBlurChanged)) + + Public Shared ReadOnly SourceProperty As DependencyProperty = DependencyProperty.RegisterAttached("Source", GetType(Visual), GetType(LiveBlurBackground), New PropertyMetadata(Nothing, AddressOf OnAppearanceChanged)) + + Public Shared ReadOnly BlurRadiusProperty As DependencyProperty = DependencyProperty.RegisterAttached("BlurRadius", GetType(Double), GetType(LiveBlurBackground), New PropertyMetadata(20.0, AddressOf OnAppearanceChanged)) + + Public Shared ReadOnly BlurOpacityProperty As DependencyProperty = DependencyProperty.RegisterAttached("BlurOpacity", GetType(Double), GetType(LiveBlurBackground), New PropertyMetadata(1.0, AddressOf OnAppearanceChanged)) + + Private Shared ReadOnly StateProperty As DependencyProperty = DependencyProperty.RegisterAttached("State", GetType(BlurState), GetType(LiveBlurBackground), New PropertyMetadata(Nothing)) + + Public Shared Function GetEnableBlur(element As DependencyObject) As Boolean + Return CBool(element.GetValue(EnableBlurProperty)) + End Function + + Public Shared Sub SetEnableBlur(element As DependencyObject, value As Boolean) + element.SetValue(EnableBlurProperty, value) + End Sub + + Public Shared Function GetSource(element As DependencyObject) As Visual + Return TryCast(element.GetValue(SourceProperty), Visual) + End Function + + Public Shared Sub SetSource(element As DependencyObject, value As Visual) + element.SetValue(SourceProperty, value) + End Sub + + Public Shared Function GetBlurRadius(element As DependencyObject) As Double + Return CDbl(element.GetValue(BlurRadiusProperty)) + End Function + + Public Shared Sub SetBlurRadius(element As DependencyObject, value As Double) + element.SetValue(BlurRadiusProperty, value) + End Sub + + Public Shared Function GetBlurOpacity(element As DependencyObject) As Double + Return CDbl(element.GetValue(BlurOpacityProperty)) + End Function + + Public Shared Sub SetBlurOpacity(element As DependencyObject, value As Double) + element.SetValue(BlurOpacityProperty, value) + End Sub + + Private Shared Sub OnEnableBlurChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs) + Dim border = TryCast(d, Border) + If border Is Nothing Then Return + + Dim state = TryCast(border.GetValue(StateProperty), BlurState) + + If CBool(e.NewValue) Then + If state Is Nothing Then + state = New BlurState(border) + border.SetValue(StateProperty, state) + End If + + state.Attach() + ElseIf state IsNot Nothing Then + state.Detach() + border.ClearValue(StateProperty) + End If + End Sub + + Private Shared Sub OnAppearanceChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs) + Dim border = TryCast(d, Border) + If border Is Nothing Then Return + + Dim state = TryCast(border.GetValue(StateProperty), BlurState) + state?.Update() + End Sub + + Private NotInheritable Class BlurState + + Private ReadOnly _border As Border + + Private _host As Grid + Private _contentHost As Grid + Private _blurRectangle As Rectangle + Private _brush As VisualBrush + Private _effect As BlurEffect + Private _originalChild As UIElement + + Private _attached As Boolean + Private _installed As Boolean + Private _trackingLayout As Boolean + + Public Sub New(border As Border) + _border = border + End Sub + + Public Sub Attach() + If _attached Then + Update() + Return + End If + + _attached = True + + AddHandler _border.Loaded, AddressOf OnLoaded + AddHandler _border.Unloaded, AddressOf OnUnloaded + + If _border.IsLoaded Then Install() + End Sub + + Public Sub Detach() + If Not _attached Then Return + + _attached = False + + RemoveHandler _border.Loaded, AddressOf OnLoaded + RemoveHandler _border.Unloaded, AddressOf OnUnloaded + + StopTrackingLayout() + + If Not _installed Then Return + + _brush.Visual = Nothing + _blurRectangle.Fill = Nothing + _blurRectangle.Effect = Nothing + + If ReferenceEquals(_border.Child, _host) Then + _border.Child = Nothing + + If _originalChild IsNot Nothing Then + _contentHost.Children.Remove(_originalChild) + _border.Child = _originalChild + End If + End If + + _host.Children.Clear() + + _host = Nothing + _contentHost = Nothing + _blurRectangle = Nothing + _brush = Nothing + _effect = Nothing + _originalChild = Nothing + + _installed = False + End Sub + + Public Sub Update() + If Not _installed Then Return + + UpdatePaddingLayout() + UpdateAppearance() + UpdateClip() + UpdateMapping() + End Sub + + Private Sub OnLoaded(sender As Object, e As RoutedEventArgs) + Install() + End Sub + + Private Sub OnUnloaded(sender As Object, e As RoutedEventArgs) + StopTrackingLayout() + End Sub + + Private Sub Install() + If _installed Then + StartTrackingLayout() + Update() + Return + End If + + _originalChild = _border.Child + _border.Child = Nothing + + _brush = New VisualBrush With { + .Stretch = Stretch.Fill, + .AlignmentX = AlignmentX.Left, + .AlignmentY = AlignmentY.Top, + .ViewboxUnits = BrushMappingMode.Absolute, + .ViewportUnits = BrushMappingMode.RelativeToBoundingBox, + .Viewport = New Rect(0, 0, 1, 1), + .TileMode = TileMode.None + } + + _effect = New BlurEffect With { + .KernelType = KernelType.Gaussian, + .RenderingBias = RenderingBias.Performance + } + + _blurRectangle = New Rectangle With { + .Fill = _brush, + .Effect = _effect, + .IsHitTestVisible = False + } + + _host = New Grid() + _contentHost = New Grid() + + _host.Children.Add(_blurRectangle) + _host.Children.Add(_contentHost) + + If _originalChild IsNot Nothing Then + _contentHost.Children.Add(_originalChild) + End If + + _border.Child = _host + _installed = True + + Update() + StartTrackingLayout() + End Sub + + Private Sub StartTrackingLayout() + If _trackingLayout Then Return + + AddHandler _border.LayoutUpdated, AddressOf OnLayoutUpdated + _trackingLayout = True + End Sub + + Private Sub StopTrackingLayout() + If Not _trackingLayout Then Return + + RemoveHandler _border.LayoutUpdated, AddressOf OnLayoutUpdated + _trackingLayout = False + End Sub + + Private Sub OnLayoutUpdated(sender As Object, e As EventArgs) + If Not _installed Then Return + + UpdatePaddingLayout() + UpdateClip() + UpdateMapping() + End Sub + + Private Sub UpdatePaddingLayout() + If _host Is Nothing OrElse _contentHost Is Nothing Then Return + + Dim padding = _border.Padding + Dim negativePadding = New Thickness(-padding.Left, -padding.Top, -padding.Right, -padding.Bottom) + + If _host.Margin <> negativePadding Then _host.Margin = negativePadding + If _contentHost.Margin <> padding Then _contentHost.Margin = padding + + End Sub + + Private Sub UpdateAppearance() + If _effect Is Nothing OrElse _brush Is Nothing Then Return + + Dim radius = Math.Max(0, GetBlurRadius(_border)) + Dim blurOpacity = Math.Clamp(GetBlurOpacity(_border), 0, 1) + + If Not AreClose(_effect.Radius, radius) Then _effect.Radius = radius + + If Not AreClose(_brush.Opacity, blurOpacity) Then _brush.Opacity = blurOpacity + + 'Provide buffer around the visible region so the blur does not produce transparent/ darkened edges. + Dim overscan = Math.Ceiling(radius * 1.5) + Dim margin = New Thickness(-overscan) + + If _blurRectangle.Margin <> margin Then _blurRectangle.Margin = margin + End Sub + + Private Sub UpdateClip() + If _host Is Nothing OrElse _host.ActualWidth <= 0 OrElse _host.ActualHeight <= 0 Then Return + + Dim radius = Math.Max(0, _border.CornerRadius.TopLeft) + Dim bounds = New Rect(0, 0, _host.ActualWidth, _host.ActualHeight) + Dim clip = TryCast(_host.Clip, RectangleGeometry) + + If clip Is Nothing Then + _host.Clip = New RectangleGeometry(bounds, radius, radius) + Else + If Not RectsEqual(clip.Rect, bounds) Then clip.Rect = bounds + If Not AreClose(clip.RadiusX, radius) Then clip.RadiusX = radius + If Not AreClose(clip.RadiusY, radius) Then clip.RadiusY = radius + End If + End Sub + + Private Sub UpdateMapping() + If _brush Is Nothing Then Return + + Dim source = GetSource(_border) + + If source Is Nothing OrElse + _host Is Nothing OrElse + _host.ActualWidth <= 0 OrElse + _host.ActualHeight <= 0 Then + + _brush.Visual = Nothing + Return + End If + + 'The source MUST NOT be an ancestor of the border or we get a circular dependency and fkn overflow + If source.IsAncestorOf(_border) Then + _brush.Visual = Nothing + Return + End If + + If Not ReferenceEquals(_brush.Visual, source) Then _brush.Visual = source + + Try + Dim overscan = Math.Ceiling(Math.Max(0, GetBlurRadius(_border)) * 1.5) + + Dim localCaptureBounds = New Rect(-overscan, -overscan, _host.ActualWidth + overscan * 2, _host.ActualHeight + overscan * 2) + + Dim transform = _host.TransformToVisual(source) + Dim sourceBounds = transform.TransformBounds(localCaptureBounds) + + If sourceBounds.Width <= 0 OrElse sourceBounds.Height <= 0 Then Return + + If Not RectsEqual(_brush.Viewbox, sourceBounds) Then _brush.Viewbox = sourceBounds + + Catch ex As InvalidOperationException + + End Try + End Sub + + Private Shared Function AreClose(a As Double, b As Double) As Boolean + Return Math.Abs(a - b) < 0.01 + End Function + + Private Shared Function RectsEqual(a As Rect, b As Rect) As Boolean + Return AreClose(a.X, b.X) AndAlso + AreClose(a.Y, b.Y) AndAlso + AreClose(a.Width, b.Width) AndAlso + AreClose(a.Height, b.Height) + End Function + + End Class + +End Class \ No newline at end of file diff --git a/CompactGUI/Components/Settings/Settings_skiplistflyout.xaml b/CompactGUI/Components/Settings/Settings_skiplistflyout.xaml index cca0717c..f5752895 100644 --- a/CompactGUI/Components/Settings/Settings_skiplistflyout.xaml +++ b/CompactGUI/Components/Settings/Settings_skiplistflyout.xaml @@ -3,16 +3,21 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:CompactGUI" + xmlns:loc="clr-namespace:LazyTranslate;assembly=LazyTranslate" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" - Width="620" Height="400" - d:DesignHeight="400" d:DesignWidth="500" - Background="{DynamicResource ApplicationBackgroundBrush}" + Width="620" + Height="400" + d:DesignHeight="400" + d:DesignWidth="500" ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}" + Background="{DynamicResource ApplicationBackgroundBrush}" ExtendsContentIntoTitleBar="True" Foreground="{DynamicResource TextFillColorPrimaryBrush}" - RenderOptions.BitmapScalingMode="HighQuality" RenderOptions.ClearTypeHint="Enabled" - WindowBackdropType="Mica" WindowStartupLocation="CenterScreen" + RenderOptions.BitmapScalingMode="HighQuality" + RenderOptions.ClearTypeHint="Enabled" + WindowBackdropType="Mica" + WindowStartupLocation="CenterScreen" mc:Ignorable="d"> @@ -25,17 +30,51 @@ - - - + Height="28" MinWidth="70" + Margin="5 8 5 0" Padding="10 0" + Background="#7AB3C6D8" BorderThickness="0" CornerRadius="5" Cursor="Hand"> + + + + + + + + + + + @@ -43,39 +82,95 @@ - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -88,17 +95,13 @@ - - + + - - + + - + @@ -110,9 +113,12 @@ - + diff --git a/CompactGUI/Views/Pages/HomePage.xaml.vb b/CompactGUI/Views/Pages/HomePage.xaml.vb index 32e38e6c..556994e6 100644 --- a/CompactGUI/Views/Pages/HomePage.xaml.vb +++ b/CompactGUI/Views/Pages/HomePage.xaml.vb @@ -16,9 +16,9 @@ End Sub - Private Async Sub AddFolderButton_Click(sender As Object, e As RoutedEventArgs) Handles BtnAddFolder1.Click, BtnAddFolder2.Click + Private Async Sub AddFolderButton_Click(sender As Object, e As RoutedEventArgs) Handles BtnAddFolder1.Click Dim folderBrowser As New Microsoft.Win32.OpenFolderDialog With { - .Title = "Select a folder to compress", + .Title = "Select a folder to compress".LT(), .Multiselect = True, .ValidateNames = True } diff --git a/CompactGUI/Views/Pages/PendingCompression.xaml b/CompactGUI/Views/Pages/PendingCompression.xaml index 6122a9d6..0a3d66e8 100644 --- a/CompactGUI/Views/Pages/PendingCompression.xaml +++ b/CompactGUI/Views/Pages/PendingCompression.xaml @@ -3,184 +3,357 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:core="clr-namespace:CompactGUI.Core;assembly=CompactGUI.Core" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" + xmlns:loc="clr-namespace:LazyTranslate;assembly=LazyTranslate" xmlns:local="clr-namespace:CompactGUI" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" - d:DataContext="{d:DesignInstance Type=local:FolderViewModel}" - d:DesignHeight="450" d:DesignWidth="900" d:Foreground="White" + d:DesignHeight="450" + d:DesignWidth="900" + d:Foreground="White" RenderOptions.ClearTypeHint="Enabled" mc:Ignorable="d"> + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + + + + + + - + - + - + + Savings="{Binding Folder.WikiCompressionResults.LZX.CompressionSavings}" /> - + - + - + - For Steam Games: estimate is based on database results - - - For Non-Steam Folders: estimate is calculated by block analysis. - If estimation is disabled, this will always show 0% + For Steam Games: + estimate is based on database results + + For Non-Steam Folders: + estimate is calculated by block analysis. + If estimation is disabled, this will always show 0% - + + + + + + + + + + + + + + + + + - - - - - - + + + + + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + - - - - - - + + + + + + + + + + + + + + + + + + - + - + + + + + + + + + - + + + diff --git a/CompactGUI/Views/Pages/PendingCompression.xaml.vb b/CompactGUI/Views/Pages/PendingCompression.xaml.vb index 7893f8bd..043b2a5b 100644 --- a/CompactGUI/Views/Pages/PendingCompression.xaml.vb +++ b/CompactGUI/Views/Pages/PendingCompression.xaml.vb @@ -19,37 +19,39 @@ Public Class PendingCompression End Sub - Private Sub UiChkSkipPoorlyCompressed_Checked(sender As Object, e As RoutedEventArgs) - _settingsService.AppSettings.SkipNonCompressable = True + Private Sub uiChkWatchFolderForChanges_Checked(sender As Object, e As RoutedEventArgs) + _settingsService.AppSettings.WatchFolderForChanges = True _settingsService.SaveSettings() - End Sub - Private Sub UiChkSkipPoorlyCompressed_Unchecked(sender As Object, e As RoutedEventArgs) - If Not IsVisible Then Return ' Prevents issues when the page is not fully loaded - _settingsService.AppSettings.SkipNonCompressable = False + Private Sub uiChkWatchFolderForChanges_Unchecked(sender As Object, e As RoutedEventArgs) + If Not IsVisible Then Return + _settingsService.AppSettings.WatchFolderForChanges = False _settingsService.SaveSettings() End Sub - Private Sub UiChkSkipUserPoorlyCompressed_Checked(sender As Object, e As RoutedEventArgs) - _settingsService.AppSettings.SkipUserNonCompressable = True - _settingsService.SaveSettings() + Private Sub UiEditSkipList_Click(sender As Object, e As RoutedEventArgs) + Dim folderViewModel = TryCast(DataContext, FolderViewModel) + If folderViewModel Is Nothing Then Return + + Dim flyout As New Settings_skiplistflyout(folderViewModel.Folder) + flyout.Owner = Window.GetWindow(Me) + flyout.ShowDialog() + + folderViewModel.Folder.NotifyPropertyChanged(NameOf(CompressableFolder.SkippedFileCount)) End Sub - Private Sub UiChkSkipUserPoorlyCompressed_Unchecked(sender As Object, e As RoutedEventArgs) - If Not IsVisible Then Return - _settingsService.AppSettings.SkipUserNonCompressable = False - _settingsService.SaveSettings() + Private Sub UiChkSkipListEnabled_Checked(sender As Object, e As RoutedEventArgs) + NotifySkippedFileCount() End Sub - Private Sub uiChkWatchFolderForChanges_Checked(sender As Object, e As RoutedEventArgs) - _settingsService.AppSettings.WatchFolderForChanges = True - _settingsService.SaveSettings() + Private Sub UiChkSkipListEnabled_Unchecked(sender As Object, e As RoutedEventArgs) + NotifySkippedFileCount() End Sub - Private Sub uiChkWatchFolderForChanges_Unchecked(sender As Object, e As RoutedEventArgs) - If Not IsVisible Then Return - _settingsService.AppSettings.WatchFolderForChanges = False - _settingsService.SaveSettings() + Private Sub NotifySkippedFileCount() + Dim folderViewModel = TryCast(DataContext, FolderViewModel) + If folderViewModel Is Nothing Then Return + folderViewModel.Folder.NotifyPropertyChanged(NameOf(CompressableFolder.SkippedFileCount)) End Sub End Class diff --git a/CompactGUI/Views/Pages/QueueSidebar.xaml b/CompactGUI/Views/Pages/QueueSidebar.xaml new file mode 100644 index 00000000..b941b30b --- /dev/null +++ b/CompactGUI/Views/Pages/QueueSidebar.xaml @@ -0,0 +1,431 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CompactGUI/Views/Pages/QueueSidebar.xaml.vb b/CompactGUI/Views/Pages/QueueSidebar.xaml.vb new file mode 100644 index 00000000..bdef36ba --- /dev/null +++ b/CompactGUI/Views/Pages/QueueSidebar.xaml.vb @@ -0,0 +1,45 @@ +Class QueueSidebar + + Public Shared ReadOnly ShowCloseButtonProperty As DependencyProperty = + DependencyProperty.Register(NameOf(ShowCloseButton), GetType(Boolean), GetType(QueueSidebar), New PropertyMetadata(True)) + + Public Property ShowCloseButton As Boolean + Get + Return CBool(GetValue(ShowCloseButtonProperty)) + End Get + Set(value As Boolean) + SetValue(ShowCloseButtonProperty, value) + End Set + End Property + + Public Sub New() + InitializeComponent() + DataContext = Application.GetService(Of HomeViewModel)() + End Sub + + Private Async Sub AddFolderButton_Click(sender As Object, e As RoutedEventArgs) + Dim folderBrowser As New Microsoft.Win32.OpenFolderDialog With { + .Title = "Select a folder to compress".LT(), + .Multiselect = True, + .ValidateNames = True + } + folderBrowser.ShowDialog() + + If folderBrowser.FolderNames.Length > 0 Then + Await CType(DataContext, HomeViewModel).AddFoldersAsync(folderBrowser.FolderNames) + End If + End Sub + + Private Sub QueueSelectionChanged(sender As Object, e As SelectionChangedEventArgs) + Dim selectedFolder = If(e.AddedItems.Count > 0, TryCast(e.AddedItems(0), CompressableFolder), Nothing) + If selectedFolder Is Nothing Then Return + + If ReferenceEquals(sender, UpNextListView) Then + CompletedListView.SelectedItem = Nothing + Else + UpNextListView.SelectedItem = Nothing + End If + + CType(DataContext, HomeViewModel).SelectedFolder = selectedFolder + End Sub +End Class diff --git a/CompactGUI/Views/Pages/ResultsTemplate.xaml b/CompactGUI/Views/Pages/ResultsTemplate.xaml index 29fc7cad..7e7c0793 100644 --- a/CompactGUI/Views/Pages/ResultsTemplate.xaml +++ b/CompactGUI/Views/Pages/ResultsTemplate.xaml @@ -2,6 +2,7 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" + xmlns:loc="clr-namespace:LazyTranslate;assembly=LazyTranslate" xmlns:local="clr-namespace:CompactGUI" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" @@ -17,124 +18,218 @@ - - + + + - - - - - - - - - + loc:L.Value="Compression Summary" FontSize="14" FontWeight="SemiBold" TextOptions.TextFormattingMode="Display" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + FontSize="16"> + + + + + + + + + + + + + + + + Command="{Binding SubmitToWikiCommand}"> @@ -151,3 +246,4 @@ + diff --git a/CompactGUI/Views/Pages/SteamMonitorPage.xaml b/CompactGUI/Views/Pages/SteamMonitorPage.xaml new file mode 100644 index 00000000..bdfb8b13 --- /dev/null +++ b/CompactGUI/Views/Pages/SteamMonitorPage.xaml @@ -0,0 +1,1467 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CompactGUI/Views/Pages/SteamMonitorPage.xaml.vb b/CompactGUI/Views/Pages/SteamMonitorPage.xaml.vb new file mode 100644 index 00000000..6c5e7c21 --- /dev/null +++ b/CompactGUI/Views/Pages/SteamMonitorPage.xaml.vb @@ -0,0 +1,114 @@ +Public Class SteamMonitorPage + + Private ReadOnly _viewModel As SteamMonitorViewModel + Private _isUpdatingSelection As Boolean + Private _isViewChangeHandlerAttached As Boolean + + Public Sub New(viewmodel As SteamMonitorViewModel) + InitializeComponent() + _viewModel = viewmodel + DataContext = viewmodel + End Sub + + Private Async Sub OnLoaded(sender As Object, e As RoutedEventArgs) + If Not _isViewChangeHandlerAttached Then + AddHandler DirectCast(_viewModel.FilteredSteamGames, System.Collections.Specialized.INotifyCollectionChanged).CollectionChanged, AddressOf OnVisibleGamesChanged + _isViewChangeHandlerAttached = True + End If + + Await _viewModel.LoadGamesAsync() + UpdateMasterCheckbox() + End Sub + + Private Sub OnUnloaded(sender As Object, e As RoutedEventArgs) + If Not _isViewChangeHandlerAttached Then Return + RemoveHandler DirectCast(_viewModel.FilteredSteamGames, System.Collections.Specialized.INotifyCollectionChanged).CollectionChanged, AddressOf OnVisibleGamesChanged + _isViewChangeHandlerAttached = False + End Sub + + Private Sub OnSteamGamesSelectionChanged(sender As Object, e As SelectionChangedEventArgs) + If _isUpdatingSelection Then Return + _viewModel.UpdateSelectedGames(DirectCast(sender, ListView).SelectedItems) + UpdateMasterCheckbox() + End Sub + + 'Today I learned about Func and this seems like a perfectly dumb place to use it + Private Sub OnSelectAllVisibleClick(sender As Object, e As RoutedEventArgs) + Dim visibleGames = SteamGamesList.Items.Cast(Of Object).ToList() + Dim allVisibleSelected = visibleGames.Count > 0 AndAlso visibleGames.All(Function(game) SteamGamesList.SelectedItems.Contains(game)) + + SetVisibleSelection(Function(game) Not allVisibleSelected) + End Sub + + Private Sub OnSelectAllClick(sender As Object, e As RoutedEventArgs) + SetVisibleSelection(Function(game) True) + End Sub + + Private Sub OnSelectAllCompressableClick(sender As Object, e As RoutedEventArgs) + SetVisibleSelection(Function(game) game.CanCompress) + End Sub + + Private Sub OnDeselectAllClick(sender As Object, e As RoutedEventArgs) + SetVisibleSelection(Function(game) False) + End Sub + + Private Sub SetVisibleSelection(shouldSelect As Func(Of SteamDetailedResult, Boolean)) + _isUpdatingSelection = True + For Each game As SteamDetailedResult In SteamGamesList.Items + If shouldSelect(game) Then + If Not SteamGamesList.SelectedItems.Contains(game) Then SteamGamesList.SelectedItems.Add(game) + Else + SteamGamesList.SelectedItems.Remove(game) + End If + Next + _isUpdatingSelection = False + + _viewModel.UpdateSelectedGames(SteamGamesList.SelectedItems) + UpdateMasterCheckbox() + End Sub + + Private Sub OnVisibleGamesChanged(sender As Object, e As System.Collections.Specialized.NotifyCollectionChangedEventArgs) + Dispatcher.BeginInvoke(New Action(AddressOf UpdateMasterCheckbox)) + End Sub + + Private Sub UpdateMasterCheckbox() + Dim visibleGames = SteamGamesList.Items.Cast(Of Object).ToList() + Dim selectedCount = visibleGames.Where(Function(game) SteamGamesList.SelectedItems.Contains(game)).Count() + + If selectedCount = 0 Then + SelectAllVisibleCheckBox.IsChecked = False + ElseIf selectedCount = visibleGames.Count Then + SelectAllVisibleCheckBox.IsChecked = True + Else + SelectAllVisibleCheckBox.IsChecked = Nothing + End If + End Sub + + Private Sub OnCompressSplitButtonLoaded(sender As Object, e As RoutedEventArgs) + Dim splitButton = DirectCast(sender, Wpf.Ui.Controls.SplitButton) + splitButton.ApplyTemplate() + + Dim toggleButton = TryCast(splitButton.Template.FindName("PART_ToggleButton", splitButton), Primitives.ToggleButton) + Dim toggleBorder = If(toggleButton Is Nothing, Nothing, TryCast(Media.VisualTreeHelper.GetParent(toggleButton), Border)) + Dim layoutGrid = If(toggleBorder Is Nothing, Nothing, TryCast(Media.VisualTreeHelper.GetParent(toggleBorder), Grid)) + + If layoutGrid Is Nothing OrElse layoutGrid.ColumnDefinitions.Count <> 2 Then Return + layoutGrid.ColumnDefinitions(0).Width = New GridLength(1, GridUnitType.Star) + End Sub + + Private Sub OnDetailCardSizeChanged(sender As Object, e As SizeChangedEventArgs) + Dim card = DirectCast(sender, Border) + Dim clip = TryCast(card.Clip, Media.RectangleGeometry) + + If clip Is Nothing Then + clip = New Media.RectangleGeometry With { + .RadiusX = card.CornerRadius.TopLeft, + .RadiusY = card.CornerRadius.TopLeft + } + card.Clip = clip + End If + + clip.Rect = New Rect(0, 0, card.ActualWidth, card.ActualHeight) + End Sub + +End Class diff --git a/CompactGUI/Views/Pages/WatcherPage.xaml b/CompactGUI/Views/Pages/WatcherPage.xaml index 936422bf..663d0ef1 100644 --- a/CompactGUI/Views/Pages/WatcherPage.xaml +++ b/CompactGUI/Views/Pages/WatcherPage.xaml @@ -4,12 +4,13 @@ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:CompactGUI" + xmlns:loc="clr-namespace:LazyTranslate;assembly=LazyTranslate" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800" - Title="{local:Localize PageNameWatcher}" - d:Title="WatcherPage"> + Title="{loc:T 'WatcherPage'}"> + diff --git a/CompactGUI/Views/SettingsPage.xaml b/CompactGUI/Views/SettingsPage.xaml index 9a466397..e859e60c 100644 --- a/CompactGUI/Views/SettingsPage.xaml +++ b/CompactGUI/Views/SettingsPage.xaml @@ -4,6 +4,7 @@ xmlns:Flags="clr-namespace:FamFamFam.Flags.Wpf;assembly=FamFamFam.Flags.Wpf" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:i="http://schemas.microsoft.com/xaml/behaviors" + xmlns:loc="clr-namespace:LazyTranslate;assembly=LazyTranslate" xmlns:local="clr-namespace:CompactGUI" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" @@ -20,11 +21,9 @@ - + - + @@ -36,6 +35,7 @@ + @@ -53,7 +53,7 @@ + Text="{Binding NativeName}" /> @@ -62,8 +62,20 @@ + + + + + + + + - -