35 Commits
Author SHA1 Message Date
poli0981 7e7ab59204 feat: add memory management features and UI updates for hash file handling 2026-02-18 11:38:08 +07:00
poli0981 7803b5ba47 feat: implement memory cleanup on window deactivation and minimization to optimize resource usage 2026-02-18 11:38:07 +07:00
poli0981 0bf7e50c45 Delete tests/CheckHash.Tests directory 2026-02-18 11:38:07 +07:00
poli0981 6695d1b1df feat: add garbage collection calls after message box displays to optimize memory management 2026-02-18 11:38:07 +07:00
poli0981 435da58f0e feat: update localization for UI elements in AboutView and FileStatusConverter 2026-02-18 11:38:06 +07:00
poli0981 80d6920ada feat: refactor hash computation methods for improved clarity and performance 2026-02-18 11:38:06 +07:00
poli0981 cba664e141 feat: enhance batch processing logs to include estimated time and task duration 2026-02-18 11:38:06 +07:00
poli0981 9915759ad0 feat: implement cancellation handling in hash processing with status updates 2026-02-18 11:38:05 +07:00
poli0981 ae33bf7d45 feat: add AlgorithmEnabledConverter for dynamic ComboBox enabling based on processing state 2026-02-18 11:38:05 +07:00
poli0981 efba0d1903 feat: refactor processing logic to use batching for improved performance and clarity 2026-02-18 11:38:05 +07:00
poli0981 61b17c4b97 feat: enhance MessageBoxHelper to support icons for different message types 2026-02-18 11:38:04 +07:00
poli0981 853ce93a77 feat: add documents section to About view with links to relevant resources 2026-02-18 11:38:04 +07:00
poli0981 db2efdc82c feat: increase width of search TextBox and adjust Grid column definitions for improved layout in MainWindow 2026-02-18 11:38:04 +07:00
poli0981 aec3882cef feat: update UI elements for improved layout and usability in About, Main, and Settings views 2026-02-18 11:38:04 +07:00
poli0981 ffc2172dc4 feat: rename ResetAppearance to ResetSettings and update related functionality for comprehensive settings reset 2026-02-18 11:38:03 +07:00
poli0981 d2b79dd168 feat: refactor config file handling to ensure existence and improve error logging 2026-02-18 11:38:03 +07:00
poli0981 6625faa718 feat: add HighlightTextBlock control for enhanced text highlighting in UI 2026-02-18 11:38:03 +07:00
poli0981 fc406faeee feat: add conditional logic for clearing individual and all hashes 2026-02-18 11:38:03 +07:00
poli0981 1ae987eca9 feat: enhance processing options to include algorithm selection for file sizes 2026-02-18 11:38:02 +07:00
poli0981 adc8451995 feat: add clear hash and clear all hashes functionality with UI updates 2026-02-18 11:38:02 +07:00
poli0981 b68995fcd5 feat: add file size filtering options and update UI 2026-02-18 11:38:01 +07:00
poli0981 ae0a177451 fix: fix cancelled logic 2026-02-18 11:38:01 +07:00
poli0981 c33d651782 add search feature 2026-02-18 11:38:00 +07:00
poli0981 982eb5bdfd Add read/write speed monitoring and update UI to display progress statistics 2026-02-18 11:38:00 +07:00
poli0981 d7aa41b013 Add processing limits for file and folder counts in settings 2026-02-18 11:38:00 +07:00
poli0981 957472dca8 Refactor CheckHash and CreateHash view models to inherit from FileListViewModelBase for shared functionality 2026-02-18 11:37:59 +07:00
poli0981 553953cb9e Add folder selection for file input and enhance progress tracking with estimated time 2026-02-18 11:37:59 +07:00
poli0981 b657309f26 Add support for additional hash algorithms and update hash regex pattern 2026-02-18 11:37:59 +07:00
poli0981 8381617c8f Add network connectivity checks and error handling messages 2026-02-18 11:37:58 +07:00
poli0981 b1cf6cb5ed Add new theme styles and refactor theme application logic 2026-02-18 11:37:58 +07:00
poli0981 5594b55765 Add language change confirmation dialog and related settings 2026-02-18 11:37:58 +07:00
poli0981 1eae5ce415 Add AppConstants for file size constants and refactor related code 2026-02-18 11:37:45 +07:00
poli0981 385a50894a Refactor configuration loading to check for file existence before reading 2026-02-08 01:56:54 +07:00
poli0981 a9740a582d Enhance application metadata and improve configuration handling 2026-02-08 01:32:42 +07:00
poli0981 99e16b56b7 Update acknowledgements and AboutViewModel with additional library information 2026-02-07 20:26:11 +07:00
62 changed files with 5944 additions and 2246 deletions

No files matched your search

+1 -2
View File
@@ -1,2 +1 @@
* auto eol = lf
* text=auto eol=lf
+6 -1
View File
@@ -5,7 +5,7 @@ HashTool would not have been possible without the generous contributions of open
All AI-generated content (code suggestions, translations, text) was carefully reviewed, tested, and verified by the author.
### AI Assistance
- **Gemini 3 Pro** (including Jules Agent) (by Google): Provided code suggestions, debugging help, error detection,
- **Gemini 3 Pro** (including Jules Agent) (by Google): Provided code suggestions, debugging help, error detection,
and fixes.
- **Grok 4.1** (by xAI): Code suggestions, multi-language translations (30+ languages), and assistance in writing documentation/texts (e.g., Disclaimer, Privacy Policy).
@@ -15,6 +15,11 @@ Big thanks to these AIs for speeding up development.
HashTool uses the following open-source libraries:
- [Avalonia UI](https://github.com/AvaloniaUI/Avalonia) version 11.3.11 – Licensed under the MIT License.
- [Avalonia.Controls.ColorPicker](https://github.com/AvaloniaUI/Avalonia) version 11.3.11 – Licensed under the MIT License.
- [Avalonia.Controls.DataGrid](https://github.com/AvaloniaUI/Avalonia) version 11.3.11 – Licensed under the MIT License.
- [Avalonia.Desktop](https://github.com/AvaloniaUI/Avalonia) version 11.3.11 – Licensed under the MIT License.
- [Avalonia.Fonts.Inter](https://github.com/AvaloniaUI/Avalonia) version 11.3.11 – Licensed under the MIT License / SIL OFL 1.1.
- [Avalonia.Themes.Fluent](https://github.com/AvaloniaUI/Avalonia) version 11.3.11 – Licensed under the MIT License.
- [Blake3.NET](https://github.com/xoofx/Blake3.NET) version 2.2.0 – Copyright © Alexandre Mutel. Licensed under the BSD 2-Clause License.
- [CommunityToolkit.Mvvm](https://github.com/CommunityToolkit/dotnet) version 8.2.1 – Licensed under the MIT License.
- [Material.Icons.Avalonia](https://github.com/AvaloniaUtils/Material.Icons.Avalonia) version 2.4.1 – Licensed under the MIT License.
+10
View File
@@ -2,6 +2,7 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="CheckHash.App"
xmlns:local="using:CheckHash"
xmlns:conv="using:CheckHash.Converters"
xmlns:avalonia="clr-namespace:Material.Icons.Avalonia;assembly=Material.Icons.Avalonia"
Name="Hash Tool"
RequestedThemeVariant="Dark">
@@ -34,18 +35,27 @@
<Application.Resources>
<ResourceDictionary>
<conv:HashMaskConverter x:Key="HashMaskConverter" />
<conv:CountToVisibilityConverter x:Key="CountToVisibilityConverter" />
<conv:ComputeButtonEnabledConverter x:Key="ComputeButtonEnabledConverter" />
<conv:AlgorithmEnabledConverter x:Key="AlgorithmEnabledConverter" />
<conv:FileStatusConverter x:Key="FileStatusConverter" />
<conv:FileSizeFilterConverter x:Key="FileSizeFilterConverter" />
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Light">
<Color x:Key="AppBackgroundColor">#F8F9FA</Color>
<Color x:Key="PaneBackgroundColor">#FFFFFF</Color>
<SolidColorBrush x:Key="AppBackgroundBrush" Color="{StaticResource AppBackgroundColor}" />
<SolidColorBrush x:Key="PaneBackgroundBrush" Color="{StaticResource PaneBackgroundColor}" />
<SolidColorBrush x:Key="HighlightBrush" Color="#0066CC" />
</ResourceDictionary>
<ResourceDictionary x:Key="Dark">
<Color x:Key="AppBackgroundColor"> #121212</Color>
<Color x:Key="PaneBackgroundColor">#212529</Color>
<SolidColorBrush x:Key="AppBackgroundBrush" Color="{StaticResource AppBackgroundColor}" />
<SolidColorBrush x:Key="PaneBackgroundBrush" Color="{StaticResource PaneBackgroundColor}" />
<SolidColorBrush x:Key="HighlightBrush" Color="#FFD700" />
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>
-2
View File
@@ -34,8 +34,6 @@ public class App : Application
args.SetObserved();
};
_ = ConfigurationService.Instance.EnsureConfigFileExistsAsync();
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
DisableAvaloniaDataAnnotationValidation();
+11 -5
View File
@@ -6,7 +6,12 @@
<ApplicationManifest>app.manifest</ApplicationManifest>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
<Authors>poli0981</Authors>
<Version>1.1.0</Version>
<InformationalVersion>1.1.0</InformationalVersion>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<AssemblyTitle>Hash Tool</AssemblyTitle>
<Company>poli0981</Company>
<Product>Hash Tool</Product>
<Description>A powerful tool for generating, verifying, and compressing file hashes. Or so I think :)</Description>
@@ -40,6 +45,7 @@
<PackageReference Include="Blake3" Version="2.2.0"/>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.1"/>
<PackageReference Include="Material.Icons.Avalonia" Version="2.4.1"/>
<PackageReference Include="System.IO.Hashing" Version="11.0.0-preview.1.26104.118" />
<PackageReference Include="Velopack" Version="0.0.1298"/>
</ItemGroup>
@@ -56,6 +62,10 @@
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Lang\Languages.json" />
</ItemGroup>
<!-- Icon on macOS -->
<PropertyGroup Condition="'$(RuntimeIdentifier)' == 'osx-x64' or '$(RuntimeIdentifier)' == 'osx-arm64'">
@@ -72,8 +82,4 @@
<PublishState>Included</PublishState>
</Content>
</ItemGroup>
<ItemGroup>
<Folder Include=".github\" />
</ItemGroup>
</Project>
+31
View File
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Avalonia.Data.Converters;
using CheckHash.Models;
namespace CheckHash.Converters;
public class AlgorithmEnabledConverter : IMultiValueConverter
{
public object? Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture)
{
if (values == null || values.Count != 2)
return false;
if (values[0] is not FileStatus status ||
values[1] is not bool isComputing)
{
return false;
}
if (!isComputing)
{
return true;
}
// If computing, disable for Ready (Queue) or Processing (Active)
// Enable for Success, Failure, Cancelled (Complete)
return status != FileStatus.Ready && status != FileStatus.Processing;
}
}
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Avalonia.Data.Converters;
namespace CheckHash.Converters;
public class ComputeButtonEnabledConverter : IMultiValueConverter
{
public object? Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture)
{
if (values == null || values.Count != 3)
return false;
if (values[0] is not bool isCancelled ||
values[1] is not bool isProcessing ||
values[2] is not bool isGlobalBusy)
{
return false;
}
return isProcessing || !isGlobalBusy;
}
}
+34
View File
@@ -0,0 +1,34 @@
using System;
using System.Globalization;
using Avalonia.Data.Converters;
using CheckHash.Models;
using CheckHash.Services;
namespace CheckHash.Converters;
public class FileSizeFilterConverter : IValueConverter
{
private LocalizationService L => LocalizationService.Instance;
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is FileSizeFilter filter)
{
return filter switch
{
FileSizeFilter.All => L["Size_All"],
FileSizeFilter.Small => L["Size_Small"],
FileSizeFilter.Medium => L["Size_Medium"],
FileSizeFilter.Large => L["Size_Large"],
FileSizeFilter.ExtraLarge => L["Size_ExtraLarge"],
_ => filter.ToString()
};
}
return value;
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
+40
View File
@@ -0,0 +1,40 @@
using System;
using System.Globalization;
using Avalonia.Data.Converters;
using CheckHash.Models;
using CheckHash.Services;
namespace CheckHash.Converters;
public class FileStatusConverter : IValueConverter
{
private static LocalizationService L => LocalizationService.Instance;
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is FileStatus status)
{
return status switch
{
FileStatus.Ready => L["Lbl_Status_Ready"],
FileStatus.Processing => L["Status_Processing_Filter"],
FileStatus.Success => L["Status_Done"],
FileStatus.Failure => L["Status_Failure"],
FileStatus.Cancelled => L["Status_Cancelled"],
_ => status.ToString()
};
}
if (value == null)
{
return L["Filter_All"];
}
return value?.ToString();
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
+17 -15
View File
@@ -9,36 +9,38 @@ public class HashMaskConverter : IMultiValueConverter
{
public object? Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture)
{
// values[0]: Hash string to be masked
// values[1]: IsHashMaskingEnabled (Global Setting)
// values[2]: IsRevealed (Local Item State)
if (values.Count < 3) return "";
if (values == null || values.Count < 3) return "";
var hash = values[0] as string ?? "";
var isMaskingEnabled = values[1] as bool? ?? false;
var isRevealed = values[2] as bool? ?? false;
// If parameter is "MaskOnly" -> Hide hash
// Logic use for CheckHashView when user choose "Show Only Masked" option
if (parameter as string == "MaskOnly")
{
if (string.IsNullOrEmpty(hash)) return "";
if (hash.Length <= 8) return new string('*', hash.Length);
return $"{hash[..4]}{new string('*', hash.Length - 8)}{hash[^4..]}";
return MaskHash(hash);
}
if (string.IsNullOrEmpty(hash)) return "";
// If masking is disabled -> Show full hash
if (!isMaskingEnabled) return hash;
// If revealed -> Show full hash
if (isRevealed) return hash;
// Otherwise, show masked hash of format: "abcd****wxyz"
if (hash.Length <= 8) return new string('*', hash.Length);
return MaskHash(hash);
}
return $"{hash[..4]}{new string('*', hash.Length - 8)}{hash[^4..]}";
private static string MaskHash(string hash)
{
if (string.IsNullOrEmpty(hash)) return "";
int length = hash.Length;
if (length <= 8) return new string('*', length);
return string.Create(length, hash, (span, h) =>
{
h.AsSpan(0, 4).CopyTo(span);
span[4..^4].Fill('*');
h.AsSpan(h.Length - 4).CopyTo(span[^4..]);
});
}
}
+270
View File
@@ -0,0 +1,270 @@
[
{
"Name" : "Auto (System)" ,
"Code" : "auto"
} ,
{
"Name" : "English (US)" ,
"Code" : "en-US"
} ,
{
"Name" : "العربية (Arabic)" ,
"Code" : "ar"
} ,
{
"Name" : "Tiếng Việt" ,
"Code" : "vi-VN"
} ,
{
"Name" : "Bahasa Indonesia" ,
"Code" : "id-ID"
} ,
{
"Name" : "ภาษาไทย (Thai)" ,
"Code" : "th-TH"
} ,
{
"Name" : "Filipino (Tagalog)" ,
"Code" : "fil-PH"
} ,
{
"Name" : "Bahasa Melayu (Malaysia)" ,
"Code" : "ms-MY"
} ,
{
"Name" : "English (Singapore)" ,
"Code" : "en-sg"
} ,
{
"Name" : "简体中文 (Singapore)" ,
"Code" : "zh-hans-sg"
} ,
{
"Name" : "မြန်မာ (Burmese)" ,
"Code" : "my-MM"
} ,
{
"Name" : "ខ្មែរ (Khmer)" ,
"Code" : "km-KH"
} ,
{
"Name" : "ລາວ (Laos)" ,
"Code" : "lo-LA"
} ,
{
"Name" : "فارسی (Persian)" ,
"Code" : "fa-IR"
} ,
{
"Name" : "עברית (Hebrew)" ,
"Code" : "he-IL"
} ,
{
"Name" : "Türkçe (Turkish)" ,
"Code" : "tr-TR"
} ,
{
"Name" : "Ελληνικά" ,
"Code" : "el-CY"
} ,
{
"Name" : "हिन्दी (Hindi)" ,
"Code" : "hi-IN"
} ,
{
"Name" : "English (India)" ,
"Code" : "en-IN"
} ,
{
"Name" : "বাংলা (Bengali)" ,
"Code" : "bn-BD"
} ,
{
"Name" : "සිංහල (Sinhala)" ,
"Code" : "si-LK"
} ,
{
"Name" : "རྫོང་ཁ (Dzongkha)" ,
"Code" : "dz-BT"
} ,
{
"Name" : "नेपाली (Nepali)" ,
"Code" : "ne-NP"
} ,
{
"Name" : "ދިވެހި (Divehi)" ,
"Code" : "dv-MV"
} ,
{
"Name" : "پښتو (Pashto)" ,
"Code" : "ps-AF"
} ,
{
"Name" : "繁體中文 (Chinese Traditional)" ,
"Code" : "zh-hant"
} ,
{
"Name" : "简体中文 (Chinese Simplified)" ,
"Code" : "zh-hans-cn"
} ,
{
"Name" : "日本語 (Japanese)" ,
"Code" : "ja-jp"
} ,
{
"Name" : "한국어 (Korean)" ,
"Code" : "ko-KR"
} ,
{
"Name" : "Монгол (Mongolian)" ,
"Code" : "mn-MN"
} ,
{
"Name" : "Қазақша (Kazakh)" ,
"Code" : "kk-KZ"
} ,
{
"Name" : "Кыргызча (Kyrgyz)" ,
"Code" : "ky-KG"
} ,
{
"Name" : "Тоҷикӣ (Tajik)" ,
"Code" : "tg-TJ"
} ,
{
"Name" : "Türkmençe (Turkmen)" ,
"Code" : "tk-TM"
} ,
{
"Name" : "Español (Spanish)" ,
"Code" : "es-ES"
} ,
{
"Name" : "Español (Latam)" ,
"Code" : "es-419"
} ,
{
"Name" : "Français (French)" ,
"Code" : "fr-FR"
} ,
{
"Name" : "Deutsch (German)" ,
"Code" : "de-DE"
} ,
{
"Name" : "Svenska (Swedish)" ,
"Code" : "sv-SE"
} ,
{
"Name" : "Bosanski (Bosnian Latin)" ,
"Code" : "bs-latn-ba"
} ,
{
"Name" : "Polski (Polish)" ,
"Code" : "pl-PL"
} ,
{
"Name" : "Русский (Russian)" ,
"Code" : "ru-RU"
} ,
{
"Name" : "Deutsch (Austria)" ,
"Code" : "de-AT"
} ,
{
"Name" : "Deutsch (Switzerland)" ,
"Code" : "de-CH"
} ,
{
"Name" : "Shqip (Albanian)" ,
"Code" : "sq-AL"
} ,
{
"Name" : "Македонски (Macedonian)" ,
"Code" : "mk-MK"
} ,
{
"Name" : "Română (Romanian)" ,
"Code" : "ro-RO"
} ,
{
"Name" : "Slovenčina (Slovak)" ,
"Code" : "sk-SK"
} ,
{
"Name" : "Українська (Ukrainian)" ,
"Code" : "uk-UA"
} ,
{
"Name" : "Hrvatski (Croatian)" ,
"Code" : "hr-HR"
} ,
{
"Name" : "Čeština (Czech)" ,
"Code" : "cs-CZ"
} ,
{
"Name" : "Italiano (Italian)" ,
"Code" : "it-IT"
} ,
{
"Name" : "Српски (Serbian Cyrillic)" ,
"Code" : "sr-cyrl-rs"
} ,
{
"Name" : "Български (Bulgarian)" ,
"Code" : "bg-BG"
} ,
{
"Name" : "Dansk (Danish)" ,
"Code" : "da-DK"
} ,
{
"Name" : "Ελληνικά (Greek)" ,
"Code" : "el-GR"
} ,
{
"Name" : "Suomeksi (Finnish)" ,
"Code" : "fi-FI"
} ,
{
"Name" : "Magyar (Hungarian)" ,
"Code" : "hu-HU"
} ,
{
"Name" : "Norsk (Norwegian)" ,
"Code" : "nb-NO"
} ,
{
"Name" : "Nederlands (Dutch)" ,
"Code" : "nl-NL"
} ,
{
"Name" : "Nederlands (Belgium)" ,
"Code" : "nl-BE"
} ,
{
"Name" : "Íslenska (Icelandic)" ,
"Code" : "is-IS"
} ,
{
"Name" : "Slovenščina (Slovenian)" ,
"Code" : "sl-SI"
} ,
{
"Name" : "Eesti (Estonian)" ,
"Code" : "et-EE"
} ,
{
"Name" : "Latviešu (Latvian)" ,
"Code" : "lv-LV"
} ,
{
"Name" : "Lietuvių (Lithuanian)" ,
"Code" : "lt-LT"
} ,
{
"Name" : "Português (Brasil)" ,
"Code" : "pt-BR"
}
]
+1940 -860
View File
File diff suppressed because it is too large. Load diff
+181 -1
View File
@@ -54,6 +54,9 @@
<data name="Btn_Clear">
<value>Clear List</value>
</data>
<data name="Btn_ClearHashes">
<value>Clear Hashes</value>
</data>
<data name="Btn_CalcAll">
<value>COMPUTE ALL</value>
</data>
@@ -148,7 +151,7 @@
<value>Mask Hash Values (Security)</value>
</data>
<data name="Settings_Reset">
<value>Reset Theme</value>
<value>Reset Settings</value>
</data>
<data name="Settings_Other">
<value>Privacy &amp; Security</value>
@@ -370,6 +373,7 @@
<value>Processing completed!
✅ Success: {0}
❌ Failed: {1}
⛔ Cancelled: {2}
</value>
</data>
<data name="Msg_CheckResult">
@@ -494,6 +498,9 @@
<data name="Tip_Compute">
<value>Compute</value>
</data>
<data name="Tip_ClearHash">
<value>Clear Hash</value>
</data>
<data name="Tip_BrowseHash">
<value>Browse Hash</value>
</data>
@@ -562,4 +569,177 @@
{3}
</value>
</data>
<data name="Msg_SystemLanguage">
<value>System Language</value>
</data>
<data name="Msg_SystemLanguageWarning">
<value>Returning to 'Auto' setting requires a restart to fully take effect. Do you want to continue?</value>
</data>
<data name="Msg_LanguageChangeTitle">
<value>Language Change</value>
</data>
<data name="Msg_LanguageChangeConfirmation">
<value>Are you sure about that?</value>
</data>
<data name="Msg_DontShowAgain">
<value>Don't show this alert again</value>
</data>
<data name="Error_Network">
<value>Network connection error. Please check your internet connection.</value>
</data>
<data name="Error_Server">
<value>Server error (5xx). Please try again later.</value>
</data>
<data name="Error_Client">
<value>Client error (4xx). Please check the request.</value>
</data>
<data name="Error_ApiLimit">
<value>GitHub API rate limit exceeded. Please try again later.</value>
</data>
<data name="Msg_NoPreRelease">
<value>No pre-release version found. Keeping current version.</value>
</data>
<data name="Msg_PreReleaseWarning">
<value>Pre-release version {0} is available.
{1}
This version may be unstable. Do you want to download?
</value>
</data>
<data name="Btn_ClearFailed">
<value>Clear Failed</value>
</data>
<data name="Msg_ClearedFailed">
<value>Removed {0} items.</value>
</data>
<data name="Msg_EstimatedTime">
<value>Time Remaining: {0}</value>
</data>
<data name="Msg_TaskDuration">
<value>Task Duration: {0}</value>
</data>
<data name="Msg_TimeUnknown">
<value>Calculating...</value>
</data>
<data name="Btn_AddFolder">
<value>Add Folder...</value>
</data>
<data name="Msg_EmptyFolder">
<value>The selected folder is empty.</value>
</data>
<data name="Dialog_SelectFolder">
<value>Select Folder to Scan</value>
</data>
<data name="Btn_Cancel">
<value>Cancel</value>
</data>
<data name="Settings_Limits">
<value>Processing Limits</value>
</data>
<data name="Settings_MaxFileCount">
<value>Max Files per Folder Scan</value>
</data>
<data name="Settings_MaxFileCountDesc">
<value>Limit the number of files added from a folder to prevent performance issues.</value>
</data>
<data name="Settings_MaxFolderCount">
<value>Max Folders per Click</value>
</data>
<data name="Settings_MaxFolderCountDesc">
<value>Limit the number of folders selected at once.</value>
</data>
<data name="Msg_FolderLimit">
<value>You can only select up to {0} folders at a time.</value>
</data>
<data name="Msg_FileLimit">
<value>Added {0} files. Skipped {1} files due to limit.</value>
</data>
<data name="Lbl_ProgressStats">
<value>{0}/{1} ({2:F2}%)</value>
</data>
<data name="Lbl_DetailedStats">
<value>✅ {0} ({1:F2}%) | ❌ {2} ({3:F2}%) | ⛔ {4} ({5:F2}%)</value>
</data>
<data name="Lbl_Speed">
<value>Read: {0}/s | Write: {1}/s</value>
</data>
<data name="Settings_ShowSpeed">
<value>Show Read/Write Speed</value>
</data>
<data name="Settings_ShowSpeedDesc">
<value>Display real-time transfer speed during hash operations.</value>
</data>
<data name="Status_Computing">
<value>Hash Computing...</value>
</data>
<data name="Size_All">
<value>All Sizes</value>
</data>
<data name="Size_Small">
<value>Small (&lt; 1MB)</value>
</data>
<data name="Size_Medium">
<value>Medium (1MB - 100MB)</value>
</data>
<data name="Size_Large">
<value>Large (100MB - 1GB)</value>
</data>
<data name="Size_ExtraLarge">
<value>Extra Large (&gt; 1GB)</value>
</data>
<data name="About_Documents">
<value>Documents</value>
</data>
<data name="Doc_PrivacyPolicy">
<value>Privacy Policy</value>
</data>
<data name="Doc_ToS">
<value>Terms of Service</value>
</data>
<data name="Doc_EULA">
<value>End User License Agreement</value>
</data>
<data name="Doc_Disclaimer">
<value>Disclaimer</value>
</data>
<data name="Doc_Readme">
<value>README</value>
</data>
<data name="Doc_Changelog">
<value>Changelog</value>
</data>
<data name="Doc_Credit">
<value>Acknowledgements</value>
</data>
<data name="Status_Processing_Filter">
<value>Processing</value>
</data>
<data name="Status_Failure">
<value>Failed</value>
</data>
<data name="Watermark_Search">
<value>Search by name...</value>
</data>
<data name="Placeholder_Size">
<value>Size</value>
</data>
<data name="Tip_GitHubProfile">
<value>GitHub Profile</value>
</data>
<data name="Filter_All">
<value>All</value>
</data>
<data name="Settings_FreeMemory">
<value>Free Memory</value>
</data>
<data name="Settings_FreeMemoryDesc">
<value>Force a garbage collection to free up memory.</value>
</data>
<data name="Settings_BtnFreeMemory">
<value>Free Memory</value>
</data>
<data name="Msg_MemoryFreed">
<value>Memory cleanup triggered.</value>
</data>
</root>
+12
View File
@@ -35,4 +35,16 @@ public class AppConfig
// File Processing Timeout
public bool IsFileTimeoutEnabled { get; set; } = false;
public int FileTimeoutSeconds { get; set; } = 60;
// Advanced Limits
public bool IsMaxFileCountEnabled { get; set; } = true;
public int MaxFileCount { get; set; } = 1000;
public bool IsMaxFolderCountEnabled { get; set; } = true;
public int MaxFolderCount { get; set; } = 3;
// Show Language Change Warning
public bool ShowLanguageChangeWarning { get; set; } = true;
// Monitoring
public bool ShowReadWriteSpeed { get; set; } = false;
}
+10
View File
@@ -0,0 +1,10 @@
namespace CheckHash.Models;
public static class AppConstants
{
public const int OneKB = 1024;
public const int OneMB = OneKB * 1024;
public const int OneGB = OneMB * 1024;
public const long OneTB = (long)OneGB * 1024;
public const long OnePB = OneTB * 1024;
}
+5 -2
View File
@@ -3,10 +3,13 @@ namespace CheckHash.Models;
public enum AppThemeStyle
{
Fluent,
MicaCustom,
Google,
HighContrast,
Colorblind
Colorblind,
Retro,
Glassmorphism,
Cyberpunk,
Pastel
}
public enum AppThemeVariant
+10
View File
@@ -0,0 +1,10 @@
namespace CheckHash.Models;
public enum FileSizeFilter
{
All,
Small, // < 1MB
Medium, // 1MB - 100MB
Large, // 100MB - 1GB
ExtraLarge // > 1GB
}
+10
View File
@@ -0,0 +1,10 @@
namespace CheckHash.Models;
public enum FileStatus
{
Ready,
Processing,
Success,
Failure,
Cancelled
}
+4 -2
View File
@@ -21,6 +21,7 @@ internal sealed class Program
try
{
ConfigurationService.Instance.EnsureConfigFileExists();
var config = ConfigurationService.Instance.Load();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
if (config.IsAdminModeEnabled && !IsRunAsAdmin())
@@ -48,9 +49,10 @@ internal sealed class Program
}
}
}
catch (Exception)
catch (Exception ex)
{
// Ignore startup errors to ensure app still tries to launch
// Ignore startup errors to ensure app still tries to launch, but log them
LoggerService.Instance.Log($"Startup error: {ex.Message}", LogLevel.Error);
}
BuildAvaloniaApp()
+46 -19
View File
@@ -11,11 +11,12 @@ public class ConfigurationService
{
private readonly string _configDir;
private readonly SemaphoreSlim _saveLock = new(1, 1);
private bool _hasCheckedConfigDir;
public ConfigurationService()
{
var appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
_configDir = Path.Combine(appData, "HashTool", "log", "settings");
_configDir = Path.Combine(appData, "HashTool", "settings");
ConfigPath = Path.Combine(_configDir, "config.json");
}
@@ -28,7 +29,11 @@ public class ConfigurationService
await _saveLock.WaitAsync();
try
{
if (!Directory.Exists(_configDir)) Directory.CreateDirectory(_configDir);
if (!_hasCheckedConfigDir)
{
if (!Directory.Exists(_configDir)) Directory.CreateDirectory(_configDir);
_hasCheckedConfigDir = true;
}
var json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllTextAsync(ConfigPath, json);
@@ -48,7 +53,11 @@ public class ConfigurationService
await _saveLock.WaitAsync();
try
{
if (!Directory.Exists(_configDir)) Directory.CreateDirectory(_configDir);
if (!_hasCheckedConfigDir)
{
if (!Directory.Exists(_configDir)) Directory.CreateDirectory(_configDir);
_hasCheckedConfigDir = true;
}
var json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllTextAsync(ConfigPath, json);
@@ -67,12 +76,9 @@ public class ConfigurationService
{
try
{
if (File.Exists(ConfigPath))
{
var json = File.ReadAllText(ConfigPath);
var config = JsonSerializer.Deserialize<AppConfig>(json);
return config ?? new AppConfig();
}
var json = File.ReadAllText(ConfigPath);
var config = JsonSerializer.Deserialize<AppConfig>(json);
return config ?? new AppConfig();
}
catch (Exception ex)
{
@@ -81,17 +87,21 @@ public class ConfigurationService
return new AppConfig();
}
public async System.Threading.Tasks.Task<AppConfig> LoadAsync()
{
try
{
if (File.Exists(ConfigPath))
{
var json = await File.ReadAllTextAsync(ConfigPath);
var config = JsonSerializer.Deserialize<AppConfig>(json);
return config ?? new AppConfig();
}
var json = await File.ReadAllTextAsync(ConfigPath);
var config = JsonSerializer.Deserialize<AppConfig>(json);
return config ?? new AppConfig();
}
catch (FileNotFoundException)
{
return new AppConfig();
}
catch (DirectoryNotFoundException)
{
return new AppConfig();
}
catch (Exception ex)
{
@@ -100,9 +110,26 @@ public class ConfigurationService
return new AppConfig();
}
public async System.Threading.Tasks.Task EnsureConfigFileExistsAsync()
public void EnsureConfigFileExists()
{
if (!File.Exists(ConfigPath)) await Save(new AppConfig());
try
{
if (!_hasCheckedConfigDir)
{
if (!Directory.Exists(_configDir)) Directory.CreateDirectory(_configDir);
_hasCheckedConfigDir = true;
}
if (!File.Exists(ConfigPath))
{
var config = new AppConfig();
var json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(ConfigPath, json);
}
}
catch (Exception ex)
{
LoggerService.Instance.Log($"Failed to ensure config file: {ex.Message}", LogLevel.Error);
}
}
}
+15 -12
View File
@@ -41,6 +41,7 @@ public partial class FontService : ObservableObject
[ObservableProperty] private FontFamily _selectedFont;
[ObservableProperty] private double _uiScale = 1.0;
private bool _hasCheckedSettingsDir;
private CancellationTokenSource? _saveSettingsCts;
private CancellationTokenSource? _saveLogCts;
@@ -116,9 +117,9 @@ public partial class FontService : ObservableObject
if (!Directory.Exists(_logDir)) Directory.CreateDirectory(_logDir);
await File.WriteAllTextAsync(_logFile, $"Default Font Set: {fontName} at {DateTime.Now}");
}
catch
catch (Exception ex)
{
// Ignore errors
LoggerService.Instance.Log($"Failed to save font log: {ex.Message}", LogLevel.Error);
}
}, TaskScheduler.Default);
}
@@ -161,14 +162,18 @@ public partial class FontService : ObservableObject
var json = JsonSerializer.Serialize(data);
var dir = Path.GetDirectoryName(_settingsFile);
if (dir != null && !Directory.Exists(dir)) Directory.CreateDirectory(dir);
if (!_hasCheckedSettingsDir)
{
var dir = Path.GetDirectoryName(_settingsFile);
if (dir != null && !Directory.Exists(dir)) Directory.CreateDirectory(dir);
_hasCheckedSettingsDir = true;
}
await File.WriteAllTextAsync(_settingsFile, json);
}
catch
catch (Exception ex)
{
// Ignore errors
LoggerService.Instance.Log($"Failed to save font settings: {ex.Message}", LogLevel.Error);
}
}
@@ -182,9 +187,9 @@ public partial class FontService : ObservableObject
return JsonSerializer.Deserialize<FontSettingsData>(json);
}
}
catch
catch (Exception ex)
{
// Ignore errors
LoggerService.Instance.Log($"Failed to load font settings: {ex.Message}", LogLevel.Error);
}
return null;
@@ -246,7 +251,6 @@ public partial class FontService : ObservableObject
newCache[font.Name] = font;
}
// Load settings data off-thread
var settingsData = await LoadSettingsDataAsync();
Dispatcher.UIThread.Invoke(() =>
@@ -254,10 +258,8 @@ public partial class FontService : ObservableObject
InstalledFonts.Clear();
_fontCache.Clear();
// Bulk add using AvaloniaList.AddRange
InstalledFonts.AddRange(newFonts);
// Bulk cache update
foreach (var kvp in newCache)
{
_fontCache[kvp.Key] = kvp.Value;
@@ -267,8 +269,9 @@ public partial class FontService : ObservableObject
});
});
}
catch (Exception)
catch (Exception ex)
{
LoggerService.Instance.Log($"Failed to load system fonts: {ex.Message}", LogLevel.Error);
var settingsData = await LoadSettingsDataAsync();
Dispatcher.UIThread.Invoke(() =>
{
+109 -19
View File
@@ -5,7 +5,9 @@ using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using System.IO.Hashing;
using Blake3;
using CheckHash.Models;
namespace CheckHash.Services;
@@ -16,40 +18,67 @@ public enum HashType
SHA256,
SHA384,
SHA512,
BLAKE3
BLAKE3,
XxHash32,
XxHash64,
XxHash3,
XxHash128,
CRC32
}
public class HashService
{
private const int DefaultBufferSize = 81920; // 80KB for Blake3 (optimal)
private const int LargeBufferSize = 1024 * 1024; // 1MB for others (reduces syscalls)
private const int DefaultBufferSize = 80 * AppConstants.OneKB;
private const int LargeBufferSize = AppConstants.OneMB;
public async Task<string> ComputeHashAsync(string filePath, HashType type, CancellationToken token)
public async Task<string> ComputeHashAsync(string filePath, HashType type, CancellationToken token, int? bufferSize = null, Action<long>? progressCallback = null)
{
int bufferSize = type == HashType.BLAKE3 ? DefaultBufferSize : LargeBufferSize;
int actualBufferSize = bufferSize ?? (type == HashType.BLAKE3 ? DefaultBufferSize : LargeBufferSize);
try
{
using var stream = new FileStream(
Stream stream = new FileStream(
filePath,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
bufferSize,
actualBufferSize,
FileOptions.Asynchronous | FileOptions.SequentialScan);
var hashBytes = type switch
if (progressCallback != null)
{
HashType.MD5 => await MD5.HashDataAsync(stream, token),
HashType.SHA1 => await SHA1.HashDataAsync(stream, token),
HashType.SHA256 => await SHA256.HashDataAsync(stream, token),
HashType.SHA384 => await SHA384.HashDataAsync(stream, token),
HashType.SHA512 => await SHA512.HashDataAsync(stream, token),
HashType.BLAKE3 => await ComputeBlake3Async(stream, token, bufferSize),
_ => throw new ArgumentOutOfRangeException(nameof(type), type, "Unknown HashType")
};
stream = new ProgressStream(stream, progressCallback);
}
return Convert.ToHexString(hashBytes);
await using (stream)
{
byte[] hashBytes;
switch (type)
{
case HashType.MD5:
case HashType.SHA1:
case HashType.SHA256:
case HashType.SHA384:
case HashType.SHA512:
hashBytes = await ComputeIncrementalHashAsync(stream, type, token, actualBufferSize);
break;
case HashType.BLAKE3:
hashBytes = await ComputeBlake3Async(stream, token, actualBufferSize);
break;
case HashType.XxHash32:
case HashType.XxHash64:
case HashType.XxHash3:
case HashType.XxHash128:
case HashType.CRC32:
hashBytes = await ComputeNonCryptoHashAsync(stream, type, token, actualBufferSize);
break;
default:
throw new ArgumentOutOfRangeException(nameof(type), type, "Unknown HashType");
}
return Convert.ToHexString(hashBytes);
}
}
catch (FileNotFoundException)
{
@@ -69,6 +98,35 @@ public class HashService
}
}
private async Task<byte[]> ComputeIncrementalHashAsync(Stream stream, HashType type, CancellationToken token, int bufferSize)
{
var algName = type switch
{
HashType.MD5 => HashAlgorithmName.MD5,
HashType.SHA1 => HashAlgorithmName.SHA1,
HashType.SHA256 => HashAlgorithmName.SHA256,
HashType.SHA384 => HashAlgorithmName.SHA384,
HashType.SHA512 => HashAlgorithmName.SHA512,
_ => throw new ArgumentException("Invalid hash type for IncrementalHash", nameof(type))
};
using var hasher = IncrementalHash.CreateHash(algName);
var buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer.AsMemory(), token)) > 0)
{
hasher.AppendData(new ReadOnlySpan<byte>(buffer, 0, bytesRead));
}
return hasher.GetCurrentHash();
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
private async Task<byte[]> ComputeBlake3Async(Stream stream, CancellationToken token, int bufferSize)
{
using var hasher = Hasher.New();
@@ -76,10 +134,10 @@ public class HashService
try
{
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer.AsMemory(), token)) > 0)
{
hasher.Update(new ReadOnlySpan<byte>(buffer, 0, bytesRead));
}
return hasher.Finalize().AsSpan().ToArray();
}
finally
@@ -87,4 +145,36 @@ public class HashService
ArrayPool<byte>.Shared.Return(buffer);
}
}
private async Task<byte[]> ComputeNonCryptoHashAsync(Stream stream, HashType type, CancellationToken token, int bufferSize)
{
NonCryptographicHashAlgorithm hasher = type switch
{
HashType.XxHash32 => new XxHash32(),
HashType.XxHash64 => new XxHash64(),
HashType.XxHash3 => new XxHash3(),
HashType.XxHash128 => new XxHash128(),
HashType.CRC32 => new Crc32(),
_ => throw new ArgumentException("Invalid hash type for NonCryptographicHashAlgorithm", nameof(type))
};
var buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer.AsMemory(), token)) > 0)
{
hasher.Append(new ReadOnlySpan<byte>(buffer, 0, bytesRead));
}
// Allocate exact size for result
var result = new byte[hasher.HashLengthInBytes];
hasher.GetCurrentHash(result);
return result;
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
}
+9
View File
@@ -0,0 +1,9 @@
namespace CheckHash.Services;
public static class HashTypeExtensions
{
public static bool IsInsecure(this HashType type)
{
return type == HashType.MD5 || type == HashType.SHA1;
}
}
+39 -87
View File
@@ -2,22 +2,25 @@ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text.Json;
using System.Threading;
using Avalonia.Media;
using CheckHash.Services;
using CommunityToolkit.Mvvm.ComponentModel;
namespace CheckHash.Services;
public partial class LocalizationService : ObservableObject
{
// ResourceManager -> CheckHash.Lang.Resources
private readonly ResourceManager _resourceManager;
private readonly ConcurrentDictionary<string, string> _cache = new();
private readonly CultureInfo _systemCulture;
private readonly CultureInfo _systemUICulture;
private CultureInfo _currentCulture;
private CultureInfo _currentCulture = CultureInfo.InvariantCulture;
[ObservableProperty] private FlowDirection _flowDirection = FlowDirection.LeftToRight;
[ObservableProperty] private LanguageItem _selectedLanguage;
@@ -37,95 +40,45 @@ public partial class LocalizationService : ObservableObject
public static LocalizationService Instance { get; } = new();
public List<LanguageItem> AvailableLanguages { get; } = new()
public List<LanguageItem> AvailableLanguages { get; } = LoadLanguages();
private static List<LanguageItem> LoadLanguages()
{
// AUTO DETECT LANGUAGE
//---------------------------------------//
new LanguageItem("Auto (System)", "auto"),
// DEFAULT LANGUAGE (IF NO MATCH FOUND)
//---------------------------------------//
new LanguageItem("English (US)", "en-US"),
// ARAB LANGUAGE (Use ar for all arab countries)
new LanguageItem("العربية (Arabic)", "ar"),
try
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "CheckHash.Lang.Languages.json";
// SOUTHEAST ASIA LANGUAGES
new LanguageItem("Tiếng Việt", "vi-VN"),
new LanguageItem("Bahasa Indonesia", "id-ID"),
new LanguageItem("ภาษาไทย (Thai)", "th-TH"),
new LanguageItem("Filipino (Tagalog)", "fil-PH"),
new LanguageItem("Bahasa Melayu (Malaysia)", "ms-MY"),
new LanguageItem("English (Singapore)", "en-sg"),
new LanguageItem("简体中文 (Singapore)", "zh-hans-sg"),
new LanguageItem("မြန်မာ (Burmese)", "my-MM"),
new LanguageItem("ខ្មែរ (Khmer)", "km-KH"),
new LanguageItem("ລາວ (Laos)", "lo-LA"),
using var stream = assembly.GetManifestResourceStream(resourceName);
if (stream == null)
{
// Fallback if resource not found
return GetDefaultLanguages();
}
// MIDDLE EAST/ WEST ASIA LANGUAGES
new LanguageItem("فارسی (Persian)", "fa-IR"),
new LanguageItem("עברית (Hebrew)", "he-IL"),
new LanguageItem("Türkçe (Turkish)", "tr-TR"),
new LanguageItem("Ελληνικά", "el-CY"),
using var reader = new StreamReader(stream);
var json = reader.ReadToEnd();
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var languages = JsonSerializer.Deserialize<List<LanguageItem>>(json, options);
//---------------------------------------//
// SOUTH ASIA LANGUAGES
new LanguageItem("हिन्दी (Hindi)", "hi-IN"),
new LanguageItem("English (India)", "en-IN"),
new LanguageItem("বাংলা (Bengali)", "bn-BD"),
new LanguageItem("සිංහල (Sinhala)", "si-LK"),
new LanguageItem("རྫོང་ཁ (Dzongkha)", "dz-BT"),
new LanguageItem("नेपाली (Nepali)", "ne-NP"),
new LanguageItem("ދިވެހި (Divehi)", "dv-MV"),
new LanguageItem("پښتو (Pashto)", "ps-AF"),
//--------------------------------------//
// EAST ASIA LANGUAGES
new LanguageItem("繁體中文 (Chinese Traditional)", "zh-hant"),
new LanguageItem("简体中文 (Chinese Simplified)", "zh-hans-cn"),
new LanguageItem("日本語 (Japanese)", "ja-jp"),
new LanguageItem("한국어 (Korean)", "ko-KR"),
new LanguageItem("Монгол (Mongolian)", "mn-MN"),
return languages ?? GetDefaultLanguages();
}
catch (Exception ex)
{
LoggerService.Instance.Log("Failed to load languages: " + ex.Message, LogLevel.Error);
return GetDefaultLanguages();
}
}
new LanguageItem("Қазақша (Kazakh)", "kk-KZ"),
new LanguageItem("Кыргызча (Kyrgyz)", "ky-KG"),
new LanguageItem("Тоҷикӣ (Tajik)", "tg-TJ"),
new LanguageItem("Türkmençe (Turkmen)", "tk-TM"),
private static List<LanguageItem> GetDefaultLanguages()
{
return new List<LanguageItem>
{
new("Auto (System)", "auto"),
new("English (US)", "en-US")
};
}
// EUROPE LANGUAGES
new LanguageItem("Español (Spanish)", "es-ES"),
new LanguageItem("Español (Latam)", "es-419"),
new LanguageItem("Français (French)", "fr-FR"),
new LanguageItem("Deutsch (German)", "de-DE"),
new LanguageItem("Svenska (Swedish)", "sv-SE"),
new LanguageItem("Bosanski (Bosnian Latin)", "bs-latn-ba"),
new LanguageItem("Polski (Polish)", "pl-PL"),
new LanguageItem("Русский (Russian)", "ru-RU"),
new LanguageItem("Deutsch (Austria)", "de-AT"),
new LanguageItem("Deutsch (Switzerland)", "de-CH"),
new LanguageItem("Shqip (Albanian)", "sq-AL"),
new LanguageItem("Македонски (Macedonian)", "mk-MK"),
new LanguageItem("Română (Romanian)", "ro-RO"),
new LanguageItem("Slovenčina (Slovak)", "sk-SK"),
new LanguageItem("Українська (Ukrainian)", "uk-UA"),
new LanguageItem("Hrvatski (Croatian)", "hr-HR"),
new LanguageItem("Čeština (Czech)", "cs-CZ"),
new LanguageItem("Italiano (Italian)", "it-IT"),
new LanguageItem("Српски (Serbian Cyrillic)", "sr-cyrl-rs"),
new LanguageItem("Български (Bulgarian)", "bg-BG"),
new LanguageItem("Dansk (Danish)", "da-DK"),
new LanguageItem("Ελληνικά (Greek)", "el-GR"),
new LanguageItem("Suomeksi (Finnish)", "fi-FI"),
new LanguageItem("Magyar (Hungarian)", "hu-HU"),
new LanguageItem("Norsk (Norwegian)", "nb-NO"),
new LanguageItem("Nederlands (Dutch)", "nl-NL"),
new LanguageItem("Nederlands (Belgium)", "nl-BE"),
new LanguageItem("Íslenska (Icelandic)", "is-IS"),
new LanguageItem("Slovenščina (Slovenian)", "sl-SI"),
new LanguageItem("Eesti (Estonian)", "et-EE"),
new LanguageItem("Latviešu (Latvian)", "lv-LV"),
new LanguageItem("Lietuvių (Lithuanian)", "lt-LT"),
new LanguageItem("Português (Brasil)", "pt-BR")
};
// Indexer
public string this[string key]
{
get
@@ -176,6 +129,7 @@ public partial class LocalizationService : ObservableObject
}
catch
{
// Ignore and use fallback
}
return fallbackCode;
@@ -188,13 +142,11 @@ public partial class LocalizationService : ObservableObject
_currentCulture = new CultureInfo(languageCode);
_cache.Clear();
// Update Thread Culture
Thread.CurrentThread.CurrentCulture = _currentCulture;
Thread.CurrentThread.CurrentUICulture = _currentCulture;
UpdateFlowDirection(languageCode);
// Update UI bindings
OnPropertyChanged("Item[]");
}
catch
+42 -10
View File
@@ -28,6 +28,7 @@ public partial class LoggerService : ObservableObject
private readonly string _logBaseDir;
private readonly Channel<LogWriteRequest> _logChannel;
private readonly Channel<string> _uiLogChannel = Channel.CreateUnbounded<string>();
private readonly List<(string Path, string Placeholder)> _replacements;
// Settings
[ObservableProperty] private bool _isRecording = true;
@@ -47,6 +48,27 @@ public partial class LoggerService : ObservableObject
_logChannel = Channel.CreateUnbounded<LogWriteRequest>();
_ = ProcessLogQueueAsync();
_ = ProcessUiLogQueueAsync();
// Initialize replacements for SanitizeMessage
_replacements = new List<(string Path, string Placeholder)>();
var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var tempPath = Path.GetTempPath();
if (!string.IsNullOrEmpty(userProfile) && userProfile != Path.DirectorySeparatorChar.ToString())
{
_replacements.Add((userProfile, "[USER_PROFILE]"));
}
if (!string.IsNullOrEmpty(tempPath) && tempPath != Path.DirectorySeparatorChar.ToString())
{
var trimmedTemp = tempPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (!string.IsNullOrEmpty(trimmedTemp))
{
_replacements.Add((trimmedTemp, "[TEMP]"));
}
}
_replacements = _replacements.OrderByDescending(x => x.Path.Length).ToList();
}
public static LoggerService Instance { get; } = new();
@@ -62,6 +84,7 @@ public partial class LoggerService : ObservableObject
public void Log(string message, LogLevel level = LogLevel.Info)
{
message = SanitizeMessage(message);
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var logEntry = $"[{timestamp}] [{level.ToString().ToUpper()}] {message}";
@@ -79,6 +102,18 @@ public partial class LoggerService : ObservableObject
Dispatcher.UIThread.Post(() => Logs.Clear());
}
private string SanitizeMessage(string message)
{
if (string.IsNullOrEmpty(message)) return message;
foreach (var (path, placeholder) in _replacements)
{
message = message.Replace(path, placeholder, StringComparison.OrdinalIgnoreCase);
}
return message;
}
private void WriteToFile(string dir, string filename, string content)
{
// Offload to background channel
@@ -87,9 +122,10 @@ public partial class LoggerService : ObservableObject
private async Task ProcessUiLogQueueAsync()
{
var batch = new List<string>();
while (await _uiLogChannel.Reader.WaitToReadAsync())
{
var batch = new List<string>();
batch.Clear();
while (_uiLogChannel.Reader.TryRead(out var msg))
{
batch.Add(msg);
@@ -98,35 +134,34 @@ public partial class LoggerService : ObservableObject
if (batch.Count > 0)
{
var itemsToAdd = batch.ToList();
await Dispatcher.UIThread.InvokeAsync(() =>
{
Logs.AddRange(batch);
Logs.AddRange(itemsToAdd);
if (Logs.Count > 1000)
{
Logs.RemoveRange(0, Logs.Count - 1000);
}
}, DispatcherPriority.Background);
await Task.Delay(100); // Throttle updates
await Task.Delay(50);
}
}
}
private async Task ProcessLogQueueAsync()
{
var batch = new List<LogWriteRequest>();
while (await _logChannel.Reader.WaitToReadAsync())
{
var batch = new List<LogWriteRequest>();
batch.Clear();
while (_logChannel.Reader.TryRead(out var msg))
{
batch.Add(msg);
// Limit batch size to avoid holding too much memory or delaying writes too long
if (batch.Count >= 1000) break;
}
if (batch.Count == 0) continue;
// Group by file path to minimize file open/close operations
var fileGroups = batch.GroupBy(x => Path.Combine(x.Directory, x.Filename));
foreach (var group in fileGroups)
@@ -138,9 +173,6 @@ public partial class LoggerService : ObservableObject
{
sb.AppendLine(item.Content);
}
// Use AppendAllTextAsync which opens and closes the file.
// Since we batched messages, this is much more efficient than one open/close per message.
await File.AppendAllTextAsync(group.Key, sb.ToString());
}
catch
+264 -67
View File
@@ -1,64 +1,221 @@
using System;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Material.Icons;
using Material.Icons.Avalonia;
namespace CheckHash.Services;
public enum MessageBoxIcon
{
None,
Information,
Warning,
Error,
Success,
Question
}
public static class MessageBoxHelper
{
public static async Task ShowAsync(string title, string message)
private static Control? GetIconControl(MessageBoxIcon icon)
{
if (icon == MessageBoxIcon.None) return null;
MaterialIconKind kind;
IBrush color;
switch (icon)
{
case MessageBoxIcon.Information:
kind = MaterialIconKind.Information;
color = Brushes.DodgerBlue;
break;
case MessageBoxIcon.Success:
kind = MaterialIconKind.CheckCircle;
color = Brushes.Green;
break;
case MessageBoxIcon.Warning:
kind = MaterialIconKind.Alert;
color = Brushes.Orange;
break;
case MessageBoxIcon.Error:
kind = MaterialIconKind.CloseCircle;
color = Brushes.Red;
break;
case MessageBoxIcon.Question:
kind = MaterialIconKind.HelpCircle;
color = Brushes.DodgerBlue;
break;
default:
return null;
}
return new MaterialIcon
{
Kind = kind,
Width = 32,
Height = 32,
Foreground = color,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 15, 0)
};
}
private static (Window window, StackPanel contentPanel) CreateBaseWindow(string title, MessageBoxIcon icon)
{
var window = new Window
{
Title = title,
Width = 400,
SystemDecorations = SystemDecorations.None,
Width = 450,
SizeToContent = SizeToContent.Height,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
CanResize = false
CanResize = false,
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent, WindowTransparencyLevel.None },
Background = Brushes.Transparent
};
if (Application.Current != null &&
Application.Current.TryFindResource("PaneBackgroundBrush", null, out var bg) && bg is IBrush brush)
window.Background = brush;
// Main Container (DockPanel)
// Top: Title Bar
// Center: Content (Icon + Text) + Buttons (Bottom of center?)
// Actually, let's use a Grid for the whole window content
// Row 0: Title Bar
// Row 1: Content
var rootGrid = new Grid();
rootGrid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); // Title
rootGrid.RowDefinitions.Add(new RowDefinition(GridLength.Auto)); // Content
// Title Bar
var titleText = new TextBlock
{
Text = title,
FontWeight = FontWeight.Bold,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(10, 8, 10, 8)
};
var titleBar = new Border
{
Child = titleText
};
// Drag logic
titleBar.PointerPressed += (_, e) =>
{
if (e.GetCurrentPoint(window).Properties.IsLeftButtonPressed)
{
window.BeginMoveDrag(e);
}
};
Grid.SetRow(titleBar, 0);
rootGrid.Children.Add(titleBar);
// Content Container
var contentStack = new StackPanel
{
Margin = new Thickness(20),
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(contentStack, 1);
rootGrid.Children.Add(contentStack);
// Wrap everything in a Border to provide rounded corners and background
var windowBorder = new Border
{
CornerRadius = new CornerRadius(10),
BorderThickness = new Thickness(1),
ClipToBounds = true,
Child = rootGrid
};
// Bind resources if Application.Current is available
if (Application.Current != null)
{
titleBar.Bind(Border.BackgroundProperty, Application.Current.GetResourceObservable("AppBackgroundBrush"));
windowBorder.Bind(Border.BackgroundProperty, Application.Current.GetResourceObservable("PaneBackgroundBrush"));
windowBorder.Bind(Border.BorderBrushProperty, Application.Current.GetResourceObservable("HighlightBrush"));
}
else
{
// Fallbacks for testing
titleBar.Background = Brushes.LightGray;
windowBorder.Background = Brushes.White;
windowBorder.BorderBrush = Brushes.Gray;
}
window.Content = windowBorder;
// Bind Fonts
window.Bind(TemplatedControl.FontFamilyProperty, new Binding("SelectedFont") { Source = FontService.Instance });
window.Bind(TemplatedControl.FontSizeProperty, new Binding("BaseFontSize") { Source = FontService.Instance });
return (window, contentStack);
}
private static Grid CreateMessageContent(string message, MessageBoxIcon icon)
{
var grid = new Grid();
grid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Auto));
grid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
var iconControl = GetIconControl(icon);
if (iconControl != null)
{
Grid.SetColumn(iconControl, 0);
grid.Children.Add(iconControl);
}
var textBlock = new TextBlock
{
Text = message,
TextWrapping = TextWrapping.Wrap,
HorizontalAlignment = HorizontalAlignment.Center,
// VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(3),
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Left,
TextAlignment = TextAlignment.Left
};
//* Ok button *//
Grid.SetColumn(textBlock, 1);
grid.Children.Add(textBlock);
return grid;
}
public static async Task ShowAsync(string title, string message, MessageBoxIcon icon = MessageBoxIcon.Information)
{
var (window, contentPanel) = CreateBaseWindow(title, icon);
// Content
var messageGrid = CreateMessageContent(message, icon);
messageGrid.Margin = new Thickness(0, 0, 0, 20);
contentPanel.Children.Add(messageGrid);
// OK Button
var button = new Button
{
Content = LocalizationService.Instance["Btn_OK"],
HorizontalAlignment = HorizontalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Right,
HorizontalContentAlignment = HorizontalAlignment.Center,
Width = 100,
Margin = new Thickness(0, 0, 0, 20)
Width = 80
};
// Close the window when the button is clicked
button.Click += (_, _) => window.Close();
var stackPanel = new StackPanel
var btnContainer = new StackPanel
{
VerticalAlignment = VerticalAlignment.Center,
Children = { textBlock, button }
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Right,
Children = { button }
};
window.Content = stackPanel;
window.Bind(TemplatedControl.FontFamilyProperty, new Binding("SelectedFont") { Source = FontService.Instance });
window.Bind(TemplatedControl.FontSizeProperty, new Binding("BaseFontSize") { Source = FontService.Instance });
contentPanel.Children.Add(btnContainer);
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop &&
desktop.MainWindow != null)
@@ -66,47 +223,29 @@ public static class MessageBoxHelper
}
public static async Task<bool> ShowConfirmationAsync(string title, string message, string yesText = "Yes",
string noText = "No")
string noText = "No", MessageBoxIcon icon = MessageBoxIcon.Question)
{
var window = new Window
{
Title = title,
Width = 350,
SizeToContent = SizeToContent.Height,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
CanResize = false
};
var (window, contentPanel) = CreateBaseWindow(title, icon);
if (Application.Current != null &&
Application.Current.TryFindResource("PaneBackgroundBrush", null, out var bg) && bg is IBrush brush)
window.Background = brush;
var textBlock = new TextBlock
{
Text = message,
TextWrapping = TextWrapping.Wrap,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(10, 20, 10, 20),
TextAlignment = TextAlignment.Center
};
// Content
var messageGrid = CreateMessageContent(message, icon);
messageGrid.Margin = new Thickness(0, 0, 0, 20);
contentPanel.Children.Add(messageGrid);
// Buttons
var btnYes = new Button
{
Content = yesText,
HorizontalAlignment = HorizontalAlignment.Center,
HorizontalContentAlignment = HorizontalAlignment.Center,
Width = 80,
Margin = new Thickness(5)
HorizontalContentAlignment = HorizontalAlignment.Center,
Margin = new Thickness(0, 0, 10, 0)
};
var btnNo = new Button
{
Content = noText,
HorizontalAlignment = HorizontalAlignment.Center,
HorizontalContentAlignment = HorizontalAlignment.Center,
Width = 80,
Margin = new Thickness(5)
Width = 80
};
var result = false;
@@ -126,21 +265,10 @@ public static class MessageBoxHelper
var btnPanel = new StackPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Center,
Margin = new Thickness(0, 0, 0, 20),
HorizontalAlignment = HorizontalAlignment.Right,
Children = { btnYes, btnNo }
};
var stackPanel = new StackPanel
{
VerticalAlignment = VerticalAlignment.Center,
Children = { textBlock, btnPanel }
};
window.Content = stackPanel;
window.Bind(TemplatedControl.FontFamilyProperty, new Binding("SelectedFont") { Source = FontService.Instance });
window.Bind(TemplatedControl.FontSizeProperty, new Binding("BaseFontSize") { Source = FontService.Instance });
contentPanel.Children.Add(btnPanel);
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop &&
desktop.MainWindow != null)
@@ -148,4 +276,73 @@ public static class MessageBoxHelper
return result;
}
}
public static async Task<(bool Confirmed, bool IsChecked)> ShowConfirmationWithCheckboxAsync(
string title, string message, string checkboxText, string yesText = "Yes", string noText = "No", MessageBoxIcon icon = MessageBoxIcon.Question)
{
var (window, contentPanel) = CreateBaseWindow(title, icon);
// Content
var messageGrid = CreateMessageContent(message, icon);
messageGrid.Margin = new Thickness(0, 0, 0, 10);
contentPanel.Children.Add(messageGrid);
// Checkbox
var checkBox = new CheckBox
{
Content = checkboxText,
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(0, 0, 0, 20)
};
// Indent checkbox to align with text if icon exists?
// If icon exists (32 + 15 = 47), we might want to indent.
// But simplified, just putting it below is fine.
// If we want it aligned with text, we should put it in the Grid?
// Let's keep it simple: below the message grid.
contentPanel.Children.Add(checkBox);
// Buttons
var btnYes = new Button
{
Content = yesText,
Width = 80,
HorizontalContentAlignment = HorizontalAlignment.Center,
Margin = new Thickness(0, 0, 10, 0)
};
var btnNo = new Button
{
Content = noText,
HorizontalContentAlignment = HorizontalAlignment.Center,
Width = 80
};
var confirmed = false;
btnYes.Click += (_, _) =>
{
confirmed = true;
window.Close();
};
btnNo.Click += (_, _) =>
{
confirmed = false;
window.Close();
};
var btnPanel = new StackPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Right,
Children = { btnYes, btnNo }
};
contentPanel.Children.Add(btnPanel);
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop &&
desktop.MainWindow != null)
await window.ShowDialog(desktop.MainWindow);
return (confirmed, checkBox.IsChecked ?? false);
}
}
+9 -14
View File
@@ -9,25 +9,20 @@ public partial class PreferencesService : ObservableObject
[ObservableProperty] private FileSizeUnit _fileSizeLimitUnit = FileSizeUnit.GB;
[ObservableProperty] private double _fileSizeLimitValue = 10;
[ObservableProperty] private int _fileTimeoutSeconds = 60;
// Limit file size
[ObservableProperty] private bool _isFileSizeLimitEnabled;
// File Timeout
[ObservableProperty] private bool _isFileTimeoutEnabled;
[ObservableProperty] private bool _isHashMaskingEnabled;
[ObservableProperty] private bool _isMaxFileCountEnabled = true;
[ObservableProperty] private int _maxFileCount = 1000;
[ObservableProperty] private bool _isMaxFolderCountEnabled = true;
[ObservableProperty] private int _maxFolderCount = 3;
public static PreferencesService Instance { get; } = new();
// Force Cancel Event
public event EventHandler? ForceCancelRequested;
public void RequestForceCancel()
{
ForceCancelRequested?.Invoke(this, EventArgs.Empty);
}
// Calculate max size in bytes
public long GetMaxSizeBytes()
{
if (!IsFileSizeLimitEnabled) return long.MaxValue;
@@ -35,11 +30,11 @@ public partial class PreferencesService : ObservableObject
double multiplier = FileSizeLimitUnit switch
{
FileSizeUnit.Byte => 1,
FileSizeUnit.KB => 1024,
FileSizeUnit.MB => 1024 * 1024,
FileSizeUnit.GB => 1024 * 1024 * 1024,
FileSizeUnit.TB => 1024L * 1024 * 1024 * 1024,
FileSizeUnit.PB => 1024L * 1024 * 1024 * 1024 * 1024,
FileSizeUnit.KB => AppConstants.OneKB,
FileSizeUnit.MB => AppConstants.OneMB,
FileSizeUnit.GB => AppConstants.OneGB,
FileSizeUnit.TB => AppConstants.OneTB,
FileSizeUnit.PB => AppConstants.OnePB,
_ => 1
};
+58
View File
@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using CheckHash.Models;
namespace CheckHash.Services;
public class ProcessingStrategyService
{
private const long OneGB = 1024L * 1024 * 1024;
private const long HeavyFileThreshold = 5L * 1024 * 1024 * 1024; // 5GB
private const int OneMB = 1024 * 1024;
private const int TwoMB = 2 * 1024 * 1024;
private const int FourMB = 4 * 1024 * 1024;
private const int Blake3BufferSize = 80 * 1024; // 80KB
public List<List<T>> GetProcessingBatches<T>(IEnumerable<T> items, Func<T, long> sizeSelector)
{
var result = new List<List<T>> { new(), new(), new() };
foreach (var item in items)
{
var size = sizeSelector(item);
if (size < OneGB)
{
result[0].Add(item);
}
else if (size < HeavyFileThreshold)
{
result[1].Add(item);
}
else
{
result[2].Add(item);
}
}
return result;
}
public int GetBufferSize(long size, HashType algorithm)
{
if (algorithm == HashType.BLAKE3)
{
return Blake3BufferSize;
}
if (size < OneGB)
{
return OneMB;
}
if (size < HeavyFileThreshold)
{
return TwoMB;
}
return FourMB;
}
}
+79
View File
@@ -0,0 +1,79 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace CheckHash.Services;
public class ProgressStream : Stream
{
private readonly Stream _inner;
private readonly Action<long>? _onBytesRead;
private readonly Action<long>? _onBytesWritten;
public ProgressStream(Stream inner, Action<long>? onBytesRead = null, Action<long>? onBytesWritten = null)
{
_inner = inner;
_onBytesRead = onBytesRead;
_onBytesWritten = onBytesWritten;
}
public override bool CanRead => _inner.CanRead;
public override bool CanSeek => _inner.CanSeek;
public override bool CanWrite => _inner.CanWrite;
public override long Length => _inner.Length;
public override long Position
{
get => _inner.Position;
set => _inner.Position = value;
}
public override void Flush() => _inner.Flush();
public override int Read(byte[] buffer, int offset, int count)
{
var bytesRead = _inner.Read(buffer, offset, count);
if (bytesRead > 0) _onBytesRead?.Invoke(bytesRead);
return bytesRead;
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var bytesRead = await _inner.ReadAsync(buffer, offset, count, cancellationToken);
if (bytesRead > 0) _onBytesRead?.Invoke(bytesRead);
return bytesRead;
}
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
var bytesRead = await _inner.ReadAsync(buffer, cancellationToken);
if (bytesRead > 0) _onBytesRead?.Invoke(bytesRead);
return bytesRead;
}
public override long Seek(long offset, SeekOrigin origin) => _inner.Seek(offset, origin);
public override void SetLength(long value) => _inner.SetLength(value);
public override void Write(byte[] buffer, int offset, int count)
{
_inner.Write(buffer, offset, count);
_onBytesWritten?.Invoke(count);
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await _inner.WriteAsync(buffer, offset, count, cancellationToken);
_onBytesWritten?.Invoke(count);
}
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
await _inner.WriteAsync(buffer, cancellationToken);
_onBytesWritten?.Invoke(buffer.Length);
}
protected override void Dispose(bool disposing)
{
if (disposing) _inner.Dispose();
base.Dispose(disposing);
}
}
@@ -4,13 +4,11 @@ using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Media;
using Avalonia.Platform;
// Để check OS
namespace CheckHash.Services.ThemeEffects;
public static class LiquidGlassEffect
public static class WindowEffect
{
// Hàm áp dụng hiệu ứng cho toàn bộ UI (tìm MainWindow)
public static void ApplyToMainWindow()
{
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
@@ -18,7 +16,6 @@ public static class LiquidGlassEffect
Apply(window);
}
// Hàm gỡ bỏ hiệu ứng cho toàn bộ UI
public static void DisableForMainWindow()
{
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
@@ -26,60 +23,40 @@ public static class LiquidGlassEffect
Disable(window);
}
// Hàm áp dụng hiệu ứng cụ thể cho 1 window
public static void Apply(Window window)
{
if (window == null) return;
// 1. Cấu hình chung bắt buộc cho hiệu ứng kính
window.Background = Brushes.Transparent;
// 2. Xử lý riêng cho từng Hệ điều hành
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
ApplyMacOS(window);
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
ApplyWindows(window);
else
window.TransparencyLevelHint = new[] { WindowTransparencyLevel.None };
// 3. Tinh chỉnh UI cho Liquid Glass (Bo góc, Toolbar nhỏ hơn)
// Lưu ý: Việc thay đổi Margin/CornerRadius của SplitView Pane nên được thực hiện qua Style hoặc Binding
// Nhưng ở đây ta có thể inject Resource hoặc Style class nếu cần.
// Tạm thời ta đã xử lý Margin="0,10" trong MainWindow.axaml để tạo khoảng hở cho toolbar.
}
// Hàm gỡ bỏ hiệu ứng (về mặc định - Solid)
public static void Disable(Window window)
{
if (window == null) return;
// Tắt hiệu ứng trong suốt
window.TransparencyLevelHint = new[] { WindowTransparencyLevel.None };
// Reset background về null hoặc để ThemeService tự set lại màu Solid
// window.Background = null;
}
// --- LOGIC CHI TIẾT ---
private static void ApplyMacOS(Window window)
{
// macOS hỗ trợ AcrylicBlur rất đẹp (hiệu ứng mờ phía sau cửa sổ)
window.TransparencyLevelHint = new[]
{
WindowTransparencyLevel.AcrylicBlur,
WindowTransparencyLevel.Blur
};
// Để hiệu ứng kính tràn lên cả thanh tiêu đề (TitleBar) tạo cảm giác liền mạch
window.ExtendClientAreaToDecorationsHint = true;
window.ExtendClientAreaChromeHints = ExtendClientAreaChromeHints.PreferSystemChrome;
}
private static void ApplyWindows(Window window)
{
// Windows 11 hỗ trợ Mica (vật liệu mới, lấy màu từ hình nền desktop) và Acrylic
// Ưu tiên Mica (nhẹ hơn, đẹp hơn, native Win 11) -> Nếu không có thì Acrylic -> Blur
window.TransparencyLevelHint = new[]
{
WindowTransparencyLevel.Mica,
@@ -87,7 +64,6 @@ public static class LiquidGlassEffect
WindowTransparencyLevel.Blur
};
// Trên Windows cũng nên mở rộng vùng client để hiệu ứng đẹp hơn
window.ExtendClientAreaToDecorationsHint = true;
window.ExtendClientAreaChromeHints = ExtendClientAreaChromeHints.PreferSystemChrome;
}
+94 -18
View File
@@ -15,18 +15,6 @@ public static class ThemePalettes
switch (style)
{
// =================================================================
// MICA CUSTOM THEME
// =================================================================
case AppThemeStyle.MicaCustom:
p["AppBackgroundColor"] = Color.Parse("#991E1E1E");
p["AppBackgroundBrush"] = Brush.Parse("#991E1E1E");
p["PaneBackgroundColor"] = Color.Parse("#99252525");
p["PaneBackgroundBrush"] = Brush.Parse("#99252525");
p["GlassBorderBrush"] = Brush.Parse("#40FFFFFF");
break;
// =================================================================
// GOOGLE MATERIAL THEME
@@ -103,6 +91,94 @@ public static class ThemePalettes
p["StatusErrorBrush"] = Brush.Parse("#D55E00");
break;
// =================================================================
// RETRO THEME
// =================================================================
case AppThemeStyle.Retro:
if (!isDark)
{
p["AppBackgroundColor"] = Color.Parse("#FBF1C7");
p["AppBackgroundBrush"] = Brush.Parse("#FBF1C7");
p["PaneBackgroundColor"] = Color.Parse("#EBDBB2");
p["PaneBackgroundBrush"] = Brush.Parse("#EBDBB2");
p["GlassBorderBrush"] = Brushes.Transparent;
}
else
{
p["AppBackgroundColor"] = Color.Parse("#282828");
p["AppBackgroundBrush"] = Brush.Parse("#282828");
p["PaneBackgroundColor"] = Color.Parse("#3C3836");
p["PaneBackgroundBrush"] = Brush.Parse("#3C3836");
p["GlassBorderBrush"] = Brushes.Transparent;
}
break;
// =================================================================
// GLASSMORPHISM THEME
// =================================================================
case AppThemeStyle.Glassmorphism:
if (!isDark)
{
p["AppBackgroundColor"] = Color.Parse("#99FFFFFF");
p["AppBackgroundBrush"] = Brush.Parse("#99FFFFFF");
p["PaneBackgroundColor"] = Color.Parse("#99F3F3F3");
p["PaneBackgroundBrush"] = Brush.Parse("#99F3F3F3");
p["GlassBorderBrush"] = Brush.Parse("#40000000");
}
else
{
p["AppBackgroundColor"] = Color.Parse("#99000000");
p["AppBackgroundBrush"] = Brush.Parse("#99000000");
p["PaneBackgroundColor"] = Color.Parse("#991E1E1E");
p["PaneBackgroundBrush"] = Brush.Parse("#991E1E1E");
p["GlassBorderBrush"] = Brush.Parse("#40FFFFFF");
}
break;
// =================================================================
// CYBERPUNK THEME
// =================================================================
case AppThemeStyle.Cyberpunk:
if (!isDark)
{
p["AppBackgroundColor"] = Color.Parse("#F0F0F5");
p["AppBackgroundBrush"] = Brush.Parse("#F0F0F5");
p["PaneBackgroundColor"] = Color.Parse("#FFFFFF");
p["PaneBackgroundBrush"] = Brush.Parse("#FFFFFF");
p["GlassBorderBrush"] = Brush.Parse("#FF0099");
}
else
{
p["AppBackgroundColor"] = Color.Parse("#0B0C15");
p["AppBackgroundBrush"] = Brush.Parse("#0B0C15");
p["PaneBackgroundColor"] = Color.Parse("#1F2235");
p["PaneBackgroundBrush"] = Brush.Parse("#1F2235");
p["GlassBorderBrush"] = Brush.Parse("#00F3FF");
}
break;
// =================================================================
// PASTEL THEME
// =================================================================
case AppThemeStyle.Pastel:
if (!isDark)
{
p["AppBackgroundColor"] = Color.Parse("#FFF0F5");
p["AppBackgroundBrush"] = Brush.Parse("#FFF0F5");
p["PaneBackgroundColor"] = Color.Parse("#FFFFFF");
p["PaneBackgroundBrush"] = Brush.Parse("#FFFFFF");
p["GlassBorderBrush"] = Brush.Parse("#FFB7B2");
}
else
{
p["AppBackgroundColor"] = Color.Parse("#2A2A35");
p["AppBackgroundBrush"] = Brush.Parse("#2A2A35");
p["PaneBackgroundColor"] = Color.Parse("#3E3E4E");
p["PaneBackgroundBrush"] = Brush.Parse("#3E3E4E");
p["GlassBorderBrush"] = Brush.Parse("#B5EAD7");
}
break;
// =================================================================
// FLUENT (Default)
// =================================================================
@@ -110,18 +186,18 @@ public static class ThemePalettes
default:
if (!isDark)
{
p["AppBackgroundColor"] = Color.Parse("#F8F9FA");
p["AppBackgroundBrush"] = Brush.Parse("#F8F9FA");
p["AppBackgroundColor"] = Color.Parse("#F3F3F3");
p["AppBackgroundBrush"] = Brush.Parse("#F3F3F3");
p["PaneBackgroundColor"] = Color.Parse("#FFFFFF");
p["PaneBackgroundBrush"] = Brush.Parse("#FFFFFF");
p["GlassBorderBrush"] = Brushes.Transparent;
}
else
{
p["AppBackgroundColor"] = Color.Parse("#121212");
p["AppBackgroundBrush"] = Brush.Parse("#121212");
p["PaneBackgroundColor"] = Color.Parse("#212529");
p["PaneBackgroundBrush"] = Brush.Parse("#212529");
p["AppBackgroundColor"] = Color.Parse("#202020");
p["AppBackgroundBrush"] = Brush.Parse("#202020");
p["PaneBackgroundColor"] = Color.Parse("#2C2C2C");
p["PaneBackgroundBrush"] = Brush.Parse("#2C2C2C");
p["GlassBorderBrush"] = Brushes.Transparent;
}
+14 -17
View File
@@ -70,29 +70,26 @@ public partial class ThemeService : ObservableObject
var palette = ThemePalettes.GetPalette(CurrentThemeStyle, effectiveVariant);
// 4. Apply Palette
foreach (var kvp in palette) app.Resources[kvp.Key] = kvp.Value;
// Note: Explicitly remove before adding to ensure change notification propagates immediately,
// specifically for switching between Light/Dark variants of the same theme (e.g. Glassmorphism).
foreach (var kvp in palette)
{
if (app.Resources.ContainsKey(kvp.Key))
{
app.Resources.Remove(kvp.Key);
}
app.Resources[kvp.Key] = kvp.Value;
}
// 5. Apply Window Effects
if (CurrentThemeStyle == AppThemeStyle.MicaCustom)
LiquidGlassEffect.ApplyToMainWindow();
if (CurrentThemeStyle == AppThemeStyle.Fluent || CurrentThemeStyle == AppThemeStyle.Glassmorphism)
WindowEffect.ApplyToMainWindow();
else
LiquidGlassEffect.DisableForMainWindow();
WindowEffect.DisableForMainWindow();
}
public List<AppThemeStyle> GetAvailableThemesForVariant(AppThemeVariant variant)
{
var all = Enum.GetValues(typeof(AppThemeStyle)).Cast<AppThemeStyle>().ToList();
var isDark = variant == AppThemeVariant.Dark;
if (variant == AppThemeVariant.System)
{
var systemVariant = Application.Current?.PlatformSettings?.GetColorValues().ThemeVariant;
isDark = systemVariant == PlatformThemeVariant.Dark;
}
if (!isDark) return all.Where(t => t != AppThemeStyle.MicaCustom).ToList();
return all;
return Enum.GetValues(typeof(AppThemeStyle)).Cast<AppThemeStyle>().ToList();
}
}
+34 -8
View File
@@ -45,19 +45,45 @@ public static class UrlHelper
if (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)
return true;
// Check for Directory
// We only allow absolute paths to existing directories to prevent command injection via arguments
return false;
}
public static void OpenLocalFolder(string path)
{
if (string.IsNullOrWhiteSpace(path)) return;
try
{
// Ensure it's not a relative path that could be interpreted as a flag
if (Path.IsPathRooted(url) && Directory.Exists(url)) return true;
if (!Path.IsPathRooted(path) || !Directory.Exists(path)) return;
var appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var fullPath = Path.GetFullPath(path);
var safePath = Path.GetFullPath(Path.Combine(appData, "HashTool"));
if (!fullPath.Equals(safePath, StringComparison.OrdinalIgnoreCase) &&
!fullPath.StartsWith(safePath + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
{
return;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo(path) { UseShellExecute = true });
}
else
{
var fileName = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "open" : "xdg-open";
var startInfo = new ProcessStartInfo
{
FileName = fileName,
UseShellExecute = false,
CreateNoWindow = true
};
startInfo.ArgumentList.Add(path);
Process.Start(startInfo);
}
}
catch
{
// Invalid path characters or other errors
return false;
// Ignore errors
}
return false;
}
}
+55 -8
View File
@@ -1,7 +1,9 @@
using System;
using System.Net;
using System.Net.Http;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Velopack;
@@ -9,12 +11,23 @@ using Velopack.Sources;
namespace CheckHash.Services;
public enum NetworkStatus
{
Connected,
NoConnection,
ClientError,
ServerError,
ApiLimitExceeded
}
public class UpdateService
{
private static UpdateService? _instance;
public static UpdateService Instance => _instance ??= new UpdateService();
// URL GitHub Repo
private const string RepoUrl = "https://github.com/poli0981/CheckHash-Multiflatform";
private const string RepoUrl = "https://github.com/poli0981/HashTool";
private readonly HttpClient _httpClient;
private UpdateManager? _manager;
@@ -22,8 +35,10 @@ public class UpdateService
public UpdateService()
{
_httpClient = new HttpClient();
_httpClient.Timeout = TimeSpan.FromSeconds(30);
// GitHub API requires a User-Agent header
_httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("CheckHash", "1.0"));
var version = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "1.0.0";
_httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("HashTool", version));
try
{
@@ -62,23 +77,55 @@ public class UpdateService
_manager?.ApplyUpdatesAndRestart(info);
}
public async Task<NetworkStatus> CheckConnectivityAsync()
{
try
{
var apiUrlBase = RepoUrl.Replace("https://github.com/", "https://api.github.com/repos/");
using var request = new HttpRequestMessage(HttpMethod.Head, apiUrlBase);
var response = await _httpClient.SendAsync(request);
if (response.IsSuccessStatusCode) return NetworkStatus.Connected;
var code = (int)response.StatusCode;
if (code == 403 || code == 429) // 403 Forbidden (Rate Limit) or 429 Too Many Requests
{
if (response.Headers.TryGetValues("X-RateLimit-Remaining", out var values))
{
var remaining = values.FirstOrDefault();
if (remaining == "0") return NetworkStatus.ApiLimitExceeded;
}
if (code == 429) return NetworkStatus.ApiLimitExceeded;
}
if (code >= 500) return NetworkStatus.ServerError;
if (code >= 400) return NetworkStatus.ClientError;
return NetworkStatus.NoConnection;
}
catch (HttpRequestException)
{
return NetworkStatus.NoConnection;
}
catch
{
return NetworkStatus.NoConnection;
}
}
// Release Notes from GitHub API
public async Task<string> GetReleaseNotesAsync(string version)
{
try
{
// Build GitHub API URL of the release by tag name
// From https://github.com/user/repo
// To https://api.github.com/repos/user/repo/releases/tags/{version}
var apiUrlBase = RepoUrl.Replace("https://github.com/", "https://api.github.com/repos/");
// Try without 'v' prefix (e.g: 1.0.1)
var url = $"{apiUrlBase}/releases/tags/{version}";
var response = await _httpClient.GetAsync(url);
// If url not found, try with 'v' prefix (e.g: v1.0.1)
if (response.StatusCode == HttpStatusCode.NotFound)
{
url = $"{apiUrlBase}/releases/tags/v{version}";
+2 -2
View File
@@ -2,7 +2,7 @@ using System;
using System.Diagnostics.CodeAnalysis;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using CheckHash.ViewModels;
using CommunityToolkit.Mvvm.ComponentModel;
namespace CheckHash;
@@ -29,6 +29,6 @@ public class ViewLocator : IDataTemplate
public bool Match(object? data)
{
return data is ViewModelBase;
return data is ObservableObject;
}
}
+35 -3
View File
@@ -12,12 +12,31 @@ public partial class AboutViewModel : ObservableObject
public AboutViewModel()
{
UpdateDocuments();
LocalizationService.Instance.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "Item[]") Localization = new LocalizationProxy(LocalizationService.Instance);
if (e.PropertyName == "Item[]")
{
Localization = new LocalizationProxy(LocalizationService.Instance);
UpdateDocuments();
}
};
}
private void UpdateDocuments()
{
Documents.Clear();
const string baseUrl = "https://github.com/poli0981/HashTool/blob/main";
Documents.Add(new DocumentItem(Localization["Doc_PrivacyPolicy"], $"{baseUrl}/docs/PrivacyPolicy.md"));
Documents.Add(new DocumentItem(Localization["Doc_ToS"], $"{baseUrl}/docs/ToS.md"));
Documents.Add(new DocumentItem(Localization["Doc_EULA"], $"{baseUrl}/docs/EULA.md"));
Documents.Add(new DocumentItem(Localization["Doc_Disclaimer"], $"{baseUrl}/docs/DISCLAIMER.md"));
Documents.Add(new DocumentItem(Localization["Doc_Readme"], $"{baseUrl}/README.md"));
Documents.Add(new DocumentItem(Localization["Doc_Changelog"], $"{baseUrl}/CHANGELOG.md"));
Documents.Add(new DocumentItem(Localization["Doc_Credit"], $"{baseUrl}/ACKNOWLEDGEMENTS.md"));
}
// Basic Info
public string AppName => "Hash Tool";
public string Version => UpdateService.Instance.CurrentVersion;
@@ -25,12 +44,24 @@ public partial class AboutViewModel : ObservableObject
public string GitHubProfile => "https://github.com/poli0981";
public string Copyright => $"© 2026 {AuthorName}. All rights reserved.";
// Documents
public ObservableCollection<DocumentItem> Documents { get; } = new();
// Credits 3rd party libraries
public ObservableCollection<LibraryItem> Libraries { get; } = new()
{
new LibraryItem("Avalonia UI version 11.3.11", "MIT License", "https://avaloniaui.net/"),
new LibraryItem("Avalonia.Controls.ColorPicker version 11.3.11", "MIT License",
"https://github.com/AvaloniaUI/Avalonia"),
new LibraryItem("Avalonia.Controls.DataGrid version 11.3.11", "MIT License",
"https://github.com/AvaloniaUI/Avalonia"),
new LibraryItem("Avalonia.Desktop version 11.3.11", "MIT License", "https://github.com/AvaloniaUI/Avalonia"),
new LibraryItem("Avalonia.Fonts.Inter version 11.3.11", "MIT License / SIL OFL 1.1",
"https://github.com/AvaloniaUI/Avalonia"),
new LibraryItem("Avalonia.Themes.Fluent version 11.3.11", "MIT License",
"https://github.com/AvaloniaUI/Avalonia"),
new LibraryItem("Blake3.NET version 2.2.0",
"Copyright (c) Alexandre Mutel. All rights reserved.\nLicensed under the BSD " +
"Copyright (c) Alexandre Mutel. All rights reserved.\nLicensed under the BSD-" +
"2-Clause License.", "https://github.com/xoofx/Blake3.NET"),
new LibraryItem("CommunityToolkit.Mvvm Ver 8.2.1", "MIT License", "https://github.com/CommunityToolkit/dotnet"),
new LibraryItem("Material.Icons.Avalonia Ver 2.4.1", "MIT License",
@@ -47,4 +78,5 @@ public partial class AboutViewModel : ObservableObject
}
}
public record LibraryItem(string Name, string License, string Url);
public record LibraryItem(string Name, string License, string Url);
public record DocumentItem(string Name, string Url);
+323 -236
View File
@@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Avalonia.Collections;
using System.Diagnostics;
using System.IO;
using System.Linq;
@@ -9,201 +7,59 @@ using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using CheckHash.Models;
using CheckHash.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace CheckHash.ViewModels;
public partial class CheckHashViewModel : ObservableObject, IDisposable
public partial class CheckHashViewModel : FileListViewModelBase
{
private const long MaxHashFileSize = 1024 * 1024; // 1MB
private const long MaxHashFileSize = AppConstants.OneMB; // 1MB
private readonly HashService _hashService = new();
[ObservableProperty] private HashType _globalAlgorithm = HashType.SHA256;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(VerifyAllCommand))]
[NotifyCanExecuteChangedFor(nameof(AddFilesToCheckCommand))]
[NotifyCanExecuteChangedFor(nameof(ClearListCommand))]
[NotifyCanExecuteChangedFor(nameof(RemoveFileCommand))]
private bool _isChecking;
[ObservableProperty] private bool _isChecking;
[ObservableProperty] private LocalizationProxy _localization = new(LocalizationService.Instance);
[ObservableProperty] private double _progressMax = 100;
[ObservableProperty] private double _progressValue;
public CheckHashViewModel()
{
Prefs.ForceCancelRequested += OnForceCancelRequested;
LocalizationService.Instance.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "Item[]")
{
Localization = new LocalizationProxy(LocalizationService.Instance);
OnPropertyChanged(nameof(TotalFilesText));
}
};
}
private LocalizationService L => LocalizationService.Instance;
private ConfigurationService ConfigService => ConfigurationService.Instance;
private PreferencesService Prefs => PreferencesService.Instance;
private LoggerService Logger => LoggerService.Instance;
public AvaloniaList<FileItem> Files { get; } = new();
public ObservableCollection<HashType> AlgorithmList { get; } = new(Enum.GetValues<HashType>());
public string TotalFilesText => string.Format(L["Lbl_TotalFiles"], Files.Count);
private bool CanModifyList => !IsChecking;
protected override bool IsGlobalBusy => IsChecking;
private bool CanVerify => Files.Count > 0 && !IsChecking;
public void Dispose()
partial void OnIsCheckingChanged(bool value)
{
Prefs.ForceCancelRequested -= OnForceCancelRequested;
foreach (var file in Files) file.Cts?.Dispose();
NotifyCommands();
}
private void OnForceCancelRequested(object? sender, EventArgs e)
protected override void NotifyCommands()
{
Logger.Log("Force Cancel requested by user (Check Hash).", LogLevel.Warning);
foreach (var file in Files) file.Cts?.Cancel();
}
[RelayCommand(CanExecute = nameof(CanModifyList))]
private void ClearList()
{
foreach (var file in Files)
{
file.Cts?.Cancel();
file.Cts?.Dispose();
}
Files.Clear();
ProgressValue = 0;
OnPropertyChanged(nameof(TotalFilesText));
VerifyAllCommand.NotifyCanExecuteChanged();
Logger.Log("Cleared check list.");
CancelAllCommand.NotifyCanExecuteChanged();
// Base commands
AddFilesCommand.NotifyCanExecuteChanged();
AddFolderCommand.NotifyCanExecuteChanged();
ClearListCommand.NotifyCanExecuteChanged();
RemoveFileCommand.NotifyCanExecuteChanged();
ClearFailedCommand.NotifyCanExecuteChanged();
BrowseHashFileCommand.NotifyCanExecuteChanged();
}
[RelayCommand(CanExecute = nameof(CanVerify))]
private async Task VerifyAll()
protected override IEnumerable<FileItem> GetFailedItems()
{
Logger.Log("Starting batch verification...");
IsChecking = true;
ProgressMax = Files.Count;
ProgressValue = 0;
var queue = Files.ToList();
var counters = new int[2];
using var cts = new CancellationTokenSource();
var progressTask = Task.Run(async () =>
{
try
{
while (!cts.Token.IsCancellationRequested)
{
await Task.Delay(100, cts.Token);
var current = counters[0];
await Dispatcher.UIThread.InvokeAsync(() => ProgressValue = current);
if (current >= queue.Count) break;
}
}
catch (OperationCanceledException) { }
});
var statusCancelled = L["Status_Cancelled"];
try
{
await Parallel.ForEachAsync(queue, new ParallelOptions
{
MaxDegreeOfParallelism = Environment.ProcessorCount
}, async (file, ct) =>
{
await VerifyItemLogic(file);
Interlocked.Increment(ref counters[0]);
if (file.Status == statusCancelled)
{
Interlocked.Increment(ref counters[1]);
}
});
}
finally
{
cts.Cancel();
}
try
{
await progressTask;
}
catch
{
// Ignore cancellation/tasks errors
}
ProgressValue = counters[0];
IsChecking = false;
var cancelled = counters[1];
var match = Files.Count(f => f.IsMatch == true);
var failCount = Files.Count(f => f.IsMatch == false);
Logger.Log($"Batch verification finished. Match: {match}, Mismatch/Error: {failCount}, Cancelled: {cancelled}");
if (cancelled > 0)
{
var msg = L["Msg_TaskCancelled_Content"];
Logger.Log(msg, LogLevel.Warning);
await MessageBoxHelper.ShowAsync(L["Msg_TaskCancelled_Title"], msg);
}
else
{
await MessageBoxHelper.ShowAsync(L["Msg_Result_Title"],
string.Format(L["Msg_CheckResult"], Files.Count, match, failCount, cancelled));
}
return Files.Where(f => f.IsMatch != true);
}
[RelayCommand(CanExecute = nameof(CanModifyList))]
private async Task AddFilesToCheck(Window window)
{
try
{
Logger.Log("Opening file picker for Check Hash...");
var result = await window.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
AllowMultiple = true,
Title = L["Dialog_SelectCheckFiles"]
});
var paths = result.Select(x => x.Path.LocalPath);
await AddFilesAsync(paths);
}
catch (Exception ex)
{
Logger.Log($"Error adding files: {ex.Message}", LogLevel.Error);
await MessageBoxHelper.ShowAsync(L["Msg_Error"], ex.Message);
}
}
public async Task AddFilesAsync(IEnumerable<string> filePaths)
public override async Task AddFilesFromPaths(IEnumerable<string> filePaths)
{
if (IsChecking) return;
IsChecking = true;
try
{
var existingPaths = new HashSet<string>(Files.Select(f => f.FilePath));
await Task.Run(async () =>
{
var config = await ConfigService.LoadAsync();
@@ -247,10 +103,10 @@ public partial class CheckHashViewModel : ObservableObject, IDisposable
var sourcePath = Path.Combine(dir, Path.GetFileNameWithoutExtension(path));
result.SourcePath = sourcePath;
if (File.Exists(sourcePath))
var sourceInfo = new FileInfo(sourcePath);
if (sourceInfo.Exists)
{
result.SourceExists = true;
var sourceInfo = new FileInfo(sourcePath);
result.SourceInfo = sourceInfo;
if (config.IsFileSizeLimitEnabled && sourceInfo.Length > limitBytes)
@@ -261,7 +117,7 @@ public partial class CheckHashViewModel : ObservableObject, IDisposable
}
}
result.HashContent = await ReadHashFromFile(path);
result.HashContent = await ReadHashFromFileAsync(path);
}
}
}
@@ -275,6 +131,7 @@ public partial class CheckHashViewModel : ObservableObject, IDisposable
var newItems = new List<FileItem>();
var skippedFiles = new List<string>();
var batchSeen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var result in results)
{
@@ -319,31 +176,35 @@ public partial class CheckHashViewModel : ObservableObject, IDisposable
if (result.SourceExists && result.SourceInfo != null)
{
item.FileSize = FileItem.FormatSize(result.SourceInfo.Length);
item.RawSizeBytes = result.SourceInfo.Length;
}
else
{
item.IsMatch = false;
}
if (ExistingPaths.Contains(item.FilePath)) continue;
if (!batchSeen.Add(item.FilePath)) continue;
newItems.Add(item);
existingPaths.Add(item.FilePath);
Logger.Log($"Added check item (from hash file): {item.FileName}");
}
else
{
if (!existingPaths.Contains(path) && result.Info != null)
if (!ExistingPaths.Contains(path) && result.Info != null)
{
if (!batchSeen.Add(path)) continue;
var item = new FileItem
{
FileName = fileName,
FilePath = path,
RawSizeBytes = result.Info.Length,
FileSize = FileItem.FormatSize(result.Info.Length),
Status = L["Status_Waiting"],
ExpectedHash = ""
};
newItems.Add(item);
existingPaths.Add(path);
Logger.Log($"Added check item: {fileName}");
}
}
@@ -353,7 +214,7 @@ public partial class CheckHashViewModel : ObservableObject, IDisposable
{
await RunOnUIAsync(() =>
{
Files.AddRange(newItems);
AddItemsToAll(newItems);
return Task.CompletedTask;
});
}
@@ -366,7 +227,7 @@ public partial class CheckHashViewModel : ObservableObject, IDisposable
var summaryMsg = string.Format(L["Msg_FileSizeLimitExceeded_Summary"], skippedFiles.Count,
config.FileSizeLimitValue, config.FileSizeLimitUnit, fileList);
await RunOnUIAsync(async () => await MessageBoxHelper.ShowAsync(L["Msg_Error"], summaryMsg));
await RunOnUIAsync(async () => await MessageBoxHelper.ShowAsync(L["Msg_Error"], summaryMsg, MessageBoxIcon.Error));
}
});
@@ -383,25 +244,227 @@ public partial class CheckHashViewModel : ObservableObject, IDisposable
}
}
private async Task RunOnUIAsync(Func<Task> action)
[RelayCommand(CanExecute = nameof(CanVerify))]
private async Task VerifyAllAsync()
{
if (Application.Current == null)
Logger.Log("Starting batch verification...");
IsChecking = true;
ProgressMax = Files.Count;
ProgressValue = 0;
RemainingTime = L["Msg_TimeUnknown"];
// Reset Stats
ProcessedCount = 0;
SuccessCount = 0;
FailCount = 0;
CancelledCount = 0;
SpeedText = "";
UpdateStatsText();
var queue = Files.ToList();
var processedCounter = 0;
var cancelled = 0;
var match = 0;
var mismatch = 0;
long totalBytesRead = 0;
long totalBytesWritten = 0;
long lastBytesRead = 0;
long lastBytesWritten = 0;
var lastSpeedUpdate = DateTime.UtcNow;
var showSpeed = (await ConfigService.LoadAsync()).ShowReadWriteSpeed;
var startTime = DateTime.UtcNow;
// Reset items
foreach (var item in queue)
{
await action();
return;
item.Status = L["Status_Waiting"];
item.ProcessingState = FileStatus.Ready;
item.IsMatch = null;
item.IsCancelled = false;
item.ProcessDuration = "";
}
_batchCts = new CancellationTokenSource();
using var progressCts = new CancellationTokenSource();
var progressTask = Task.Run(async () =>
{
try
{
while (!progressCts.Token.IsCancellationRequested)
{
await Task.Delay(250, progressCts.Token);
var current = processedCounter;
var elapsed = (DateTime.UtcNow - startTime).TotalSeconds;
var rate = current / elapsed;
var remainingCount = queue.Count - current;
var eta = rate > 0 ? TimeSpan.FromSeconds(remainingCount / rate) : TimeSpan.Zero;
var etaStr = current > 0 && current < queue.Count
? string.Format(L["Msg_EstimatedTime"], $"{(int)eta.TotalHours}:{eta.Minutes:D2}:{eta.Seconds:D2}")
: L["Msg_TimeUnknown"];
// Speed Calculation
if (showSpeed)
{
var now = DateTime.UtcNow;
var currentTotalRead = Interlocked.Read(ref totalBytesRead);
var currentTotalWrite = Interlocked.Read(ref totalBytesWritten);
var diffRead = currentTotalRead - lastBytesRead;
var diffWrite = currentTotalWrite - lastBytesWritten;
var timeDiff = (now - lastSpeedUpdate).TotalSeconds;
if (timeDiff > 0.5) // Update every 0.5s
{
var readBytesPerSec = diffRead / timeDiff;
var writeBytesPerSec = diffWrite / timeDiff;
await Dispatcher.UIThread.InvokeAsync(() =>
UpdateSpeedText(readBytesPerSec, writeBytesPerSec), DispatcherPriority.Background);
lastBytesRead = currentTotalRead;
lastBytesWritten = currentTotalWrite;
lastSpeedUpdate = now;
}
}
await Dispatcher.UIThread.InvokeAsync(() =>
{
ProgressValue = current;
RemainingTime = etaStr;
ProcessedCount = current;
SuccessCount = match;
FailCount = mismatch;
CancelledCount = cancelled;
UpdateStatsText();
}, DispatcherPriority.Background);
if (current >= queue.Count) break;
}
}
catch (OperationCanceledException)
{
}
});
var statusCancelled = L["Status_Cancelled"];
try
{
await Dispatcher.UIThread.InvokeAsync(action);
var strategyService = new ProcessingStrategyService();
var batches = strategyService.GetProcessingBatches(queue, f => f.RawSizeBytes);
Logger.Log($"Starting processing with 3 streams. Small: {batches[0].Count}, Medium: {batches[1].Count}, Large: {batches[2].Count}");
Action<long>? progressCallback = null;
if (showSpeed)
{
progressCallback = (bytes) => Interlocked.Add(ref totalBytesRead, bytes);
}
var tasks = new List<Task>();
foreach (var batch in batches)
{
if (batch.Count == 0) continue;
tasks.Add(Task.Run(async () =>
{
foreach (var file in batch)
{
if (_batchCts?.Token.IsCancellationRequested == true) break;
var algo = file.HasSpecificAlgorithm ? file.SelectedAlgorithm : GlobalAlgorithm;
var bufferSize = strategyService.GetBufferSize(file.RawSizeBytes, algo);
await VerifyItemLogicAsync(file, bufferSize, progressCallback);
Interlocked.Increment(ref processedCounter);
if (file.IsMatch == true) Interlocked.Increment(ref match);
else if (file.IsMatch == false) Interlocked.Increment(ref mismatch);
if (file.Status == statusCancelled)
{
Interlocked.Increment(ref cancelled);
}
}
}, _batchCts?.Token ?? CancellationToken.None));
}
await Task.WhenAll(tasks);
}
catch (OperationCanceledException)
{
Logger.Log("Batch verification cancelled.");
}
finally
{
progressCts.Cancel();
_batchCts?.Dispose();
_batchCts = null;
}
var cancelledStatus = L["Status_Cancelled"];
await Dispatcher.UIThread.InvokeAsync(() =>
{
foreach (var item in queue)
{
if (item.ProcessingState == FileStatus.Ready)
{
item.Status = cancelledStatus;
item.ProcessingState = FileStatus.Cancelled;
item.IsCancelled = true;
cancelled++;
processedCounter++;
}
}
}, DispatcherPriority.Background);
try
{
await progressTask;
}
catch
{
await action();
// Ignore cancellation/tasks errors
}
ProgressValue = processedCounter;
RemainingTime = "";
IsChecking = false;
ProcessedCount = processedCounter;
SuccessCount = match;
FailCount = mismatch;
CancelledCount = cancelled;
UpdateStatsText();
SpeedText = "";
var totalDuration = DateTime.UtcNow - startTime;
var durationStr = $"{(int)totalDuration.TotalHours}:{totalDuration.Minutes:D2}:{totalDuration.Seconds:D2}";
Logger.Log($"Batch verification finished in {durationStr}. Match: {match}, Mismatch/Error: {mismatch}, Cancelled: {cancelled}");
if (cancelled > 0)
{
var msg = L["Msg_TaskCancelled_Content"];
msg += $"\n{string.Format(L["Msg_TaskDuration"], durationStr)}";
Logger.Log(msg, LogLevel.Warning);
await MessageBoxHelper.ShowAsync(L["Msg_TaskCancelled_Title"], msg, MessageBoxIcon.Warning);
}
else
{
var icon = mismatch > 0 ? MessageBoxIcon.Warning : MessageBoxIcon.Success;
var resultMsg = string.Format(L["Msg_CheckResult"], Files.Count, match, mismatch, cancelled);
resultMsg += $"\n{string.Format(L["Msg_TaskDuration"], durationStr)}";
await MessageBoxHelper.ShowAsync(L["Msg_Result_Title"], resultMsg, icon);
}
}
private async Task<string> ReadHashFromFile(string path)
private async Task<string> ReadHashFromFileAsync(string path)
{
try
{
@@ -411,6 +474,7 @@ public partial class CheckHashViewModel : ObservableObject, IDisposable
Logger.Log($"Hash file too large (>{MaxHashFileSize / 1024}KB): {path}", LogLevel.Warning);
return "";
}
var regex = HashRegex();
var content = await File.ReadAllTextAsync(path);
@@ -422,54 +486,55 @@ public partial class CheckHashViewModel : ObservableObject, IDisposable
{
return "";
}
}
[GeneratedRegex(@"[a-fA-F0-9]{32,128}")]
[GeneratedRegex(@"[a-fA-F0-9]{8,128}")]
private static partial Regex HashRegex();
[RelayCommand(CanExecute = nameof(CanModifyList))]
private void RemoveFile(FileItem item)
{
item.Cts?.Cancel();
if (Files.Contains(item))
{
Files.Remove(item);
item.IsDeleted = true;
OnPropertyChanged(nameof(TotalFilesText));
VerifyAllCommand.NotifyCanExecuteChanged();
Logger.Log($"Removed check item: {item.FileName}");
}
}
[RelayCommand]
private async Task VerifySingle(FileItem item)
private async Task VerifySingleAsync(FileItem item)
{
if (IsChecking && !item.IsProcessing) return;
if (item.IsProcessing)
{
item.Cts?.Cancel();
return;
}
await VerifyItemLogic(item);
try
{
IsChecking = true;
item.Status = L["Status_Waiting"];
item.IsMatch = null;
item.IsCancelled = false;
await VerifyItemLogicAsync(item);
}
finally
{
IsChecking = false;
}
}
private async Task VerifyItemLogic(FileItem file)
private async Task VerifyItemLogicAsync(FileItem file, int? bufferSize = null,
Action<long>? progressCallback = null)
{
await Dispatcher.UIThread.InvokeAsync(() =>
{
file.IsProcessing = true;
file.ProcessingState = FileStatus.Processing;
file.IsMatch = null;
file.ProcessDuration = "";
file.Status = L["Status_Waiting"];
});
}, DispatcherPriority.Background);
file.Cts = new CancellationTokenSource();
if (Prefs.IsFileTimeoutEnabled) file.Cts.CancelAfter(TimeSpan.FromSeconds(Prefs.FileTimeoutSeconds));
await Task.Run(async () =>
{
var result = await VerifyFileInternalAsync(file, file.Cts.Token);
var result = await VerifyFileInternalAsync(file, file.Cts.Token, bufferSize, progressCallback);
await Dispatcher.UIThread.InvokeAsync(() =>
{
@@ -479,20 +544,22 @@ private async Task VerifyItemLogic(FileItem file)
file.IsMatch = result.IsMatch;
file.ProcessDuration = result.Duration;
file.IsProcessing = false;
if (file.IsCancelled)
file.ProcessingState = FileStatus.Cancelled;
else if (result.IsMatch == true)
file.ProcessingState = FileStatus.Success;
else
file.ProcessingState = FileStatus.Failure;
file.Cts?.Dispose();
file.Cts = null;
});
}, DispatcherPriority.Background);
});
}
private record struct VerificationResult(
string Status,
bool? IsMatch,
string Duration,
string? NewExpectedHash = null
);
private async Task<VerificationResult> VerifyFileInternalAsync(FileItem file, CancellationToken ct)
private async Task<VerificationResult> VerifyFileInternalAsync(FileItem file, CancellationToken ct,
int? bufferSize = null, Action<long>? progressCallback = null)
{
var sw = Stopwatch.StartNew();
var result = new VerificationResult
@@ -502,7 +569,7 @@ private async Task VerifyItemLogic(FileItem file)
IsMatch = false
};
Logger.Log($"Verifying {file.FileName}...");
// Logger.Log($"Verifying {file.FileName}...");
try
{
@@ -523,7 +590,7 @@ private async Task VerifyItemLogic(FileItem file)
if (File.Exists(sidecarPath))
{
var hash = await ReadHashFromFile(sidecarPath);
var hash = await ReadHashFromFileAsync(sidecarPath);
if (!string.IsNullOrWhiteSpace(hash))
{
expectedHash = hash;
@@ -542,7 +609,14 @@ private async Task VerifyItemLogic(FileItem file)
else
{
var algoToCheck = file.HasSpecificAlgorithm ? file.SelectedAlgorithm : GlobalAlgorithm;
var actualHash = await _hashService.ComputeHashAsync(file.FilePath, algoToCheck, ct);
if (algoToCheck.IsInsecure())
{
LoggerService.Instance.Log($"Weak algorithm used for verification: {algoToCheck}",
LogLevel.Warning);
}
var actualHash =
await _hashService.ComputeHashAsync(file.FilePath, algoToCheck, ct, bufferSize, progressCallback);
if (string.Equals(actualHash, expectedHash.Trim(), StringComparison.OrdinalIgnoreCase))
{
@@ -564,6 +638,7 @@ private async Task VerifyItemLogic(FileItem file)
{
result.Status = L["Status_Cancelled"];
result.IsMatch = null;
await Dispatcher.UIThread.InvokeAsync(() => file.IsCancelled = true, DispatcherPriority.Background);
Logger.Log($"Verification cancelled: {file.FileName}", LogLevel.Warning);
}
catch (Exception ex)
@@ -584,28 +659,13 @@ private async Task VerifyItemLogic(FileItem file)
return result;
}
private enum FilePreparationStatus
private bool CanBrowseHashFile(FileItem item)
{
Success,
FileTooLarge,
SourceTooLarge
return !IsChecking;
}
private sealed class FilePreparationResult
{
public required string Path { get; init; }
public FilePreparationStatus Status { get; set; } = FilePreparationStatus.Success;
public FileInfo? Info { get; set; }
public bool IsHashFile { get; set; }
public HashType DetectedAlgo { get; set; }
public string SourcePath { get; set; } = "";
public bool SourceExists { get; set; }
public FileInfo? SourceInfo { get; set; }
public string HashContent { get; set; } = "";
}
[RelayCommand]
private async Task BrowseHashFile(FileItem item)
[RelayCommand(CanExecute = nameof(CanBrowseHashFile))]
private async Task BrowseHashFileAsync(FileItem item)
{
var window =
Application.Current?.ApplicationLifetime is
@@ -628,21 +688,48 @@ private async Task VerifyItemLogic(FileItem file)
if (!hashFileName.Contains(item.FileName, StringComparison.OrdinalIgnoreCase))
{
await MessageBoxHelper.ShowAsync(L["Msg_WrongHashFile"],
string.Format(L["Msg_WrongHashFileContent"], item.FileName, hashFileName));
string.Format(L["Msg_WrongHashFileContent"], item.FileName, hashFileName), MessageBoxIcon.Warning);
return;
}
try
{
item.ExpectedHash = await ReadHashFromFile(hashFilePath);
item.ExpectedHash = await ReadHashFromFileAsync(hashFilePath);
item.Status = L["Status_HashFileLoaded"];
Logger.Log($"Loaded hash file for {item.FileName}");
}
catch (Exception ex)
{
await MessageBoxHelper.ShowAsync(L["Msg_Error"], L["Msg_ReadHashError"]);
await MessageBoxHelper.ShowAsync(L["Msg_Error"], L["Msg_ReadHashError"], MessageBoxIcon.Error);
Logger.Log($"Error reading hash file: {ex.Message}", LogLevel.Error);
}
}
}
private record struct VerificationResult(
string Status,
bool? IsMatch,
string Duration,
string? NewExpectedHash = null
);
private enum FilePreparationStatus
{
Success,
FileTooLarge,
SourceTooLarge
}
private sealed class FilePreparationResult
{
public required string Path { get; init; }
public FilePreparationStatus Status { get; set; } = FilePreparationStatus.Success;
public FileInfo? Info { get; set; }
public bool IsHashFile { get; set; }
public HashType DetectedAlgo { get; set; }
public string SourcePath { get; set; } = "";
public bool SourceExists { get; set; }
public FileInfo? SourceInfo { get; set; }
public string HashContent { get; set; } = "";
}
}
+292 -138
View File
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using Avalonia.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
@@ -14,83 +12,55 @@ using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using CheckHash.Models;
using CheckHash.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace CheckHash.ViewModels;
public partial class CreateHashViewModel : ObservableObject, IDisposable
public partial class CreateHashViewModel : FileListViewModelBase
{
private readonly HashService _hashService = new();
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ComputeAllCommand))]
[NotifyCanExecuteChangedFor(nameof(AddFilesCommand))]
[NotifyCanExecuteChangedFor(nameof(ClearListCommand))]
[NotifyCanExecuteChangedFor(nameof(CompressFilesCommand))]
private bool _isComputing;
[ObservableProperty] private bool _isComputing;
[ObservableProperty] private LocalizationProxy _localization = new(LocalizationService.Instance);
[ObservableProperty] private HashType _selectedAlgorithm = HashType.SHA256;
public CreateHashViewModel()
{
Prefs.ForceCancelRequested += OnForceCancelRequested;
LocalizationService.Instance.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "Item[]")
{
Localization = new LocalizationProxy(LocalizationService.Instance);
OnPropertyChanged(nameof(TotalFilesText));
}
};
}
private LocalizationService L => LocalizationService.Instance;
private ConfigurationService ConfigService => ConfigurationService.Instance;
private PreferencesService Prefs => PreferencesService.Instance;
private LoggerService Logger => LoggerService.Instance;
public string TotalFilesText => string.Format(L["Lbl_TotalFiles"], Files.Count);
public AvaloniaList<FileItem> Files { get; } = new();
public ObservableCollection<HashType> AlgorithmList { get; } = new(Enum.GetValues<HashType>());
protected override bool IsGlobalBusy => IsComputing;
private bool CanComputeAll => Files.Count > 0 && !IsComputing;
private bool CanModifyList => !IsComputing;
private bool CanCompress => Files.Count > 0 && !IsComputing;
public void Dispose()
partial void OnIsComputingChanged(bool value)
{
Prefs.ForceCancelRequested -= OnForceCancelRequested;
foreach (var file in Files) file.Cts?.Dispose();
NotifyCommands();
}
private void OnForceCancelRequested(object? sender, EventArgs e)
protected override void NotifyCommands()
{
Logger.Log("Force Cancel requested by user.", LogLevel.Warning);
foreach (var file in Files) file.Cts?.Cancel();
ComputeAllCommand.NotifyCanExecuteChanged();
CancelAllCommand.NotifyCanExecuteChanged();
CompressFilesCommand.NotifyCanExecuteChanged();
// Base commands
AddFilesCommand.NotifyCanExecuteChanged();
AddFolderCommand.NotifyCanExecuteChanged();
ClearListCommand.NotifyCanExecuteChanged();
RemoveFileCommand.NotifyCanExecuteChanged();
ClearHashCommand.NotifyCanExecuteChanged();
ClearAllHashesCommand.NotifyCanExecuteChanged();
ClearFailedCommand.NotifyCanExecuteChanged();
CopyToClipboardCommand.NotifyCanExecuteChanged();
SaveHashFileCommand.NotifyCanExecuteChanged();
}
[RelayCommand(CanExecute = nameof(CanModifyList))]
private async Task AddFiles(Window window)
protected override IEnumerable<FileItem> GetFailedItems()
{
Logger.Log("Opening file picker for Create Hash...");
var files = await window.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
AllowMultiple = true,
Title = L["Dialog_SelectFiles"]
});
if (files.Count == 0) return;
var paths = files.Select(x => x.Path.LocalPath);
await AddFilesFromPaths(paths);
return Files.Where(f => string.IsNullOrEmpty(f.ResultHash));
}
public async Task AddFilesFromPaths(IEnumerable<string> filePaths)
public override async Task AddFilesFromPaths(IEnumerable<string> filePaths)
{
var config = await ConfigService.LoadAsync();
long limitBytes = 0;
@@ -99,6 +69,7 @@ public partial class CreateHashViewModel : ObservableObject, IDisposable
var existingPaths = new HashSet<string>(Files.Select(f => f.FilePath));
IsComputing = true;
var selectedAlgo = SelectedAlgorithm;
try
{
await Task.Run(async () =>
@@ -117,32 +88,34 @@ public partial class CreateHashViewModel : ObservableObject, IDisposable
var results = new FileItem?[inputs.Length];
var skippedFiles = new ConcurrentQueue<string>();
Parallel.For(0, inputs.Length, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, i =>
{
var path = inputs[i];
var info = new FileInfo(path);
var len = info.Length;
var fileName = Path.GetFileName(path);
if (config.IsFileSizeLimitEnabled && len > limitBytes)
Parallel.For(0, inputs.Length,
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, i =>
{
var msg = string.Format(L["Msg_FileSizeLimitExceeded"], fileName, config.FileSizeLimitValue,
config.FileSizeLimitUnit);
Logger.Log(msg, LogLevel.Warning);
skippedFiles.Enqueue(fileName);
return;
}
var path = inputs[i];
var info = new FileInfo(path);
var len = info.Length;
var fileName = Path.GetFileName(path);
var item = new FileItem
{
FileName = fileName,
FilePath = path,
FileSize = FileItem.FormatSize(len),
SelectedAlgorithm = HashType.SHA256
};
results[i] = item;
Logger.Log($"Added file: {fileName}");
});
if (config.IsFileSizeLimitEnabled && len > limitBytes)
{
var msg = string.Format(L["Msg_FileSizeLimitExceeded"], fileName, config.FileSizeLimitValue,
config.FileSizeLimitUnit);
Logger.Log(msg, LogLevel.Warning);
skippedFiles.Enqueue(fileName);
return;
}
var item = new FileItem
{
FileName = fileName,
FilePath = path,
FileSize = FileItem.FormatSize(len),
RawSizeBytes = len,
SelectedAlgorithm = selectedAlgo
};
results[i] = item;
Logger.Log($"Added file: {fileName}");
});
var newItems = new List<FileItem>(inputs.Length);
foreach (var res in results)
@@ -151,10 +124,7 @@ public partial class CreateHashViewModel : ObservableObject, IDisposable
}
if (newItems.Count > 0)
await Dispatcher.UIThread.InvokeAsync(() =>
{
Files.AddRange(newItems);
});
await Dispatcher.UIThread.InvokeAsync(() => { AddItemsToAll(newItems); });
if (!skippedFiles.IsEmpty)
{
@@ -165,7 +135,7 @@ public partial class CreateHashViewModel : ObservableObject, IDisposable
config.FileSizeLimitValue, config.FileSizeLimitUnit, fileList);
await Dispatcher.UIThread.InvokeAsync(async () =>
await MessageBoxHelper.ShowAsync(L["Msg_Error"], summaryMsg));
await MessageBoxHelper.ShowAsync(L["Msg_Error"], summaryMsg, MessageBoxIcon.Error));
}
});
}
@@ -207,7 +177,8 @@ public partial class CreateHashViewModel : ObservableObject, IDisposable
await Task.Run(async () =>
{
await using var fs = new FileStream(zipPath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, useAsync: true);
await using var fs = new FileStream(zipPath, FileMode.Create, FileAccess.Write, FileShare.None,
4096, useAsync: true);
await using var archive = new ZipArchive(fs, ZipArchiveMode.Create);
foreach (var item in filesToCompress)
if (!string.IsNullOrEmpty(item.ResultHash))
@@ -230,65 +201,232 @@ public partial class CreateHashViewModel : ObservableObject, IDisposable
Logger.Log($"Compression failed: {ex.Message}", LogLevel.Error);
}
}
[RelayCommand(CanExecute = nameof(CanModifyList))]
private void ClearList()
{
foreach (var file in Files)
{
file.Cts?.Cancel();
file.Cts?.Dispose();
file.IsDeleted = true;
}
Files.Clear();
OnPropertyChanged(nameof(TotalFilesText));
ComputeAllCommand.NotifyCanExecuteChanged();
Logger.Log("Cleared file list.");
}
[RelayCommand(CanExecute = nameof(CanComputeAll))]
private async Task ComputeAll()
{
Logger.Log("Starting batch computation...");
IsComputing = true;
ProgressMax = Files.Count;
ProgressValue = 0;
RemainingTime = L["Msg_TimeUnknown"];
// Reset Stats
ProcessedCount = 0;
SuccessCount = 0;
FailCount = 0;
CancelledCount = 0;
SpeedText = "";
UpdateStatsText();
var success = 0;
var fail = 0;
var cancelled = 0;
var processedCounter = 0;
long totalBytesRead = 0;
long totalBytesWritten = 0;
long lastBytesRead = 0;
long lastBytesWritten = 0;
var lastSpeedUpdate = DateTime.UtcNow;
var showSpeed = (await ConfigService.LoadAsync()).ShowReadWriteSpeed;
var queue = Files.ToList();
var startTime = DateTime.UtcNow;
var statusDone = L["Status_Done"];
var statusCancelled = L["Status_Cancelled"];
await Parallel.ForEachAsync(queue, new ParallelOptions
// Reset items
foreach (var item in queue)
{
MaxDegreeOfParallelism = Environment.ProcessorCount
}, async (file, ct) =>
item.ResultHash = "";
item.Status = L["Status_Computing"];
item.ProcessingState = FileStatus.Ready;
item.IsMatch = null;
item.IsCancelled = false;
item.ProcessDuration = "";
}
_batchCts = new CancellationTokenSource();
using var progressCts = new CancellationTokenSource();
var progressTask = Task.Run(async () =>
{
if (file.IsDeleted) return;
try
{
while (!progressCts.Token.IsCancellationRequested)
{
await Task.Delay(250, progressCts.Token);
var current = processedCounter;
await ProcessItemAsync(file);
var elapsed = (DateTime.UtcNow - startTime).TotalSeconds;
var rate = current / elapsed;
var remainingCount = queue.Count - current;
var eta = rate > 0 ? TimeSpan.FromSeconds(remainingCount / rate) : TimeSpan.Zero;
var etaStr = current > 0 && current < queue.Count
? string.Format(L["Msg_EstimatedTime"], $"{(int)eta.TotalHours}:{eta.Minutes:D2}:{eta.Seconds:D2}")
: L["Msg_TimeUnknown"];
if (file.Status == statusDone) Interlocked.Increment(ref success);
else if (file.Status == statusCancelled) Interlocked.Increment(ref cancelled);
else Interlocked.Increment(ref fail);
// Speed Calculation
if (showSpeed)
{
var now = DateTime.UtcNow;
var currentTotalRead = Interlocked.Read(ref totalBytesRead);
var currentTotalWrite = Interlocked.Read(ref totalBytesWritten);
var diffRead = currentTotalRead - lastBytesRead;
var diffWrite = currentTotalWrite - lastBytesWritten;
var timeDiff = (now - lastSpeedUpdate).TotalSeconds;
if (timeDiff > 0.5) // Update every 0.5s to avoid jitter
{
var readBytesPerSec = diffRead / timeDiff;
var writeBytesPerSec = diffWrite / timeDiff;
await Dispatcher.UIThread.InvokeAsync(() =>
UpdateSpeedText(readBytesPerSec, writeBytesPerSec));
lastBytesRead = currentTotalRead;
lastBytesWritten = currentTotalWrite;
lastSpeedUpdate = now;
}
}
await Dispatcher.UIThread.InvokeAsync(() =>
{
ProgressValue = current;
RemainingTime = etaStr;
ProcessedCount = current;
SuccessCount = success;
FailCount = fail;
CancelledCount = cancelled;
UpdateStatsText();
});
if (current >= queue.Count) break;
}
}
catch (OperationCanceledException)
{
}
});
IsComputing = false;
Logger.Log($"Batch finished. Success: {success}, Failed: {fail}, Cancelled: {cancelled}");
try
{
var strategyService = new ProcessingStrategyService();
var batches = strategyService.GetProcessingBatches(queue, f => f.RawSizeBytes);
Logger.Log($"Starting processing with 3 streams. Small: {batches[0].Count}, Medium: {batches[1].Count}, Large: {batches[2].Count}");
if (cancelled > 0)
{
var msg = L["Msg_TaskCancelled_Content"];
Logger.Log(msg, LogLevel.Warning);
await MessageBoxHelper.ShowAsync(L["Msg_TaskCancelled_Title"], msg);
Action<long>? progressCallback = null;
if (showSpeed)
{
progressCallback = (bytes) => Interlocked.Add(ref totalBytesRead, bytes);
}
var tasks = new List<Task>();
foreach (var batch in batches)
{
if (batch.Count == 0) continue;
tasks.Add(Task.Run(async () =>
{
foreach (var file in batch)
{
if (_batchCts?.Token.IsCancellationRequested == true) break;
if (file.IsDeleted)
{
Interlocked.Increment(ref processedCounter);
continue;
}
var bufferSize = strategyService.GetBufferSize(file.RawSizeBytes, file.SelectedAlgorithm);
await ProcessItemAsync(file, bufferSize, progressCallback);
Interlocked.Increment(ref processedCounter);
if (file.Status == statusDone) Interlocked.Increment(ref success);
else if (file.Status == statusCancelled) Interlocked.Increment(ref cancelled);
else Interlocked.Increment(ref fail);
}
}, _batchCts?.Token ?? CancellationToken.None));
}
await Task.WhenAll(tasks);
}
else
catch (OperationCanceledException)
{
await MessageBoxHelper.ShowAsync(L["Msg_Result_Title"],
string.Format(L["Msg_Result_Content"], success, fail));
Logger.Log("Batch computation cancelled.");
}
finally
{
progressCts.Cancel();
_batchCts?.Dispose();
_batchCts = null;
}
var cancelledStatus = L["Status_Cancelled"];
await Dispatcher.UIThread.InvokeAsync(() =>
{
foreach (var item in queue)
{
if (item.ProcessingState == FileStatus.Ready)
{
item.Status = cancelledStatus;
item.ProcessingState = FileStatus.Cancelled;
item.IsCancelled = true;
cancelled++;
processedCounter++;
}
}
});
try
{
await progressTask;
}
catch
{
// Ignore cancellation/tasks errors
}
ProgressValue = processedCounter;
RemainingTime = "";
IsComputing = false;
ProcessedCount = processedCounter;
SuccessCount = success;
FailCount = fail;
CancelledCount = cancelled;
UpdateStatsText();
SpeedText = "";
await Task.Run(() =>
{
GC.Collect();
GC.WaitForPendingFinalizers();
});
var totalDuration = DateTime.UtcNow - startTime;
var durationStr = $"{(int)totalDuration.TotalHours}:{totalDuration.Minutes:D2}:{totalDuration.Seconds:D2}";
Logger.Log($"Batch finished in {durationStr}. Success: {success}, Failed: {fail}, Cancelled: {cancelled}");
var icon = (fail > 0 || cancelled > 0) ? MessageBoxIcon.Warning : MessageBoxIcon.Success;
var resultMsg = string.Format(L["Msg_Result_Content"], success, fail, cancelled);
resultMsg += $"\n{string.Format(L["Msg_TaskDuration"], durationStr)}";
await MessageBoxHelper.ShowAsync(L["Msg_Result_Title"], resultMsg, icon);
}
[RelayCommand]
private bool CanSaveHashFile(FileItem? item)
{
return !IsComputing && item != null && !string.IsNullOrEmpty(item.ResultHash);
}
[RelayCommand(CanExecute = nameof(CanSaveHashFile))]
private async Task SaveHashFile(FileItem item)
{
if (string.IsNullOrEmpty(item.ResultHash)) return;
@@ -319,8 +457,13 @@ public partial class CreateHashViewModel : ObservableObject, IDisposable
}
}
[RelayCommand]
private async Task CopyToClipboard(string hash)
private bool CanCopyToClipboard(string? hash)
{
return !IsComputing && !string.IsNullOrEmpty(hash);
}
[RelayCommand(CanExecute = nameof(CanCopyToClipboard))]
private async Task CopyToClipboard(string? hash)
{
if (string.IsNullOrEmpty(hash)) return;
@@ -338,11 +481,12 @@ public partial class CreateHashViewModel : ObservableObject, IDisposable
}
}
private async Task ProcessItemAsync(FileItem item)
private async Task ProcessItemAsync(FileItem item, int? bufferSize = null, Action<long>? progressCallback = null)
{
await Dispatcher.UIThread.InvokeAsync(() =>
{
item.IsProcessing = true;
item.ProcessingState = FileStatus.Processing;
item.Status = string.Format(L["Status_Processing"], item.SelectedAlgorithm);
item.ProcessDuration = "";
});
@@ -353,24 +497,36 @@ public partial class CreateHashViewModel : ObservableObject, IDisposable
var stopwatch = Stopwatch.StartNew();
Logger.Log($"Computing hash for {item.FileName} ({item.SelectedAlgorithm})...");
if (item.SelectedAlgorithm.IsInsecure())
{
LoggerService.Instance.Log($"Weak algorithm selected: {item.SelectedAlgorithm}", LogLevel.Warning);
}
string? resultHash = null;
string status = "";
try
{
resultHash = await _hashService.ComputeHashAsync(item.FilePath, item.SelectedAlgorithm, item.Cts.Token);
resultHash = await _hashService.ComputeHashAsync(item.FilePath, item.SelectedAlgorithm, item.Cts.Token,
bufferSize, progressCallback);
status = L["Status_Done"];
await Dispatcher.UIThread.InvokeAsync(() => item.ProcessingState = FileStatus.Success);
Logger.Log($"Computed {item.FileName}: {resultHash}", LogLevel.Success);
}
catch (OperationCanceledException)
{
status = L["Status_Cancelled"];
await Dispatcher.UIThread.InvokeAsync(() =>
{
item.IsCancelled = true;
item.ProcessingState = FileStatus.Cancelled;
});
Logger.Log($"Cancelled computation for {item.FileName}", LogLevel.Warning);
}
catch (Exception ex)
{
status = string.Format(L["Status_Error"], ex.Message);
await Dispatcher.UIThread.InvokeAsync(() => item.ProcessingState = FileStatus.Failure);
Logger.Log($"Error computing {item.FileName}: {ex.Message}", LogLevel.Error);
}
finally
@@ -396,27 +552,25 @@ public partial class CreateHashViewModel : ObservableObject, IDisposable
[RelayCommand]
private async Task ComputeSingle(FileItem item)
{
if (IsComputing && !item.IsProcessing) return;
if (item.IsProcessing)
{
item.Cts?.Cancel();
return;
}
await ProcessItemAsync(item);
}
[RelayCommand]
private void RemoveFile(FileItem item)
{
item.Cts?.Cancel();
item.Cts?.Dispose();
item.IsDeleted = true;
if (Files.Contains(item))
try
{
Files.Remove(item);
OnPropertyChanged(nameof(TotalFilesText));
ComputeAllCommand.NotifyCanExecuteChanged();
Logger.Log($"Removed file: {item.FileName}");
IsComputing = true;
item.ResultHash = "";
item.Status = L["Status_Computing"];
item.ProcessingState = FileStatus.Ready;
item.IsCancelled = false;
await ProcessItemAsync(item);
}
finally
{
IsComputing = false;
}
}
}
+1 -1
View File
@@ -59,6 +59,6 @@ public partial class DeveloperViewModel : ObservableObject
// Open the log folder in file explorer
var appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var path = Path.Combine(appData, "HashTool", "log");
UrlHelper.Open(path);
UrlHelper.OpenLocalFolder(path);
}
}
+7 -3
View File
@@ -1,4 +1,5 @@
using System.Threading;
using CheckHash.Models;
using CheckHash.Services;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -12,17 +13,20 @@ public partial class FileItem : ObservableObject
[ObservableProperty] private string _fileName = "";
[ObservableProperty] private string _filePath = "";
[ObservableProperty] private string _fileSize = "";
[ObservableProperty] private bool _hasSpecificAlgorithm;
[ObservableProperty] private bool _isCancelled;
[ObservableProperty] private bool? _isMatch;
[ObservableProperty] private bool _isProcessing;
// Reveal/Hide Expected Hash
[ObservableProperty] private bool _isRevealed;
[ObservableProperty] private string _processDuration = "";
[ObservableProperty] private FileStatus _processingState = FileStatus.Ready;
[ObservableProperty] private long _rawSizeBytes;
[ObservableProperty] private string _resultHash = "";
// Algorithm Select
[ObservableProperty] private HashType _selectedAlgorithm = HashType.SHA256;
[ObservableProperty] private bool _hasSpecificAlgorithm;
[ObservableProperty] private string _status;
public FileItem()
@@ -40,10 +44,10 @@ public partial class FileItem : ObservableObject
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = bytes;
var order = 0;
while (len >= 1024 && order < sizes.Length - 1)
while (len >= AppConstants.OneKB && order < sizes.Length - 1)
{
order++;
len /= 1024;
len /= AppConstants.OneKB;
}
return $"{len:0.##} {sizes[order]}";
+471
View File
@@ -0,0 +1,471 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using CheckHash.Models;
using CheckHash.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace CheckHash.ViewModels;
public abstract partial class FileListViewModelBase : ObservableObject, IDisposable
{
protected CancellationTokenSource? _batchCts;
[ObservableProperty] private int _cancelledCount;
[ObservableProperty] private string _detailedStatsText = "";
[ObservableProperty] private int _failCount;
private CancellationTokenSource? _filterCts;
[ObservableProperty] private LocalizationProxy _localization = new(LocalizationService.Instance);
[ObservableProperty] private int _processedCount;
[ObservableProperty] private double _progressMax = 100;
[ObservableProperty] private string _progressStatsText = "";
[ObservableProperty] private double _progressValue;
[ObservableProperty] private string _remainingTime = "";
[ObservableProperty] private string _searchText = "";
[ObservableProperty] private FileStatus? _selectedFilterStatus = null;
[ObservableProperty] private FileSizeFilter _selectedSizeFilter = FileSizeFilter.All;
[ObservableProperty] private string _speedText = "";
[ObservableProperty] private int _successCount;
protected ImmutableList<FileItem> AllFiles = ImmutableList<FileItem>.Empty;
protected readonly HashSet<string> ExistingPaths = new(StringComparer.OrdinalIgnoreCase);
protected FileListViewModelBase()
{
Prefs.ForceCancelRequested += OnForceCancelRequested;
LocalizationService.Instance.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "Item[]")
{
Localization = new LocalizationProxy(LocalizationService.Instance);
OnPropertyChanged(nameof(TotalFilesText));
UpdateStatsText();
}
};
}
protected LocalizationService L => LocalizationService.Instance;
protected ConfigurationService ConfigService => ConfigurationService.Instance;
protected PreferencesService Prefs => PreferencesService.Instance;
protected LoggerService Logger => LoggerService.Instance;
public bool HasFiles => AllFiles.Count > 0;
public AvaloniaList<FileItem> Files { get; } = new();
public ObservableCollection<HashType> AlgorithmList { get; } = new(Enum.GetValues<HashType>());
public List<FileStatus?> FilterStatusOptions { get; } = new()
{
null,
FileStatus.Ready,
FileStatus.Processing,
FileStatus.Success,
FileStatus.Failure,
FileStatus.Cancelled
};
public List<FileSizeFilter> SizeFilterOptions { get; } = Enum.GetValues<FileSizeFilter>().ToList();
public virtual string TotalFilesText => string.Format(L["Lbl_TotalFiles"], Files.Count);
protected abstract bool IsGlobalBusy { get; }
protected bool CanModifyList => !IsGlobalBusy;
public void Dispose()
{
Prefs.ForceCancelRequested -= OnForceCancelRequested;
foreach (var file in Files) file.Cts?.Dispose();
}
partial void OnSearchTextChanged(string value) => ApplyFilter(true);
partial void OnSelectedFilterStatusChanged(FileStatus? value) => ApplyFilter(true);
partial void OnSelectedSizeFilterChanged(FileSizeFilter value) => ApplyFilter(true);
protected async void ApplyFilter(bool debounce = false)
{
_filterCts?.Cancel();
_filterCts = new CancellationTokenSource();
var token = _filterCts.Token;
if (debounce)
{
try
{
await Task.Delay(300, token); // Debounce
}
catch (OperationCanceledException)
{
return;
}
}
if (token.IsCancellationRequested) return;
// Snapshot (atomic read of immutable list)
var snapshot = AllFiles;
var text = SearchText;
var status = SelectedFilterStatus;
var sizeFilter = SelectedSizeFilter;
await Task.Run(async () =>
{
if (token.IsCancellationRequested) return;
var filtered = snapshot.AsEnumerable();
if (!string.IsNullOrWhiteSpace(text))
{
filtered = filtered.Where(f => f.FileName.Contains(text, StringComparison.OrdinalIgnoreCase));
}
if (status.HasValue)
{
filtered = filtered.Where(f => f.ProcessingState == status.Value);
}
if (sizeFilter != FileSizeFilter.All)
{
long oneMB = AppConstants.OneMB;
long oneHundredMB = 100L * AppConstants.OneMB;
long oneGB = AppConstants.OneGB;
filtered = filtered.Where(f =>
{
var size = f.RawSizeBytes;
return sizeFilter switch
{
FileSizeFilter.Small => size < oneMB,
FileSizeFilter.Medium => size >= oneMB && size < oneHundredMB,
FileSizeFilter.Large => size >= oneHundredMB && size < oneGB,
FileSizeFilter.ExtraLarge => size >= oneGB,
_ => true
};
});
}
var result = filtered.ToList();
if (token.IsCancellationRequested) return;
await RunOnUIAsync(() =>
{
if (token.IsCancellationRequested) return Task.CompletedTask;
Files.Clear();
Files.AddRange(result);
OnPropertyChanged(nameof(TotalFilesText));
NotifyCommands();
return Task.CompletedTask;
});
}, token);
}
protected void AddItemsToAll(IEnumerable<FileItem> items)
{
var list = items.ToList();
if (list.Count == 0) return;
AllFiles = AllFiles.AddRange(list);
foreach (var item in list) ExistingPaths.Add(item.FilePath);
OnPropertyChanged(nameof(HasFiles));
ApplyFilter(false);
}
private void OnForceCancelRequested(object? sender, EventArgs e)
{
Logger.Log($"Force Cancel requested by user ({GetType().Name}).", LogLevel.Warning);
foreach (var file in Files) file.Cts?.Cancel();
}
[RelayCommand(CanExecute = nameof(CanModifyList))]
protected virtual async Task ClearList()
{
foreach (var file in AllFiles)
{
file.Cts?.Cancel();
file.Cts?.Dispose();
}
AllFiles = ImmutableList<FileItem>.Empty;
ExistingPaths.Clear();
Files.Clear();
OnPropertyChanged(nameof(HasFiles));
ProgressValue = 0;
RemainingTime = "";
OnPropertyChanged(nameof(TotalFilesText));
NotifyCommands();
Logger.Log(GetClearLogMessage());
}
protected virtual string GetClearLogMessage() => "Cleared file list.";
[RelayCommand(CanExecute = nameof(CanModifyList))]
protected virtual void RemoveFile(FileItem? item)
{
if (item == null || item.IsProcessing) return;
item.Cts?.Cancel();
item.Cts?.Dispose();
item.IsDeleted = true;
AllFiles = AllFiles.Remove(item);
ExistingPaths.Remove(item.FilePath);
OnPropertyChanged(nameof(HasFiles));
if (Files.Contains(item))
{
Files.Remove(item);
OnPropertyChanged(nameof(TotalFilesText));
NotifyCommands();
Logger.Log($"{GetRemoveLogPrefix()}: {item.FileName}");
}
}
protected virtual string GetRemoveLogPrefix() => "Removed file";
protected bool CanClearHash(FileItem? item)
{
return CanModifyList && item != null && item.ProcessingState != FileStatus.Ready;
}
[RelayCommand(CanExecute = nameof(CanClearHash))]
protected virtual void ClearHash(FileItem? item)
{
if (item == null || item.IsProcessing) return;
ResetItem(item);
Logger.Log($"Cleared hash for {item.FileName}");
NotifyCommands();
}
protected bool CanClearAllHashes()
{
return CanModifyList && Files.Any(f => f.ProcessingState != FileStatus.Ready);
}
[RelayCommand(CanExecute = nameof(CanClearAllHashes))]
protected virtual void ClearAllHashes()
{
var count = 0;
foreach (var item in Files)
{
if (!item.IsProcessing)
{
ResetItem(item);
count++;
}
}
if (count > 0)
{
Logger.Log($"Cleared hashes for {count} files.");
NotifyCommands();
}
}
protected virtual void ResetItem(FileItem item)
{
item.ResultHash = "";
item.Status = L["Lbl_Status_Ready"];
item.ProcessingState = FileStatus.Ready;
item.IsMatch = null;
item.IsCancelled = false;
item.ProcessDuration = "";
}
public void UpdateStatsText()
{
var total = Files.Count;
var percentage = total > 0 ? (double)ProcessedCount / total * 100 : 0;
ProgressStatsText = string.Format(L["Lbl_ProgressStats"], ProcessedCount, total, percentage);
var successPct = total > 0 ? (double)SuccessCount / total * 100 : 0;
var failPct = total > 0 ? (double)FailCount / total * 100 : 0;
var cancelPct = total > 0 ? (double)CancelledCount / total * 100 : 0;
DetailedStatsText = string.Format(L["Lbl_DetailedStats"],
SuccessCount, successPct,
FailCount, failPct,
CancelledCount, cancelPct);
}
public void UpdateSpeedText(double readBytesPerSecond, double writeBytesPerSecond = 0)
{
var readStr = FileItem.FormatSize((long)readBytesPerSecond);
var writeStr = FileItem.FormatSize((long)writeBytesPerSecond);
SpeedText = string.Format(L["Lbl_Speed"], readStr, writeStr);
}
// Abstract methods to hook into subclass specific logic
protected abstract void NotifyCommands();
[RelayCommand(CanExecute = nameof(IsGlobalBusy))]
protected virtual void CancelAll()
{
Logger.Log("Cancel all requested.");
_batchCts?.Cancel();
foreach (var file in Files)
{
if (file.IsProcessing) file.Cts?.Cancel();
}
}
[RelayCommand(CanExecute = nameof(CanModifyList))]
protected virtual async Task AddFiles(Window window)
{
try
{
Logger.Log($"Opening file picker for {GetType().Name}...");
var files = await window.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
AllowMultiple = true,
Title = L["Dialog_SelectFiles"]
});
if (files.Count == 0) return;
var paths = files.Select(x => x.Path.LocalPath);
await AddFilesFromPaths(paths);
}
catch (Exception ex)
{
Logger.Log($"Error adding files: {ex.Message}", LogLevel.Error);
await MessageBoxHelper.ShowAsync(L["Msg_Error"], ex.Message, MessageBoxIcon.Error);
}
}
[RelayCommand(CanExecute = nameof(CanModifyList))]
protected virtual async Task AddFolder(Window window)
{
try
{
Logger.Log($"Opening folder picker for {GetType().Name}...");
var folders = await window.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
{
AllowMultiple = true,
Title = L["Dialog_SelectFolder"]
});
if (folders.Count == 0) return;
if (Prefs.IsMaxFolderCountEnabled && folders.Count > Prefs.MaxFolderCount)
{
await MessageBoxHelper.ShowAsync(L["Msg_Error"],
string.Format(L["Msg_FolderLimit"], Prefs.MaxFolderCount), MessageBoxIcon.Error);
return;
}
var allFiles = new List<string>();
foreach (var folder in folders)
{
try
{
var folderPath = folder.Path.LocalPath;
var files = Directory.GetFiles(folderPath, "*", SearchOption.AllDirectories);
allFiles.AddRange(files);
}
catch (Exception ex)
{
Logger.Log($"Error reading folder {folder.Path.LocalPath}: {ex.Message}", LogLevel.Error);
}
}
if (allFiles.Count == 0)
{
await MessageBoxHelper.ShowAsync(L["Msg_Error"], L["Msg_EmptyFolder"], MessageBoxIcon.Warning);
Logger.Log("Selected folder(s) are empty.", LogLevel.Warning);
return;
}
if (Prefs.IsMaxFileCountEnabled && allFiles.Count > Prefs.MaxFileCount)
{
var skippedCount = allFiles.Count - Prefs.MaxFileCount;
var filesToAdd = allFiles.Take(Prefs.MaxFileCount).ToList();
await AddFilesFromPaths(filesToAdd);
await MessageBoxHelper.ShowAsync(L["Msg_Result_Title"],
string.Format(L["Msg_FileLimit"], filesToAdd.Count, skippedCount), MessageBoxIcon.Warning);
Logger.Log($"Added {filesToAdd.Count} files, skipped {skippedCount} due to limit.");
}
else
{
await AddFilesFromPaths(allFiles);
}
}
catch (Exception ex)
{
Logger.Log($"Error adding folder: {ex.Message}", LogLevel.Error);
await MessageBoxHelper.ShowAsync(L["Msg_Error"], string.Format(L["Msg_OpenFolderError"], ex.Message), MessageBoxIcon.Error);
}
}
public abstract Task AddFilesFromPaths(IEnumerable<string> filePaths);
protected abstract IEnumerable<FileItem> GetFailedItems();
protected virtual string GetClearFailedLogMessage(int count) => $"Cleared {count} failed/cancelled items.";
[RelayCommand(CanExecute = nameof(CanModifyList))]
protected virtual async Task ClearFailedAsync()
{
var failedItems = GetFailedItems().ToList();
if (failedItems.Count == 0) return;
foreach (var item in failedItems)
{
item.Cts?.Cancel();
item.Cts?.Dispose();
item.IsDeleted = true;
Files.Remove(item);
ExistingPaths.Remove(item.FilePath);
}
AllFiles = AllFiles.RemoveRange(failedItems);
OnPropertyChanged(nameof(HasFiles));
OnPropertyChanged(nameof(TotalFilesText));
NotifyCommands();
Logger.Log(GetClearFailedLogMessage(failedItems.Count));
await MessageBoxHelper.ShowAsync(L["Msg_Result_Title"],
string.Format(L["Msg_ClearedFailed"], failedItems.Count), MessageBoxIcon.Information);
}
protected async Task RunOnUIAsync(Func<Task> action)
{
if (Application.Current == null)
{
await action();
return;
}
try
{
if (Dispatcher.UIThread.CheckAccess())
{
await action();
}
else
{
await Dispatcher.UIThread.InvokeAsync(action, DispatcherPriority.Background);
}
}
catch
{
await action();
}
}
}
+3 -1
View File
@@ -165,6 +165,8 @@ public partial class MainWindowViewModel : ObservableObject
[RelayCommand]
private void ToggleTheme()
{
if (!SettingsVM.CanChangeTheme) return;
if (Theme.CurrentThemeVariant == AppThemeVariant.Dark)
Theme.CurrentThemeVariant = AppThemeVariant.Light;
else
@@ -181,7 +183,7 @@ public partial class MainWindowViewModel : ObservableObject
if (CurrentPage == CreateHashVM)
await CreateHashVM.AddFilesCommand.ExecuteAsync(window);
else if (CurrentPage == CheckHashVM) await CheckHashVM.AddFilesToCheckCommand.ExecuteAsync(window);
else if (CurrentPage == CheckHashVM) await CheckHashVM.AddFilesCommand.ExecuteAsync(window);
}
[RelayCommand]
+194 -22
View File
@@ -1,11 +1,13 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using CheckHash.Models;
using CheckHash.Services;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -15,10 +17,16 @@ namespace CheckHash.ViewModels;
public partial class SettingsViewModel : ObservableObject
{
[DllImport("kernel32.dll")]
private static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);
[DllImport("/usr/lib/libSystem.dylib")]
private static extern void malloc_zone_pressure_relief(IntPtr zone, ulong goal);
// Config Path
[ObservableProperty] private string _configFilePath;
[ObservableProperty] private List<AppThemeStyle> _filteredThemeStyles;
[ObservableProperty] private List<AppThemeStyle> _filteredThemeStyles = new();
[ObservableProperty] private int _forceQuitTimeout;
[ObservableProperty] private bool _isAdminModeEnabled;
@@ -33,6 +41,56 @@ public partial class SettingsViewModel : ObservableObject
[ObservableProperty] private LocalizationProxy _localization = new(LocalizationService.Instance);
[ObservableProperty] private bool _showConfigPath;
[ObservableProperty] private bool _showReadWriteSpeed;
private bool _showLanguageChangeWarning = true;
public LanguageItem SelectedLanguage
{
get => Localization.SelectedLanguage;
set
{
if (value == null || value == Localization.SelectedLanguage) return;
if (value.Code == "auto")
{
Dispatcher.UIThread.InvokeAsync(async () =>
{
if (_showLanguageChangeWarning)
{
var (confirmed, isChecked) = await MessageBoxHelper.ShowConfirmationWithCheckboxAsync(
L["Msg_LanguageChangeTitle"],
L["Msg_LanguageChangeConfirmation"],
L["Msg_DontShowAgain"],
L["Btn_Yes"],
L["Btn_No"],
MessageBoxIcon.Question);
if (!confirmed)
{
OnPropertyChanged(nameof(SelectedLanguage));
return;
}
if (isChecked)
{
_showLanguageChangeWarning = false;
}
}
Localization.SelectedLanguage = value;
OnPropertyChanged(nameof(CanSetLanguageDefault));
await SaveSettingsAsync();
});
}
else
{
Localization.SelectedLanguage = value;
OnPropertyChanged(nameof(CanSetLanguageDefault));
}
}
}
private bool _isInitializing;
public SettingsViewModel()
@@ -41,11 +99,19 @@ public partial class SettingsViewModel : ObservableObject
Theme.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(Theme.CurrentThemeVariant))
{
UpdateFilteredThemes();
}
else if (e.PropertyName == nameof(Theme.IsThemeLocked))
{
OnPropertyChanged(nameof(CanChangeTheme));
}
if (_isInitializing) return;
if (e.PropertyName == nameof(Theme.CurrentThemeVariant))
{
UpdateFilteredThemes();
Logger.Log($"Theme variant changed to {Theme.CurrentThemeVariant}");
}
else if (e.PropertyName == nameof(Theme.CurrentThemeStyle))
@@ -54,7 +120,6 @@ public partial class SettingsViewModel : ObservableObject
}
else if (e.PropertyName == nameof(Theme.IsThemeLocked))
{
OnPropertyChanged(nameof(CanChangeTheme));
_ = SaveSettingsAsync();
Logger.Log($"Theme lock changed: {Theme.IsThemeLocked}");
}
@@ -70,7 +135,9 @@ public partial class SettingsViewModel : ObservableObject
if (e.PropertyName == nameof(LocalizationService.Instance.SelectedLanguage))
{
OnPropertyChanged(nameof(CanSetLanguageDefault));
if (!_isInitializing) Logger.Log($"Language changed to {LocalizationService.Instance.SelectedLanguage.Code}");
OnPropertyChanged(nameof(SelectedLanguage));
if (!_isInitializing)
Logger.Log($"Language changed to {LocalizationService.Instance.SelectedLanguage.Code}");
}
else if (e.PropertyName == "Item[]")
{
@@ -116,20 +183,50 @@ public partial class SettingsViewModel : ObservableObject
}
[RelayCommand]
private async Task ResetAppearance()
private async Task ResetSettings()
{
if (IsSettingsLocked) return;
Font.ResetSettings();
Theme.CurrentThemeStyle = AppThemeStyle.Fluent;
Theme.CurrentThemeVariant = AppThemeVariant.System;
Theme.IsThemeLocked = false;
var defaultConfig = new AppConfig();
Localization.SelectedLanguage = Localization.AvailableLanguages.FirstOrDefault(x => x.Code == "auto") ??
Localization.AvailableLanguages[0];
// Reset Appearance
Font.ResetSettings();
Theme.CurrentThemeStyle = defaultConfig.ThemeStyle;
Theme.CurrentThemeVariant = defaultConfig.ThemeVariant;
Theme.IsThemeLocked = defaultConfig.IsThemeLocked;
// Reset Language
Localization.SelectedLanguage =
Localization.AvailableLanguages.FirstOrDefault(x => x.Code == defaultConfig.LanguageCode) ??
Localization.AvailableLanguages[0];
_showLanguageChangeWarning = defaultConfig.ShowLanguageChangeWarning;
// Reset Developer & Admin Mode
IsDeveloperModeEnabled = defaultConfig.IsDeveloperModeEnabled;
IsAdminModeEnabled = defaultConfig.IsAdminModeEnabled;
// Reset Timeouts & Monitor
ForceQuitTimeout = defaultConfig.ForceQuitTimeout;
ShowReadWriteSpeed = defaultConfig.ShowReadWriteSpeed;
// Reset Preferences
Prefs.IsHashMaskingEnabled = defaultConfig.IsHashMaskingEnabled;
Prefs.IsFileSizeLimitEnabled = defaultConfig.IsFileSizeLimitEnabled;
Prefs.FileSizeLimitValue = defaultConfig.FileSizeLimitValue;
Prefs.FileSizeLimitUnit = defaultConfig.FileSizeLimitUnit;
Prefs.IsFileTimeoutEnabled = defaultConfig.IsFileTimeoutEnabled;
Prefs.FileTimeoutSeconds = defaultConfig.FileTimeoutSeconds;
Prefs.IsMaxFileCountEnabled = defaultConfig.IsMaxFileCountEnabled;
Prefs.MaxFileCount = defaultConfig.MaxFileCount;
Prefs.IsMaxFolderCountEnabled = defaultConfig.IsMaxFolderCountEnabled;
Prefs.MaxFolderCount = defaultConfig.MaxFolderCount;
await SaveSettingsAsync();
Logger.Log("Reset appearance settings to default.", LogLevel.Warning);
Logger.Log("All settings reset to default.", LogLevel.Warning);
}
[RelayCommand]
@@ -175,6 +272,25 @@ public partial class SettingsViewModel : ObservableObject
private async Task SetCurrentLanguageAsDefault()
{
if (IsSettingsLocked) return;
if (_showLanguageChangeWarning)
{
var (confirmed, isChecked) = await MessageBoxHelper.ShowConfirmationWithCheckboxAsync(
L["Msg_LanguageChangeTitle"],
L["Msg_LanguageChangeConfirmation"],
L["Msg_DontShowAgain"],
L["Btn_Yes"],
L["Btn_No"],
MessageBoxIcon.Question);
if (!confirmed) return;
if (isChecked)
{
_showLanguageChangeWarning = false;
}
}
await SaveSettingsAsync();
Logger.Log("Language saved as default.");
}
@@ -184,9 +300,9 @@ public partial class SettingsViewModel : ObservableObject
{
var path = ConfigService.ConfigPath;
if (File.Exists(path))
await MessageBoxHelper.ShowAsync(L["Msg_ConfigCheck"], L["Msg_ConfigExists"].Replace("{0}", path));
await MessageBoxHelper.ShowAsync(L["Msg_ConfigCheck"], L["Msg_ConfigExists"].Replace("{0}", path), MessageBoxIcon.Information);
else
await MessageBoxHelper.ShowAsync(L["Msg_ConfigCheck"], L["Msg_ConfigMissing"]);
await MessageBoxHelper.ShowAsync(L["Msg_ConfigCheck"], L["Msg_ConfigMissing"], MessageBoxIcon.Warning);
}
[RelayCommand]
@@ -201,7 +317,7 @@ public partial class SettingsViewModel : ObservableObject
if (clipboard != null)
{
await clipboard.SetTextAsync(ConfigFilePath);
await MessageBoxHelper.ShowAsync(L["Msg_ConfigCheck"], L["Msg_ConfigCopied"]);
await MessageBoxHelper.ShowAsync(L["Msg_ConfigCheck"], L["Msg_ConfigCopied"], MessageBoxIcon.Success);
Logger.Log("Config path copied to clipboard.");
}
}
@@ -220,7 +336,42 @@ public partial class SettingsViewModel : ObservableObject
{
await SaveSettingsAsync();
Logger.Log($"Admin Mode toggled: {IsAdminModeEnabled}");
if (IsAdminModeEnabled) await MessageBoxHelper.ShowAsync(L["Msg_AdminMode"], L["Msg_AdminRestart"]);
if (IsAdminModeEnabled) await MessageBoxHelper.ShowAsync(L["Msg_AdminMode"], L["Msg_AdminRestart"], MessageBoxIcon.Warning);
}
[RelayCommand]
private void FreeMemory()
{
System.Runtime.GCSettings.LargeObjectHeapCompactionMode = System.Runtime.GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
using var proc = Process.GetCurrentProcess();
SetProcessWorkingSetSize(proc.Handle, -1, -1);
}
catch
{
// Ignore errors during working set trimming
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
try
{
malloc_zone_pressure_relief(IntPtr.Zero, 0);
}
catch
{
// Ignore errors
}
}
Logger.Log(L["Msg_MemoryFreed"], LogLevel.Success);
}
partial void OnForceQuitTimeoutChanged(int value)
@@ -228,6 +379,11 @@ public partial class SettingsViewModel : ObservableObject
if (!_isInitializing) _ = SaveSettingsAsync();
}
partial void OnShowReadWriteSpeedChanged(bool value)
{
if (!_isInitializing) _ = SaveSettingsAsync();
}
partial void OnIsAdminModeEnabledChanged(bool value)
{
if (!_isInitializing) _ = SaveSettingsAsync();
@@ -244,7 +400,12 @@ public partial class SettingsViewModel : ObservableObject
IsDeveloperModeEnabled = config.IsDeveloperModeEnabled;
var lang = Localization.AvailableLanguages.FirstOrDefault(x => x.Code == config.LanguageCode);
if (lang != null) Localization.SelectedLanguage = lang;
if (lang != null)
{
Localization.SelectedLanguage = lang;
OnPropertyChanged(nameof(SelectedLanguage));
OnPropertyChanged(nameof(CanSetLanguageDefault));
}
Theme.CurrentThemeStyle = config.ThemeStyle;
Theme.CurrentThemeVariant = config.ThemeVariant;
@@ -270,8 +431,16 @@ public partial class SettingsViewModel : ObservableObject
Prefs.IsFileTimeoutEnabled = config.IsFileTimeoutEnabled;
Prefs.FileTimeoutSeconds = config.FileTimeoutSeconds;
Prefs.IsMaxFileCountEnabled = config.IsMaxFileCountEnabled;
Prefs.MaxFileCount = config.MaxFileCount;
Prefs.IsMaxFolderCountEnabled = config.IsMaxFolderCountEnabled;
Prefs.MaxFolderCount = config.MaxFolderCount;
IsAdminModeEnabled = config.IsAdminModeEnabled;
ForceQuitTimeout = config.ForceQuitTimeout;
_showLanguageChangeWarning = config.ShowLanguageChangeWarning;
ShowReadWriteSpeed = config.ShowReadWriteSpeed;
Logger.Log("Settings loaded from config.");
}
@@ -295,23 +464,26 @@ public partial class SettingsViewModel : ObservableObject
ThemeStyle = Theme.CurrentThemeStyle,
ThemeVariant = Theme.CurrentThemeVariant,
IsThemeLocked = Theme.IsThemeLocked,
FontFamily = Font.SelectedFont?.Name,
BaseFontSize = Font.BaseFontSize,
UiScale = Font.UiScale,
IsFontLocked = Font.IsLockedFont,
IsAutoFont = Font.IsAutoFont,
IsHashMaskingEnabled = Prefs.IsHashMaskingEnabled,
IsFileSizeLimitEnabled = Prefs.IsFileSizeLimitEnabled,
FileSizeLimitValue = Prefs.FileSizeLimitValue,
FileSizeLimitUnit = Prefs.FileSizeLimitUnit,
IsFileTimeoutEnabled = Prefs.IsFileTimeoutEnabled,
FileTimeoutSeconds = Prefs.FileTimeoutSeconds,
IsMaxFileCountEnabled = Prefs.IsMaxFileCountEnabled,
MaxFileCount = Prefs.MaxFileCount,
IsMaxFolderCountEnabled = Prefs.IsMaxFolderCountEnabled,
MaxFolderCount = Prefs.MaxFolderCount,
IsAdminModeEnabled = IsAdminModeEnabled,
ForceQuitTimeout = ForceQuitTimeout
ForceQuitTimeout = ForceQuitTimeout,
ShowLanguageChangeWarning = _showLanguageChangeWarning,
ShowReadWriteSpeed = ShowReadWriteSpeed
};
await ConfigService.SaveAsync(config);
+68 -9
View File
@@ -87,32 +87,91 @@ public partial class UpdateViewModel : ObservableObject
try
{
var netStatus = await _updateService.CheckConnectivityAsync();
if (netStatus != NetworkStatus.Connected)
{
var errorKey = netStatus switch
{
NetworkStatus.NoConnection => "Error_Network",
NetworkStatus.ServerError => "Error_Server",
NetworkStatus.ClientError => "Error_Client",
NetworkStatus.ApiLimitExceeded => "Error_ApiLimit",
_ => "Msg_Error"
};
var msg = L[errorKey];
Logger.Log($"Network check failed: {netStatus}", LogLevel.Error);
StatusMessage = string.Format(L["Status_CheckError"], msg);
await MessageBoxHelper.ShowAsync(L["Msg_Error"], msg, MessageBoxIcon.Error);
return;
}
var isDev = SelectedChannelIndex == 1;
var updateInfo = await _updateService.CheckForUpdatesAsync(isDev);
if (updateInfo != null)
{
var version = updateInfo.TargetFullRelease.Version;
var versionString = version.ToString();
var isPreRelease = versionString.Contains('-'); // Simple check for pre-release tag
if (isDev)
{
if (!isPreRelease)
{
Logger.Log($"Dev Mode: Update found {versionString} is not a pre-release. Keeping current version.");
StatusMessage = L["Msg_NoPreRelease"];
await MessageBoxHelper.ShowAsync(L["Msg_Result_Title"], L["Msg_NoPreRelease"], MessageBoxIcon.Information);
return;
}
// Pre-release available
IsUpdateAvailable = true;
StatusMessage = L["Status_NewVersion"];
Logger.Log($"New pre-release found: {versionString}", LogLevel.Warning);
var notes = await _updateService.GetReleaseNotesAsync(versionString);
var result = await MessageBoxHelper.ShowConfirmationAsync(L["Title_Disclaimer"],
string.Format(L["Msg_PreReleaseWarning"], versionString, notes), L["Btn_Install"], L["Btn_No"], MessageBoxIcon.Warning);
if (result)
{
await InstallUpdate(updateInfo);
}
return;
}
// Stable Channel
IsUpdateAvailable = true;
StatusMessage = L["Status_NewVersion"];
var version = updateInfo.TargetFullRelease.Version.ToString();
Logger.Log($"New version found: {version}", LogLevel.Success);
Logger.Log($"New version found: {versionString}", LogLevel.Success);
var notes = await _updateService.GetReleaseNotesAsync(version);
var notesStable = await _updateService.GetReleaseNotesAsync(versionString);
var result = await MessageBoxHelper.ShowConfirmationAsync(L["Msg_UpdateTitle"],
string.Format(L["Msg_UpdateContent"], version, notes), L["Btn_Install"], L["Btn_No"]);
var resultStable = await MessageBoxHelper.ShowConfirmationAsync(L["Msg_UpdateTitle"],
string.Format(L["Msg_UpdateContent"], versionString, notesStable), L["Btn_Install"], L["Btn_No"], MessageBoxIcon.Question);
if (result)
if (resultStable)
{
await InstallUpdate(updateInfo);
}
}
else
{
StatusMessage = L["Status_Latest"];
Logger.Log("Application is up to date.");
await MessageBoxHelper.ShowAsync(L["Msg_Result_Title"], L["Msg_NoUpdate"]);
if (isDev)
{
StatusMessage = L["Msg_NoPreRelease"];
Logger.Log("Dev Mode: No pre-release found.");
await MessageBoxHelper.ShowAsync(L["Msg_Result_Title"], L["Msg_NoPreRelease"], MessageBoxIcon.Information);
}
else
{
StatusMessage = L["Status_Latest"];
Logger.Log("Application is up to date.");
await MessageBoxHelper.ShowAsync(L["Msg_Result_Title"], L["Msg_NoUpdate"], MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
-7
View File
@@ -1,7 +0,0 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace CheckHash.ViewModels;
public abstract class ViewModelBase : ObservableObject
{
}
+32 -2
View File
@@ -5,7 +5,8 @@
x:Class="CheckHash.Views.AboutView"
x:DataType="vm:AboutViewModel">
<ScrollViewer Padding="0,0,20,0">
<ScrollViewer Padding="0,0,20,0"
VerticalScrollBarVisibility="Hidden">
<StackPanel Spacing="25">
<TextBlock Text="{Binding Localization[Title_About]}" FontSize="28" FontWeight="Bold" Margin="0,0,0,10" />
@@ -26,6 +27,35 @@
</Grid>
</Border>
<!-- 1.5. DOCUMENTS -->
<Border Background="{DynamicResource PaneBackgroundBrush}" CornerRadius="12" Padding="20"
BorderBrush="{DynamicResource GlassBorderBrush}" BorderThickness="1">
<StackPanel Spacing="15">
<StackPanel Orientation="Horizontal" Spacing="10">
<icons:MaterialIcon Kind="FileDocument" Width="24" Height="24"
Foreground="{DynamicResource SystemAccentColor}" />
<TextBlock Text="{Binding Localization[About_Documents]}" FontSize="18" FontWeight="SemiBold" />
</StackPanel>
<ItemsControl ItemsSource="{Binding Documents}" Margin="34,0,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="*, Auto" Margin="0,0,0,8">
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" FontWeight="SemiBold" />
<Button Grid.Column="1"
Command="{Binding $parent[UserControl].((vm:AboutViewModel)DataContext).OpenUrlCommand}"
CommandParameter="{Binding Url}"
Background="Transparent" Padding="5">
<icons:MaterialIcon Kind="OpenInNew" Width="16" Height="16" Opacity="0.5" />
</Button>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<!-- 2. TECHNOLOGY & AI -->
<Border Background="{DynamicResource PaneBackgroundBrush}" CornerRadius="12" Padding="20"
BorderBrush="{DynamicResource GlassBorderBrush}" BorderThickness="1">
@@ -61,7 +91,7 @@
<StackPanel Orientation="Horizontal" Spacing="15" Margin="34,0,0,0">
<Button Command="{Binding OpenUrlCommand}" CommandParameter="{Binding GitHubProfile}"
Background="Transparent" Padding="5" CornerRadius="8"
ToolTip.Tip="GitHub Profile">
ToolTip.Tip="{Binding Localization[Tip_GitHubProfile]}">
<StackPanel Orientation="Horizontal" Spacing="10">
<icons:MaterialIcon Kind="Github" Width="24" Height="24" />
<TextBlock Text="{Binding AuthorName}" VerticalAlignment="Center" FontWeight="Bold" />
+6
View File
@@ -1,4 +1,5 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace CheckHash.Views;
@@ -8,4 +9,9 @@ public partial class AboutView : UserControl
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
+281
View File
@@ -0,0 +1,281 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:CheckHash.ViewModels"
xmlns:controls="using:CheckHash.Views.Controls"
xmlns:icons="clr-namespace:Material.Icons.Avalonia;assembly=Material.Icons.Avalonia"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="CheckHash.Views.CheckHashView"
x:DataType="vm:CheckHashViewModel">
<Grid RowDefinitions="Auto, Auto, Auto, Auto, *">
<Grid ColumnDefinitions="*, Auto">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Localization[Title_CheckHash]}" FontSize="24" FontWeight="Bold"
Margin="0,0,0,5" />
<!-- Help Text -->
<TextBlock Text="{Binding Localization[Help_CheckHash]}" FontSize="12" Opacity="0.6"
FontStyle="Italic" Margin="0,0,0,15" />
</StackPanel>
<StackPanel Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Right" Spacing="5">
<TextBlock Text="{Binding TotalFilesText}" Opacity="0.7" IsVisible="{Binding !IsChecking}"
HorizontalAlignment="Right" />
<StackPanel IsVisible="{Binding IsChecking}" Orientation="Vertical" HorizontalAlignment="Right">
<TextBlock Text="{Binding ProgressStatsText}" FontWeight="Bold" HorizontalAlignment="Right" />
<TextBlock Text="{Binding DetailedStatsText}" FontSize="11" Opacity="0.8"
HorizontalAlignment="Right" />
<TextBlock Text="{Binding SpeedText}" Foreground="{DynamicResource SystemAccentColor}"
FontWeight="Bold" HorizontalAlignment="Right"
IsVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).SettingsVM.ShowReadWriteSpeed}" />
</StackPanel>
</StackPanel>
</Grid>
<StackPanel Grid.Row="1" Orientation="Horizontal" Spacing="10" Margin="0,0,0,10">
<StackPanel Orientation="Horizontal" Spacing="10" IsEnabled="{Binding !IsChecking}">
<Button Content="{Binding Localization[Btn_AddFiles]}"
Command="{Binding AddFilesCommand}"
CommandParameter="{Binding $parent[Window]}"
ToolTip.Tip="Ctrl+F / Cmd+F" />
<Button Content="{Binding Localization[Btn_AddFolder]}" Command="{Binding AddFolderCommand}"
CommandParameter="{Binding $parent[Window]}" />
<Button Content="{Binding Localization[Btn_Clear]}" Command="{Binding ClearListCommand}"
ToolTip.Tip="Ctrl+Shift+H" />
<Button Content="{Binding Localization[Btn_ClearHashes]}"
Command="{Binding ClearAllHashesCommand}"
IsVisible="{Binding Files.Count}" />
<Button Content="{Binding Localization[Btn_ClearFailed]}"
Command="{Binding ClearFailedCommand}"
IsVisible="{Binding Files.Count}" />
<TextBlock Text="{Binding Localization[Lbl_Sample]}" VerticalAlignment="Center" />
<ComboBox ItemsSource="{Binding AlgorithmList}" SelectedItem="{Binding GlobalAlgorithm}"
Width="150" VerticalAlignment="Center" />
</StackPanel>
<Panel>
<Button Content="{Binding Localization[Btn_CheckAll]}"
Background="{DynamicResource SystemAccentColor}" Foreground="White"
Command="{Binding VerifyAllCommand}"
IsVisible="{Binding !IsChecking}"
ToolTip.Tip="Shift+A" />
<Button Content="{Binding Localization[Btn_Cancel]}"
Background="#FF6060" Foreground="White"
Command="{Binding CancelAllCommand}"
IsVisible="{Binding IsChecking}"
ToolTip.Tip="Esc" />
</Panel>
<TextBlock Text="{Binding RemainingTime}" VerticalAlignment="Center" Margin="10,0,0,0"
IsVisible="{Binding IsChecking}" FontWeight="SemiBold" />
</StackPanel>
<StackPanel Grid.Row="2" Orientation="Horizontal" Spacing="10" Margin="0,0,0,10"
IsVisible="{Binding HasFiles}" IsEnabled="{Binding !IsChecking}">
<TextBox Text="{Binding SearchText, Mode=TwoWay}" Watermark="{Binding Localization[Watermark_Search]}" Width="400"
Classes="DragOver" BorderThickness="0,0,0,1" CornerRadius="0" />
<ComboBox ItemsSource="{Binding FilterStatusOptions}"
SelectedItem="{Binding SelectedFilterStatus, Mode=TwoWay}"
Width="150">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource FileStatusConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox ItemsSource="{Binding SizeFilterOptions}"
SelectedItem="{Binding SelectedSizeFilter, Mode=TwoWay}"
Width="180" PlaceholderText="{Binding Localization[Placeholder_Size]}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource FileSizeFilterConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
<ProgressBar Grid.Row="3" Minimum="0" Maximum="{Binding ProgressMax}" Value="{Binding ProgressValue}"
IsVisible="{Binding IsChecking}" Height="4" Margin="0,0,0,10" />
<StackPanel Grid.Row="4" HorizontalAlignment="Center" VerticalAlignment="Center"
IsVisible="{Binding Files.Count, Converter={StaticResource CountToVisibilityConverter}}"
Opacity="0.5" Spacing="10"
DragDrop.AllowDrop="True" DragDrop.Drop="OnMainDrop"
DragDrop.DragEnter="OnDragEnter" DragDrop.DragLeave="OnDragLeave"
Background="Transparent">
<icons:MaterialIcon Kind="FilePlusOutline" Width="64" Height="64" />
<TextBlock Text="{Binding Localization[EmptyState_DropFiles]}"
FontSize="16" HorizontalAlignment="Center" />
</StackPanel>
<ListBox Grid.Row="4" ItemsSource="{Binding Files}" Background="Transparent"
IsVisible="{Binding Files.Count}"
DragDrop.AllowDrop="True" DragDrop.Drop="OnMainDrop"
DragDrop.DragEnter="OnDragEnter" DragDrop.DragLeave="OnDragLeave">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="#30808080" BorderThickness="0,0,0,1" Padding="5">
<Grid ColumnDefinitions="400, 100, *, 100, 80">
<StackPanel Grid.Column="0" VerticalAlignment="Center" Margin="0,0,10,0"
ToolTip.Tip="{Binding FilePath}">
<controls:HighlightTextBlock Text="{Binding FileName}"
HighlightText="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).SearchText}"
HighlightBrush="{DynamicResource SystemAccentColor}"
TextTrimming="CharacterEllipsis"
FontWeight="Bold" />
<TextBlock Text="{Binding FilePath}" FontSize="10" Opacity="0.6"
TextTrimming="CharacterEllipsis" />
</StackPanel>
<StackPanel Grid.Column="1" VerticalAlignment="Center" Margin="0,0,10,0">
<TextBlock Text="{Binding FileSize}" FontSize="11" Foreground="Gray" />
<TextBlock Text="{Binding ProcessDuration}" FontSize="11"
Foreground="LimeGreen" FontWeight="Bold"
IsVisible="{Binding ProcessDuration, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />
</StackPanel>
<!-- Hash Input/Display -->
<Grid Grid.Column="2" ColumnDefinitions="*, Auto, Auto" Margin="0,0,10,0">
<Panel Grid.Column="0">
<TextBlock VerticalAlignment="Center" FontFamily="Consolas, Monospace"
FontSize="11"
Margin="5,0">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource HashMaskConverter}">
<Binding Path="ExpectedHash" />
<Binding
Path="$parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled" />
<Binding Path="IsRevealed" />
</MultiBinding>
</TextBlock.Text>
<TextBlock.IsVisible>
<MultiBinding Converter="{x:Static BoolConverters.And}">
<Binding
Path="$parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled" />
<Binding Path="!IsRevealed" />
</MultiBinding>
</TextBlock.IsVisible>
</TextBlock>
<!-- TextBox Real (Mask OFF/ Revealed) -->
<TextBox Name="HashInputBox"
Text="{Binding ExpectedHash, Mode=TwoWay}"
Watermark="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Watermark_PasteDrop]}"
VerticalAlignment="Center" FontFamily="Consolas, Monospace"
FontSize="11"
DragDrop.AllowDrop="True" DragDrop.Drop="OnHashFileDrop"
DragDrop.DragEnter="OnDragEnter" DragDrop.DragLeave="OnDragLeave">
<TextBox.IsVisible>
<MultiBinding Converter="{x:Static BoolConverters.Or}">
<Binding
Path="!$parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled" />
<Binding Path="IsRevealed" />
</MultiBinding>
</TextBox.IsVisible>
</TextBox>
</Panel>
<ToggleButton Grid.Column="1"
IsChecked="{Binding IsRevealed}"
Background="Transparent" Padding="4" Margin="2,0,0,0"
IsVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_HashVisibility]}">
<ToolTip.Tip>
<Panel>
<TextBlock
Text="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_ShowHash]}"
IsVisible="{Binding !IsRevealed}" />
<TextBlock
Text="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_HideHash]}"
IsVisible="{Binding IsRevealed}" />
</Panel>
</ToolTip.Tip>
<Panel>
<icons:MaterialIcon Kind="EyeOutline" Width="16" Height="16"
IsVisible="{Binding !IsRevealed}" />
<icons:MaterialIcon Kind="EyeOffOutline" Width="16" Height="16"
IsVisible="{Binding IsRevealed}" />
</Panel>
</ToggleButton>
<Button Grid.Column="2" Margin="2,0,0,0" Padding="5" Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).BrowseHashFileCommand}"
CommandParameter="{Binding .}"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_BrowseHash]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_BrowseHash]}">
<icons:MaterialIcon Kind="FileFind" Width="18" Height="18"
Foreground="#00bfff" />
</Button>
</Grid>
<TextBlock Grid.Column="3" Text="{Binding Status}"
FontWeight="Bold" VerticalAlignment="Center" TextWrapping="Wrap"
FontSize="12" />
<StackPanel Grid.Column="4" Orientation="Horizontal" Spacing="5"
HorizontalAlignment="Right">
<Button Padding="5" Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).VerifySingleCommand}"
CommandParameter="{Binding .}"
AutomationProperties.Name="Verify or Stop">
<Button.IsEnabled>
<MultiBinding
Converter="{StaticResource ComputeButtonEnabledConverter}">
<Binding Path="IsCancelled" />
<Binding Path="IsProcessing" />
<Binding
Path="$parent[ListBox].((vm:CheckHashViewModel)DataContext).IsChecking" />
</MultiBinding>
</Button.IsEnabled>
<ToolTip.Tip>
<Panel>
<TextBlock
Text="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_Verify]}"
IsVisible="{Binding !IsProcessing}" />
<TextBlock
Text="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_Stop]}"
IsVisible="{Binding IsProcessing}" />
</Panel>
</ToolTip.Tip>
<Panel>
<icons:MaterialIcon Kind="PlayCircleOutline" Width="18" Height="18"
Foreground="LimeGreen"
IsVisible="{Binding !IsProcessing}" />
<icons:MaterialIcon Kind="StopCircleOutline" Width="18" Height="18"
Foreground="Orange"
IsVisible="{Binding IsProcessing}" />
</Panel>
</Button>
<Button Padding="5"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_ClearHash]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_ClearHash]}"
Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).ClearHashCommand}"
CommandParameter="{Binding .}">
<icons:MaterialIcon Kind="Eraser" Width="18" Height="18"
Foreground="#FFD700" />
</Button>
<Button Padding="5"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_RemoveFile]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_RemoveFile]}"
Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).RemoveFileCommand}"
CommandParameter="{Binding .}">
<icons:MaterialIcon Kind="TrashCanOutline" Width="18" Height="18"
Foreground="#FF6060" />
</Button>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
+115
View File
@@ -0,0 +1,115 @@
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using CheckHash.Services;
using CheckHash.ViewModels;
namespace CheckHash.Views;
public partial class CheckHashView : UserControl
{
public CheckHashView()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private LocalizationService L => LocalizationService.Instance;
private void OnDragEnter(object? sender, DragEventArgs e)
{
if (e.Data.Contains(DataFormats.Files) && sender is Control control)
{
control.Classes.Add("DragOver");
}
}
private void OnDragLeave(object? sender, DragEventArgs e)
{
if (sender is Control control)
{
control.Classes.Remove("DragOver");
}
}
private async void OnHashFileDrop(object? sender, DragEventArgs e)
{
if (sender is Control control)
{
control.Classes.Remove("DragOver");
}
if (e.Data.Contains(DataFormats.Files))
{
var files = e.Data.GetFiles()?.ToList();
if (files != null && files.Count > 0)
{
var filePath = files[0].Path.LocalPath;
if (sender is TextBox textBox && textBox.DataContext is FileItem item)
{
var hashFileName = Path.GetFileName(filePath);
if (!hashFileName.Contains(item.FileName, StringComparison.OrdinalIgnoreCase))
{
item.Status = L["Status_DropHashMismatch"];
return;
}
try
{
string content;
using (var reader = new StreamReader(filePath))
{
var buffer = new char[5120]; // 5KB
var readCount = await reader.ReadAsync(buffer, 0, buffer.Length);
content = new string(buffer, 0, readCount);
}
var match = Regex.Match(content, @"[a-fA-F0-9]{32,128}");
if (match.Success)
{
item.ExpectedHash = match.Value;
item.Status = L["Status_DropHashSuccess"];
}
else
{
item.Status = L["Status_DropNoHash"];
}
}
catch
{
item.Status = L["Status_ReadError"];
}
}
}
}
}
private async void OnMainDrop(object? sender, DragEventArgs e)
{
if (sender is Control control)
{
control.Classes.Remove("DragOver");
}
if (e.Data.Contains(DataFormats.Files))
{
var files = e.Data.GetFiles()?.Select(x => x.Path.LocalPath).ToList();
if (files == null || files.Count == 0) return;
if (DataContext is FileListViewModelBase vm)
{
await vm.AddFilesFromPaths(files);
}
}
}
}
+285
View File
@@ -0,0 +1,285 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:CheckHash.ViewModels"
xmlns:controls="using:CheckHash.Views.Controls"
xmlns:icons="clr-namespace:Material.Icons.Avalonia;assembly=Material.Icons.Avalonia"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="CheckHash.Views.CreateHashView"
x:DataType="vm:CreateHashViewModel">
<Grid RowDefinitions="Auto, Auto, Auto, *">
<Grid ColumnDefinitions="*, Auto">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Localization[Title_CreateHash]}" FontSize="24" FontWeight="Bold"
Margin="0,0,0,5" />
<!-- Help Text -->
<TextBlock Text="{Binding Localization[Help_CreateHash]}" FontSize="12" Opacity="0.6"
FontStyle="Italic" Margin="0,0,0,15" />
</StackPanel>
<StackPanel Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Right" Spacing="5">
<TextBlock Text="{Binding TotalFilesText}" Opacity="0.7" IsVisible="{Binding !IsComputing}"
HorizontalAlignment="Right" />
<StackPanel IsVisible="{Binding IsComputing}" Orientation="Vertical"
HorizontalAlignment="Right">
<TextBlock Text="{Binding ProgressStatsText}" FontWeight="Bold" HorizontalAlignment="Right" />
<TextBlock Text="{Binding DetailedStatsText}" FontSize="11" Opacity="0.8"
HorizontalAlignment="Right" />
<TextBlock Text="{Binding SpeedText}" Foreground="{DynamicResource SystemAccentColor}"
FontWeight="Bold" HorizontalAlignment="Right"
IsVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).SettingsVM.ShowReadWriteSpeed}" />
</StackPanel>
</StackPanel>
</Grid>
<StackPanel Grid.Row="1" Orientation="Horizontal" Spacing="10" Margin="0,0,0,15">
<StackPanel Orientation="Horizontal" Spacing="10" IsEnabled="{Binding !IsComputing}">
<Button Content="{Binding Localization[Btn_AddFiles]}" Command="{Binding AddFilesCommand}"
CommandParameter="{Binding $parent[Window]}"
ToolTip.Tip="Ctrl+F / Cmd+F" />
<Button Content="{Binding Localization[Btn_AddFolder]}" Command="{Binding AddFolderCommand}"
CommandParameter="{Binding $parent[Window]}" />
<Button Content="{Binding Localization[Btn_Clear]}" Command="{Binding ClearListCommand}"
ToolTip.Tip="Ctrl+Shift+H" />
<Button Content="{Binding Localization[Btn_ClearHashes]}"
Command="{Binding ClearAllHashesCommand}"
IsVisible="{Binding Files.Count}" />
<Button Content="{Binding Localization[Btn_ClearFailed]}"
Command="{Binding ClearFailedCommand}"
IsVisible="{Binding Files.Count}" />
<Button Content="{Binding Localization[Btn_Compress]}"
Command="{Binding CompressFilesCommand}"
CommandParameter="{Binding $parent[Window]}"
IsEnabled="{Binding Files.Count}"
ToolTip.Tip="Shift+Z" />
</StackPanel>
<Panel>
<Button Content="{Binding Localization[Btn_CalcAll]}"
Background="{DynamicResource SystemAccentColor}" Foreground="White"
Command="{Binding ComputeAllCommand}"
IsVisible="{Binding !IsComputing}"
ToolTip.Tip="Shift+C" />
<Button Content="{Binding Localization[Btn_Cancel]}"
Background="#FF6060" Foreground="White"
Command="{Binding CancelAllCommand}"
IsVisible="{Binding IsComputing}"
ToolTip.Tip="Esc" />
</Panel>
<TextBlock Text="{Binding RemainingTime}" VerticalAlignment="Center" Margin="10,0,0,0"
IsVisible="{Binding IsComputing}" FontWeight="SemiBold" />
</StackPanel>
<StackPanel Grid.Row="2" Orientation="Horizontal" Spacing="10" Margin="0,0,0,10"
IsVisible="{Binding HasFiles}" IsEnabled="{Binding !IsComputing}">
<TextBox Text="{Binding SearchText, Mode=TwoWay}" Watermark="{Binding Localization[Watermark_Search]}" Width="400"
Classes="DragOver" BorderThickness="0,0,0,1" CornerRadius="0" />
<ComboBox ItemsSource="{Binding FilterStatusOptions}"
SelectedItem="{Binding SelectedFilterStatus, Mode=TwoWay}"
Width="150">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource FileStatusConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox ItemsSource="{Binding SizeFilterOptions}"
SelectedItem="{Binding SelectedSizeFilter, Mode=TwoWay}"
Width="180" PlaceholderText="{Binding Localization[Placeholder_Size]}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource FileSizeFilterConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
<ProgressBar Grid.Row="3" Minimum="0" Maximum="{Binding ProgressMax}" Value="{Binding ProgressValue}"
IsVisible="{Binding IsComputing}" Height="4" Margin="0,0,0,10" VerticalAlignment="Top" />
<StackPanel Grid.Row="3" HorizontalAlignment="Center" VerticalAlignment="Center"
IsVisible="{Binding Files.Count, Converter={StaticResource CountToVisibilityConverter}}"
Opacity="0.5" Spacing="10"
DragDrop.AllowDrop="True" DragDrop.Drop="OnMainDrop"
DragDrop.DragEnter="OnDragEnter" DragDrop.DragLeave="OnDragLeave"
Background="Transparent">
<icons:MaterialIcon Kind="FilePlusOutline" Width="64" Height="64" />
<TextBlock Text="{Binding Localization[EmptyState_DropFiles]}"
FontSize="16" HorizontalAlignment="Center" />
</StackPanel>
<ListBox Grid.Row="3" ItemsSource="{Binding Files}" Background="Transparent"
IsVisible="{Binding Files.Count}"
DragDrop.AllowDrop="True" DragDrop.Drop="OnMainDrop"
DragDrop.DragEnter="OnDragEnter" DragDrop.DragLeave="OnDragLeave">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="#30808080" BorderThickness="0,0,0,1" Padding="5">
<Grid ColumnDefinitions="400, 90, 110, *, 40, 80, 100">
<!-- 0: File Name -->
<StackPanel Grid.Column="0" VerticalAlignment="Center" Margin="0,0,10,0"
ToolTip.Tip="{Binding FilePath}">
<controls:HighlightTextBlock Text="{Binding FileName}"
HighlightText="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).SearchText}"
HighlightBrush="{DynamicResource SystemAccentColor}"
TextTrimming="CharacterEllipsis"
FontWeight="Bold" />
<TextBlock Text="{Binding FilePath}" FontSize="10" Opacity="0.6"
TextTrimming="CharacterEllipsis" />
</StackPanel>
<!-- 1: Size & Duration -->
<StackPanel Grid.Column="1" VerticalAlignment="Center" Margin="0,0,10,0">
<TextBlock Text="{Binding FileSize}" FontSize="11" Foreground="Gray" />
<TextBlock Text="{Binding ProcessDuration}" FontSize="11"
Foreground="LimeGreen" FontWeight="Bold"
IsVisible="{Binding ProcessDuration, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />
</StackPanel>
<!-- 2: Algorithm -->
<ComboBox Grid.Column="2"
ItemsSource="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).AlgorithmList}"
SelectedItem="{Binding SelectedAlgorithm}"
VerticalAlignment="Center" Margin="0,0,5,0" Width="110">
<ComboBox.IsEnabled>
<MultiBinding Converter="{StaticResource AlgorithmEnabledConverter}">
<Binding Path="ProcessingState" />
<Binding Path="$parent[ListBox].((vm:CreateHashViewModel)DataContext).IsComputing" />
</MultiBinding>
</ComboBox.IsEnabled>
</ComboBox>
<!-- 3: Hash Result (Eye to Hide/Reveal) -->
<Grid Grid.Column="3" ColumnDefinitions="*, Auto">
<TextBox Grid.Column="0"
IsReadOnly="True" VerticalAlignment="Center"
FontSize="11" FontFamily="Consolas, Monospace"
BorderThickness="0" Background="Transparent"
TextWrapping="NoWrap">
<TextBox.Text>
<MultiBinding Converter="{StaticResource HashMaskConverter}">
<Binding Path="ResultHash" />
<Binding
Path="$parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled" />
<Binding Path="IsRevealed" />
</MultiBinding>
</TextBox.Text>
</TextBox>
<ToggleButton Grid.Column="1"
IsChecked="{Binding IsRevealed}"
Background="Transparent" Padding="4" Margin="2,0,0,0"
IsVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_HashVisibility]}">
<ToolTip.Tip>
<Panel>
<TextBlock
Text="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_ShowHash]}"
IsVisible="{Binding !IsRevealed}" />
<TextBlock
Text="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_HideHash]}"
IsVisible="{Binding IsRevealed}" />
</Panel>
</ToolTip.Tip>
<Panel>
<icons:MaterialIcon Kind="EyeOutline" Width="16" Height="16"
IsVisible="{Binding !IsRevealed}" />
<icons:MaterialIcon Kind="EyeOffOutline" Width="16" Height="16"
IsVisible="{Binding IsRevealed}" />
</Panel>
</ToggleButton>
</Grid>
<!-- 4: Copy Button -->
<Button Grid.Column="4" Padding="5" Background="Transparent" BorderThickness="0"
Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).CopyToClipboardCommand}"
CommandParameter="{Binding ResultHash}"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_CopyHash]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_CopyHash]}"
IsVisible="{Binding ResultHash, Converter={x:Static StringConverters.IsNotNullOrEmpty}}">
<icons:MaterialIcon Kind="ContentCopy" Width="16" Height="16" />
</Button>
<!-- 5: Status -->
<TextBlock Grid.Column="5" Text="{Binding Status}"
VerticalAlignment="Center" Foreground="#00bfff" FontSize="12"
TextWrapping="Wrap" />
<!-- 6: Actions -->
<StackPanel Grid.Column="6" Orientation="Horizontal" Spacing="2"
HorizontalAlignment="Right">
<Button Padding="5"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Dialog_SaveHash]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Dialog_SaveHash]}"
Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).SaveHashFileCommand}"
CommandParameter="{Binding .}">
<icons:MaterialIcon Kind="ContentSave" Width="18" Height="18" />
</Button>
<Button Padding="5" Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).ComputeSingleCommand}"
CommandParameter="{Binding .}"
AutomationProperties.Name="Compute or Stop">
<Button.IsEnabled>
<MultiBinding
Converter="{StaticResource ComputeButtonEnabledConverter}">
<Binding Path="IsCancelled" />
<Binding Path="IsProcessing" />
<Binding
Path="$parent[ListBox].((vm:CreateHashViewModel)DataContext).IsComputing" />
</MultiBinding>
</Button.IsEnabled>
<ToolTip.Tip>
<Panel>
<TextBlock
Text="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_Compute]}"
IsVisible="{Binding !IsProcessing}" />
<TextBlock
Text="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_Stop]}"
IsVisible="{Binding IsProcessing}" />
</Panel>
</ToolTip.Tip>
<Panel>
<icons:MaterialIcon Kind="PlayCircleOutline" Width="18" Height="18"
Foreground="LimeGreen"
IsVisible="{Binding !IsProcessing}" />
<icons:MaterialIcon Kind="StopCircleOutline" Width="18" Height="18"
Foreground="Orange"
IsVisible="{Binding IsProcessing}" />
</Panel>
</Button>
<Button Padding="5"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_ClearHash]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_ClearHash]}"
Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).ClearHashCommand}"
CommandParameter="{Binding .}">
<icons:MaterialIcon Kind="Eraser" Width="18" Height="18"
Foreground="#FFD700" />
</Button>
<Button Padding="5"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_RemoveFile]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_RemoveFile]}"
Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).RemoveFileCommand}"
CommandParameter="{Binding .}">
<icons:MaterialIcon Kind="TrashCanOutline" Width="18" Height="18"
Foreground="#FF6060" />
</Button>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
+60
View File
@@ -0,0 +1,60 @@
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using CheckHash.Services;
using CheckHash.ViewModels;
namespace CheckHash.Views;
public partial class CreateHashView : UserControl
{
public CreateHashView()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void OnDragEnter(object? sender, DragEventArgs e)
{
if (e.Data.Contains(DataFormats.Files) && sender is Control control)
{
control.Classes.Add("DragOver");
}
}
private void OnDragLeave(object? sender, DragEventArgs e)
{
if (sender is Control control)
{
control.Classes.Remove("DragOver");
}
}
private async void OnMainDrop(object? sender, DragEventArgs e)
{
if (sender is Control control)
{
control.Classes.Remove("DragOver");
}
if (e.Data.Contains(DataFormats.Files))
{
var files = e.Data.GetFiles()?.Select(x => x.Path.LocalPath).ToList();
if (files == null || files.Count == 0) return;
if (DataContext is FileListViewModelBase vm)
{
await vm.AddFilesFromPaths(files);
}
}
}
}
+2 -5
View File
@@ -10,12 +10,9 @@
<Border Grid.Row="0" Padding="10" Background="{DynamicResource PaneBackgroundBrush}"
BorderBrush="{DynamicResource GlassBorderBrush}" BorderThickness="0,0,0,1">
<Grid ColumnDefinitions="Auto, *, Auto">
<StackPanel Orientation="Horizontal" Spacing="10">
<StackPanel Grid.Column="0" Orientation="Horizontal" Spacing="10">
<TextBlock Text="{Binding Localization[Dev_Console]}" FontSize="20" FontWeight="Bold"
VerticalAlignment="Center" />
<Border Background="#30808080" CornerRadius="4" Padding="5,2">
<TextBlock Text="{Binding Localization[Dev_Beta]}" FontSize="10" FontWeight="Bold" />
</Border>
</StackPanel>
<StackPanel Grid.Column="2" Orientation="Horizontal" Spacing="10">
@@ -53,7 +50,7 @@
<DataTemplate>
<TextBlock Text="{Binding}"
FontFamily="Consolas, Monospace"
FontSize="12"
FontSize="14"
Foreground="#00FF00"
TextWrapping="Wrap" />
</DataTemplate>
+15
View File
@@ -0,0 +1,15 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="CheckHash.Views.Controls.HighlightTextBlock"
x:Name="Root">
<TextBlock Name="PART_TextBlock"
TextTrimming="{Binding #Root.TextTrimming}"
FontWeight="{Binding #Root.FontWeight}"
FontSize="{Binding #Root.FontSize}"
Foreground="{Binding #Root.Foreground}"
HorizontalAlignment="{Binding #Root.HorizontalAlignment}"
VerticalAlignment="{Binding #Root.VerticalAlignment}" />
</UserControl>
+127
View File
@@ -0,0 +1,127 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using System;
namespace CheckHash.Views.Controls;
public partial class HighlightTextBlock : UserControl
{
public static readonly StyledProperty<string?> TextProperty =
AvaloniaProperty.Register<HighlightTextBlock, string?>(nameof(Text));
public string? Text
{
get => GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public static readonly StyledProperty<string?> HighlightTextProperty =
AvaloniaProperty.Register<HighlightTextBlock, string?>(nameof(HighlightText));
public string? HighlightText
{
get => GetValue(HighlightTextProperty);
set => SetValue(HighlightTextProperty, value);
}
public static readonly StyledProperty<IBrush?> HighlightBrushProperty =
AvaloniaProperty.Register<HighlightTextBlock, IBrush?>(nameof(HighlightBrush));
public IBrush? HighlightBrush
{
get => GetValue(HighlightBrushProperty);
set => SetValue(HighlightBrushProperty, value);
}
public static readonly StyledProperty<TextTrimming> TextTrimmingProperty =
AvaloniaProperty.Register<HighlightTextBlock, TextTrimming>(nameof(TextTrimming));
public TextTrimming TextTrimming
{
get => GetValue(TextTrimmingProperty);
set => SetValue(TextTrimmingProperty, value);
}
private TextBlock? _textBlock;
public HighlightTextBlock()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
_textBlock = this.FindControl<TextBlock>("PART_TextBlock");
UpdateText();
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TextProperty ||
change.Property == HighlightTextProperty ||
change.Property == HighlightBrushProperty)
{
UpdateText();
}
}
private void UpdateText()
{
if (_textBlock == null) return;
_textBlock.Inlines?.Clear();
var text = Text;
var highlight = HighlightText;
if (string.IsNullOrEmpty(text))
{
return;
}
if (string.IsNullOrEmpty(highlight))
{
_textBlock.Inlines?.Add(new Run { Text = text });
return;
}
int index = 0;
while (index < text.Length)
{
int matchIndex = text.IndexOf(highlight, index, StringComparison.OrdinalIgnoreCase);
if (matchIndex == -1)
{
if (index < text.Length)
{
_textBlock.Inlines?.Add(new Run { Text = text.Substring(index) });
}
break;
}
if (matchIndex > index)
{
_textBlock.Inlines?.Add(new Run { Text = text.Substring(index, matchIndex - index) });
}
var matchText = text.Substring(matchIndex, highlight.Length);
_textBlock.Inlines?.Add(new Run
{
Text = matchText,
Foreground = HighlightBrush,
FontWeight = FontWeight.Bold
});
index = matchIndex + highlight.Length;
}
if (index < text.Length)
{
_textBlock.Inlines?.Add(new Run { Text = text.Substring(index) });
}
}
}
+24 -366
View File
@@ -2,13 +2,14 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:CheckHash.ViewModels"
xmlns:views="using:CheckHash.Views"
xmlns:controls="using:CheckHash.Views.Controls"
xmlns:conv="using:CheckHash.Converters"
xmlns:icons="clr-namespace:Material.Icons.Avalonia;assembly=Material.Icons.Avalonia"
x:Class="CheckHash.Views.MainWindow"
x:DataType="vm:MainWindowViewModel"
Icon="/Assets/icon/favicon.ico"
Title="{Binding AppTitleText}"
Width="1280" Height="720"
Width="1600" Height="900"
WindowStartupLocation="CenterScreen"
Background="{DynamicResource AppBackgroundBrush}"
SystemDecorations="Full"
@@ -19,11 +20,6 @@
FontSize="{Binding SettingsVM.Font.BaseFontSize}"
FlowDirection="{Binding L.FlowDirection}">
<Window.Resources>
<conv:HashMaskConverter x:Key="HashMaskConverter" />
<conv:CountToVisibilityConverter x:Key="CountToVisibilityConverter" />
</Window.Resources>
<!-- Key Bindings -->
<Window.KeyBindings>
<KeyBinding Gesture="Shift+A" Command="{Binding HotkeyCheckAllCommand}" />
@@ -36,6 +32,25 @@
</Window.KeyBindings>
<Window.Styles>
<Style Selector="StackPanel.DragOver">
<Setter Property="Background">
<SolidColorBrush Color="{DynamicResource SystemAccentColor}" Opacity="0.2" />
</Setter>
<Setter Property="Opacity" Value="1.0" />
</Style>
<Style Selector="ListBox.DragOver">
<Setter Property="Background">
<SolidColorBrush Color="{DynamicResource SystemAccentColor}" Opacity="0.2" />
</Setter>
</Style>
<Style Selector="TextBox.DragOver">
<Setter Property="Background">
<SolidColorBrush Color="{DynamicResource SystemAccentColor}" Opacity="0.2" />
</Setter>
</Style>
<Style Selector="Button.MenuBtn">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
@@ -92,367 +107,10 @@
<views:DeveloperView />
</DataTemplate>
<DataTemplate DataType="vm:CreateHashViewModel">
<Grid RowDefinitions="Auto, Auto, *">
<Grid ColumnDefinitions="*, Auto">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Localization[Title_CreateHash]}" FontSize="24" FontWeight="Bold"
Margin="0,0,0,5" />
<!-- Help Text -->
<TextBlock Text="{Binding Localization[Help_CreateHash]}" FontSize="12" Opacity="0.6"
FontStyle="Italic" Margin="0,0,0,15" />
</StackPanel>
<TextBlock Grid.Column="1" Text="{Binding TotalFilesText}" VerticalAlignment="Center" Opacity="0.7" />
</Grid>
<StackPanel Grid.Row="1" Orientation="Horizontal" Spacing="10" Margin="0,0,0,15"
IsEnabled="{Binding !IsComputing}">
<Button Content="{Binding Localization[Btn_AddFiles]}" Command="{Binding AddFilesCommand}"
CommandParameter="{Binding $parent[Window]}"
ToolTip.Tip="Ctrl+F / Cmd+F" />
<Button Content="{Binding Localization[Btn_Clear]}" Command="{Binding ClearListCommand}"
ToolTip.Tip="Ctrl+Shift+H" />
<Button Content="{Binding Localization[Btn_Compress]}"
Command="{Binding CompressFilesCommand}"
CommandParameter="{Binding $parent[Window]}"
IsEnabled="{Binding Files.Count}"
ToolTip.Tip="Shift+Z" />
<Button Content="{Binding Localization[Btn_CalcAll]}"
Background="{DynamicResource SystemAccentColor}" Foreground="White"
Command="{Binding ComputeAllCommand}"
ToolTip.Tip="Shift+C" />
</StackPanel>
<StackPanel Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center"
IsVisible="{Binding Files.Count, Converter={StaticResource CountToVisibilityConverter}}"
Opacity="0.5" Spacing="10">
<icons:MaterialIcon Kind="FilePlusOutline" Width="64" Height="64" />
<TextBlock Text="{Binding Localization[EmptyState_DropFiles]}"
FontSize="16" HorizontalAlignment="Center" />
</StackPanel>
<ListBox Grid.Row="2" ItemsSource="{Binding Files}" Background="Transparent"
IsVisible="{Binding Files.Count}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="#30808080" BorderThickness="0,0,0,1" Padding="5">
<Grid ColumnDefinitions="*, 90, 80, 200, 40, 80, 100">
<!-- 0: File Name -->
<StackPanel Grid.Column="0" VerticalAlignment="Center" Margin="0,0,10,0">
<TextBlock Text="{Binding FileName}" FontWeight="Bold"
TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding FilePath}" FontSize="10" Opacity="0.6"
TextTrimming="CharacterEllipsis" />
</StackPanel>
<!-- 1: Size & Duration -->
<StackPanel Grid.Column="1" VerticalAlignment="Center" Margin="0,0,10,0">
<TextBlock Text="{Binding FileSize}" FontSize="11" Foreground="Gray" />
<TextBlock Text="{Binding ProcessDuration}" FontSize="11"
Foreground="LimeGreen" FontWeight="Bold"
IsVisible="{Binding ProcessDuration, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />
</StackPanel>
<!-- 2: Algorithm -->
<ComboBox Grid.Column="2"
ItemsSource="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).AlgorithmList}"
SelectedItem="{Binding SelectedAlgorithm}"
VerticalAlignment="Center" Margin="0,0,5,0" Width="95" />
<!-- 3: Hash Result (Eye to Hide/Reveal) -->
<Grid Grid.Column="3" ColumnDefinitions="*, Auto">
<TextBox Grid.Column="0"
IsReadOnly="True" VerticalAlignment="Center"
FontSize="11" FontFamily="Consolas, Monospace"
BorderThickness="0" Background="Transparent"
TextWrapping="NoWrap">
<TextBox.Text>
<MultiBinding Converter="{StaticResource HashMaskConverter}">
<Binding Path="ResultHash" />
<Binding
Path="$parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled" />
<Binding Path="IsRevealed" />
</MultiBinding>
</TextBox.Text>
</TextBox>
<ToggleButton Grid.Column="1"
IsChecked="{Binding IsRevealed}"
Background="Transparent" Padding="4" Margin="2,0,0,0"
IsVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_HashVisibility]}">
<ToolTip.Tip>
<Panel>
<TextBlock
Text="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_ShowHash]}"
IsVisible="{Binding !IsRevealed}" />
<TextBlock
Text="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_HideHash]}"
IsVisible="{Binding IsRevealed}" />
</Panel>
</ToolTip.Tip>
<Panel>
<icons:MaterialIcon Kind="EyeOutline" Width="16" Height="16"
IsVisible="{Binding !IsRevealed}" />
<icons:MaterialIcon Kind="EyeOffOutline" Width="16" Height="16"
IsVisible="{Binding IsRevealed}" />
</Panel>
</ToggleButton>
</Grid>
<!-- 4: Copy Button -->
<Button Grid.Column="4" Padding="5" Background="Transparent" BorderThickness="0"
Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).CopyToClipboardCommand}"
CommandParameter="{Binding ResultHash}"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_CopyHash]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_CopyHash]}"
IsVisible="{Binding ResultHash, Converter={x:Static StringConverters.IsNotNullOrEmpty}}">
<icons:MaterialIcon Kind="ContentCopy" Width="16" Height="16" />
</Button>
<!-- 5: Status -->
<TextBlock Grid.Column="5" Text="{Binding Status}"
VerticalAlignment="Center" Foreground="#00bfff" FontSize="12"
TextWrapping="Wrap" />
<!-- 6: Actions -->
<StackPanel Grid.Column="6" Orientation="Horizontal" Spacing="2"
HorizontalAlignment="Right">
<Button Padding="5"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Dialog_SaveHash]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Dialog_SaveHash]}"
Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).SaveHashFileCommand}"
CommandParameter="{Binding .}"
IsEnabled="{Binding ResultHash, Converter={x:Static StringConverters.IsNotNullOrEmpty}}">
<icons:MaterialIcon Kind="ContentSave" Width="18" Height="18" />
</Button>
<Button Padding="5" Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).ComputeSingleCommand}"
CommandParameter="{Binding .}"
AutomationProperties.Name="Compute or Stop">
<ToolTip.Tip>
<Panel>
<TextBlock
Text="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_Compute]}"
IsVisible="{Binding !IsProcessing}" />
<TextBlock
Text="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_Stop]}"
IsVisible="{Binding IsProcessing}" />
</Panel>
</ToolTip.Tip>
<Panel>
<icons:MaterialIcon Kind="PlayCircleOutline" Width="18" Height="18"
Foreground="LimeGreen"
IsVisible="{Binding !IsProcessing}" />
<icons:MaterialIcon Kind="StopCircleOutline" Width="18" Height="18"
Foreground="Orange"
IsVisible="{Binding IsProcessing}" />
</Panel>
</Button>
<Button Padding="5"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_RemoveFile]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_RemoveFile]}"
Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).RemoveFileCommand}"
CommandParameter="{Binding .}">
<icons:MaterialIcon Kind="TrashCanOutline" Width="18" Height="18"
Foreground="#FF6060" />
</Button>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
<views:CreateHashView />
</DataTemplate>
<DataTemplate DataType="vm:CheckHashViewModel">
<Grid RowDefinitions="Auto, Auto, Auto, *">
<Grid ColumnDefinitions="*, Auto">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Localization[Title_CheckHash]}" FontSize="24" FontWeight="Bold"
Margin="0,0,0,5" />
<!-- Help Text -->
<TextBlock Text="{Binding Localization[Help_CheckHash]}" FontSize="12" Opacity="0.6"
FontStyle="Italic" Margin="0,0,0,15" />
</StackPanel>
<TextBlock Grid.Column="1" Text="{Binding TotalFilesText}" VerticalAlignment="Center" Opacity="0.7" />
</Grid>
<StackPanel Grid.Row="1" Orientation="Horizontal" Spacing="10" Margin="0,0,0,10"
IsEnabled="{Binding !IsChecking}">
<Button Content="{Binding Localization[Btn_AddFiles]}"
Command="{Binding AddFilesToCheckCommand}"
CommandParameter="{Binding $parent[Window]}"
ToolTip.Tip="Ctrl+F / Cmd+F" />
<Button Content="{Binding Localization[Btn_Clear]}" Command="{Binding ClearListCommand}"
ToolTip.Tip="Ctrl+Shift+H" />
<TextBlock Text="{Binding Localization[Lbl_Sample]}" VerticalAlignment="Center" />
<ComboBox ItemsSource="{Binding AlgorithmList}" SelectedItem="{Binding GlobalAlgorithm}"
Width="150" VerticalAlignment="Center" />
<Button Content="{Binding Localization[Btn_CheckAll]}"
Background="{DynamicResource SystemAccentColor}" Foreground="White"
Command="{Binding VerifyAllCommand}"
ToolTip.Tip="Shift+A" />
</StackPanel>
<ProgressBar Grid.Row="2" Minimum="0" Maximum="{Binding ProgressMax}" Value="{Binding ProgressValue}"
IsVisible="{Binding IsChecking}" Height="4" Margin="0,0,0,10" />
<StackPanel Grid.Row="3" HorizontalAlignment="Center" VerticalAlignment="Center"
IsVisible="{Binding Files.Count, Converter={StaticResource CountToVisibilityConverter}}"
Opacity="0.5" Spacing="10">
<icons:MaterialIcon Kind="FilePlusOutline" Width="64" Height="64" />
<TextBlock Text="{Binding Localization[EmptyState_DropFiles]}"
FontSize="16" HorizontalAlignment="Center" />
</StackPanel>
<ListBox Grid.Row="3" ItemsSource="{Binding Files}" Background="Transparent"
IsVisible="{Binding Files.Count}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="#30808080" BorderThickness="0,0,0,1" Padding="5">
<Grid ColumnDefinitions="*, 100, 250, 100, 80">
<StackPanel Grid.Column="0" VerticalAlignment="Center" Margin="0,0,10,0">
<TextBlock Text="{Binding FileName}" FontWeight="Bold"
TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding FilePath}" FontSize="10" Opacity="0.6"
TextTrimming="CharacterEllipsis" />
</StackPanel>
<StackPanel Grid.Column="1" VerticalAlignment="Center" Margin="0,0,10,0">
<TextBlock Text="{Binding FileSize}" FontSize="11" Foreground="Gray" />
<TextBlock Text="{Binding ProcessDuration}" FontSize="11"
Foreground="LimeGreen" FontWeight="Bold"
IsVisible="{Binding ProcessDuration, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />
</StackPanel>
<!-- Hash Input/Display -->
<Grid Grid.Column="2" ColumnDefinitions="*, Auto, Auto" Margin="0,0,10,0">
<Panel Grid.Column="0">
<TextBlock VerticalAlignment="Center" FontFamily="Consolas, Monospace"
FontSize="11"
Margin="5,0">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource HashMaskConverter}">
<Binding Path="ExpectedHash" />
<Binding
Path="$parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled" />
<Binding Path="IsRevealed" />
</MultiBinding>
</TextBlock.Text>
<TextBlock.IsVisible>
<MultiBinding Converter="{x:Static BoolConverters.And}">
<Binding
Path="$parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled" />
<Binding Path="!IsRevealed" />
</MultiBinding>
</TextBlock.IsVisible>
</TextBlock>
<!-- TextBox Real (Mask OFF/ Revealed) -->
<TextBox Name="HashInputBox"
Text="{Binding ExpectedHash, Mode=TwoWay}"
Watermark="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Watermark_PasteDrop]}"
VerticalAlignment="Center" FontFamily="Consolas, Monospace"
FontSize="11"
DragDrop.AllowDrop="True" DragDrop.Drop="OnHashFileDrop">
<TextBox.IsVisible>
<MultiBinding Converter="{x:Static BoolConverters.Or}">
<Binding
Path="!$parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled" />
<Binding Path="IsRevealed" />
</MultiBinding>
</TextBox.IsVisible>
</TextBox>
</Panel>
<ToggleButton Grid.Column="1"
IsChecked="{Binding IsRevealed}"
Background="Transparent" Padding="4" Margin="2,0,0,0"
IsVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).Prefs.IsHashMaskingEnabled}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_HashVisibility]}">
<ToolTip.Tip>
<Panel>
<TextBlock
Text="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_ShowHash]}"
IsVisible="{Binding !IsRevealed}" />
<TextBlock
Text="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_HideHash]}"
IsVisible="{Binding IsRevealed}" />
</Panel>
</ToolTip.Tip>
<Panel>
<icons:MaterialIcon Kind="EyeOutline" Width="16" Height="16"
IsVisible="{Binding !IsRevealed}" />
<icons:MaterialIcon Kind="EyeOffOutline" Width="16" Height="16"
IsVisible="{Binding IsRevealed}" />
</Panel>
</ToggleButton>
<Button Grid.Column="2" Margin="2,0,0,0" Padding="5" Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).BrowseHashFileCommand}"
CommandParameter="{Binding .}"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_BrowseHash]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_BrowseHash]}">
<icons:MaterialIcon Kind="FileFind" Width="18" Height="18"
Foreground="#00bfff" />
</Button>
</Grid>
<TextBlock Grid.Column="3" Text="{Binding Status}"
FontWeight="Bold" VerticalAlignment="Center" TextWrapping="Wrap"
FontSize="12" />
<StackPanel Grid.Column="4" Orientation="Horizontal" Spacing="5"
HorizontalAlignment="Right">
<Button Padding="5" Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).VerifySingleCommand}"
CommandParameter="{Binding .}"
AutomationProperties.Name="Verify or Stop">
<ToolTip.Tip>
<Panel>
<TextBlock
Text="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_Verify]}"
IsVisible="{Binding !IsProcessing}" />
<TextBlock
Text="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_Stop]}"
IsVisible="{Binding IsProcessing}" />
</Panel>
</ToolTip.Tip>
<Panel>
<icons:MaterialIcon Kind="PlayCircleOutline" Width="18" Height="18"
Foreground="LimeGreen"
IsVisible="{Binding !IsProcessing}" />
<icons:MaterialIcon Kind="StopCircleOutline" Width="18" Height="18"
Foreground="Orange"
IsVisible="{Binding IsProcessing}" />
</Panel>
</Button>
<Button Padding="5"
ToolTip.Tip="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_RemoveFile]}"
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_RemoveFile]}"
Background="Transparent"
Command="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).RemoveFileCommand}"
CommandParameter="{Binding .}">
<icons:MaterialIcon Kind="TrashCanOutline" Width="18" Height="18"
Foreground="#FF6060" />
</Button>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
<views:CheckHashView />
</DataTemplate>
<DataTemplate DataType="vm:UpdateViewModel">
<views:UpdateView />
@@ -473,7 +131,7 @@
<SplitView.Pane>
<Border Background="{DynamicResource PaneBackgroundBrush}"
CornerRadius="12"
Margin="15,40, 5,25"
Margin="15,40, 15,25"
BorderBrush="{DynamicResource GlassBorderBrush}"
BorderThickness="1">
<Grid RowDefinitions="Auto, *, Auto" Margin="0,10">
+4 -56
View File
@@ -2,6 +2,8 @@ using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using CheckHash.Services;
@@ -35,7 +37,8 @@ public partial class MainWindow : Window
L["Msg_ConfirmExit_Title"],
L["Msg_ConfirmExit_Content"],
L["Btn_Yes"],
L["Btn_No"]);
L["Btn_No"],
MessageBoxIcon.Warning);
if (result)
{
@@ -46,59 +49,4 @@ public partial class MainWindow : Window
}
}
}
private async void OnHashFileDrop(object? sender, DragEventArgs e)
{
#pragma warning disable CS0618 // Type or member is obsolete
// Check if dropped data contains files
if (e.Data.Contains(DataFormats.Files))
{
var files = e.Data.GetFiles()?.ToList();
if (files != null && files.Count > 0)
{
var filePath = files[0].Path.LocalPath;
// 2. TextBox, DataContext (FileItem)
if (sender is TextBox textBox && textBox.DataContext is FileItem item)
{
var hashFileName = Path.GetFileName(filePath);
if (!hashFileName.Contains(item.FileName, StringComparison.OrdinalIgnoreCase))
{
item.Status = L["Status_DropHashMismatch"];
return;
}
try
{
// 3. Đọc nội dung file
string content;
using (var reader = new StreamReader(filePath))
{
var buffer = new char[5120]; // 5KB
var readCount = await reader.ReadAsync(buffer, 0, buffer.Length);
content = new string(buffer, 0, readCount);
}
// 4. Lọc lấy mã Hash
var match = Regex.Match(content, @"[a-fA-F0-9]{32,128}");
if (match.Success)
{
// Gán vào TextBox (thông qua ViewModel để trigger Binding)
item.ExpectedHash = match.Value;
item.Status = L["Status_DropHashSuccess"];
}
else
{
item.Status = L["Status_DropNoHash"];
}
}
catch
{
item.Status = L["Status_ReadError"];
}
}
}
}
#pragma warning restore CS0618 // Type or member is obsolete
}
}
+101 -36
View File
@@ -11,7 +11,8 @@
<converters:FontNameConverter x:Key="FontNameConverter" />
</UserControl.Resources>
<ScrollViewer Padding="0,0,20,0">
<ScrollViewer Padding="0,0,20,0"
HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Hidden">
<StackPanel Spacing="20">
<TextBlock Text="{Binding Localization[Menu_Settings]}" FontSize="28" FontWeight="Bold" Margin="0,0,0,10" />
@@ -30,7 +31,7 @@
Opacity="0.8" />
<ComboBox Grid.Column="1"
ItemsSource="{Binding Localization.AvailableLanguages}"
SelectedItem="{Binding Localization.SelectedLanguage}"
SelectedItem="{Binding SelectedLanguage}"
IsEnabled="{Binding !IsSettingsLocked}"
Width="200"
MaxDropDownHeight="300" />
@@ -150,7 +151,82 @@
</StackPanel>
</Border>
<!-- 4. ADVANCED SETTINGS -->
<!-- 4. PROCESSING LIMITS -->
<Border Background="{DynamicResource PaneBackgroundBrush}" CornerRadius="8" Padding="20"
BorderBrush="{DynamicResource GlassBorderBrush}" BorderThickness="1">
<StackPanel Spacing="15">
<StackPanel Orientation="Horizontal" Spacing="10">
<icons:MaterialIcon Kind="Speedometer" Width="24" Height="24"
Foreground="{DynamicResource SystemAccentColor}" />
<TextBlock Text="{Binding Localization[Settings_Limits]}" FontSize="18" FontWeight="SemiBold" />
</StackPanel>
<Grid ColumnDefinitions="*, Auto"
RowDefinitions="Auto, 15, Auto, 15, Auto, 15, Auto">
<!-- File Size Limit -->
<StackPanel Grid.Row="0" Grid.Column="0">
<TextBlock Text="{Binding Localization[Settings_FileSizeLimit]}" FontWeight="Bold" />
<TextBlock Text="{Binding Localization[Settings_FileSizeDesc]}" FontSize="12" Opacity="0.7" />
</StackPanel>
<StackPanel Grid.Row="0" Grid.Column="1" Orientation="Horizontal" Spacing="10"
IsEnabled="{Binding !IsSettingsLocked}">
<ToggleSwitch IsChecked="{Binding Prefs.IsFileSizeLimitEnabled}" />
<NumericUpDown Value="{Binding Prefs.FileSizeLimitValue}" Minimum="1" Width="150"
IsEnabled="{Binding Prefs.IsFileSizeLimitEnabled}" />
<ComboBox ItemsSource="{Binding FileSizeUnits}"
SelectedItem="{Binding Prefs.FileSizeLimitUnit}"
IsEnabled="{Binding Prefs.IsFileSizeLimitEnabled}"
Width="80" />
</StackPanel>
<!-- File Processing Timeout -->
<StackPanel Grid.Row="2" Grid.Column="0">
<TextBlock Text="{Binding Localization[Settings_FileTimeout]}" FontWeight="Bold" />
<TextBlock Text="{Binding Localization[Settings_FileTimeoutDesc]}" FontSize="12"
Opacity="0.7" />
</StackPanel>
<StackPanel Grid.Row="2" Grid.Column="1" Orientation="Horizontal" Spacing="10"
IsEnabled="{Binding !IsSettingsLocked}">
<ToggleSwitch IsChecked="{Binding Prefs.IsFileTimeoutEnabled}" />
<NumericUpDown Value="{Binding Prefs.FileTimeoutSeconds}" Minimum="10" Maximum="3600"
Width="150"
IsEnabled="{Binding Prefs.IsFileTimeoutEnabled}" />
<TextBlock Text="{Binding Localization[Unit_Seconds]}" VerticalAlignment="Center" />
</StackPanel>
<!-- Max Files per Folder Scan -->
<StackPanel Grid.Row="4" Grid.Column="0">
<TextBlock Text="{Binding Localization[Settings_MaxFileCount]}" FontWeight="Bold" />
<TextBlock Text="{Binding Localization[Settings_MaxFileCountDesc]}" FontSize="12"
Opacity="0.7" />
</StackPanel>
<StackPanel Grid.Row="4" Grid.Column="1" Orientation="Horizontal" Spacing="10"
IsEnabled="{Binding !IsSettingsLocked}">
<ToggleSwitch IsChecked="{Binding Prefs.IsMaxFileCountEnabled}" />
<NumericUpDown Value="{Binding Prefs.MaxFileCount}" Minimum="1" Maximum="100000"
Width="150"
IsEnabled="{Binding Prefs.IsMaxFileCountEnabled}" />
</StackPanel>
<!-- Max Folders per Click -->
<StackPanel Grid.Row="6" Grid.Column="0">
<TextBlock Text="{Binding Localization[Settings_MaxFolderCount]}" FontWeight="Bold" />
<TextBlock Text="{Binding Localization[Settings_MaxFolderCountDesc]}" FontSize="12"
Opacity="0.7" />
</StackPanel>
<StackPanel Grid.Row="6" Grid.Column="1" Orientation="Horizontal" Spacing="10"
IsEnabled="{Binding !IsSettingsLocked}">
<ToggleSwitch IsChecked="{Binding Prefs.IsMaxFolderCountEnabled}" />
<NumericUpDown Value="{Binding Prefs.MaxFolderCount}" Minimum="1" Maximum="100"
Width="150"
IsEnabled="{Binding Prefs.IsMaxFolderCountEnabled}" />
</StackPanel>
</Grid>
</StackPanel>
</Border>
<!-- 5. ADVANCED SETTINGS -->
<Border Background="{DynamicResource PaneBackgroundBrush}" CornerRadius="8" Padding="20"
BorderBrush="{DynamicResource GlassBorderBrush}" BorderThickness="1">
<StackPanel Spacing="15">
@@ -163,43 +239,37 @@
<Grid ColumnDefinitions="*, Auto"
RowDefinitions="Auto, 15, Auto, 15, Auto, 15, Auto, 15, Auto, 15, Auto">
<!-- Developer Mode -->
<!-- Show Speed -->
<StackPanel Grid.Row="0" Grid.Column="0">
<TextBlock Text="{Binding Localization[Settings_ShowSpeed]}" FontWeight="Bold" />
<TextBlock Text="{Binding Localization[Settings_ShowSpeedDesc]}" FontSize="12"
Opacity="0.7" />
</StackPanel>
<ToggleSwitch Grid.Row="0" Grid.Column="1"
IsChecked="{Binding ShowReadWriteSpeed}"
IsEnabled="{Binding !IsSettingsLocked}" />
<!-- Developer Mode -->
<StackPanel Grid.Row="2" Grid.Column="0">
<TextBlock Text="{Binding Localization[Settings_DeveloperMode]}" FontWeight="Bold" />
<TextBlock Text="{Binding Localization[Settings_DeveloperDesc]}" FontSize="12"
Opacity="0.7" />
</StackPanel>
<ToggleSwitch Grid.Row="0" Grid.Column="1"
<ToggleSwitch Grid.Row="2" Grid.Column="1"
IsChecked="{Binding IsDeveloperModeEnabled}"
Command="{Binding ToggleDeveloperModeCommand}"
IsEnabled="{Binding !IsSettingsLocked}" />
<!-- Admin Mode -->
<StackPanel Grid.Row="2" Grid.Column="0">
<StackPanel Grid.Row="4" Grid.Column="0">
<TextBlock Text="{Binding Localization[Settings_AdminMode]}" FontWeight="Bold" />
<TextBlock Text="{Binding Localization[Settings_AdminDesc]}" FontSize="12" Opacity="0.7" />
</StackPanel>
<ToggleSwitch Grid.Row="2" Grid.Column="1"
<ToggleSwitch Grid.Row="4" Grid.Column="1"
IsChecked="{Binding IsAdminModeEnabled}"
Command="{Binding ToggleAdminModeCommand}"
IsEnabled="{Binding IsAdminModeSupported}" />
<!-- File Size Limit -->
<StackPanel Grid.Row="4" Grid.Column="0">
<TextBlock Text="{Binding Localization[Settings_FileSizeLimit]}" FontWeight="Bold" />
<TextBlock Text="{Binding Localization[Settings_FileSizeDesc]}" FontSize="12" Opacity="0.7" />
</StackPanel>
<StackPanel Grid.Row="4" Grid.Column="1" Orientation="Horizontal" Spacing="10"
IsEnabled="{Binding !IsSettingsLocked}">
<ToggleSwitch IsChecked="{Binding Prefs.IsFileSizeLimitEnabled}" />
<NumericUpDown Value="{Binding Prefs.FileSizeLimitValue}" Minimum="1" Width="100"
IsEnabled="{Binding Prefs.IsFileSizeLimitEnabled}" />
<ComboBox ItemsSource="{Binding FileSizeUnits}"
SelectedItem="{Binding Prefs.FileSizeLimitUnit}"
IsEnabled="{Binding Prefs.IsFileSizeLimitEnabled}"
Width="80" />
</StackPanel>
<!-- Force Quit Timeout -->
<StackPanel Grid.Row="6" Grid.Column="0">
<TextBlock Text="{Binding Localization[Settings_ForceQuitTimeout]}" FontWeight="Bold" />
@@ -208,24 +278,19 @@
</StackPanel>
<StackPanel Grid.Row="6" Grid.Column="1" Orientation="Horizontal" Spacing="10"
IsEnabled="{Binding !IsSettingsLocked}">
<NumericUpDown Value="{Binding ForceQuitTimeout}" Minimum="1" Maximum="60" Width="100" />
<NumericUpDown Value="{Binding ForceQuitTimeout}" Minimum="1" Maximum="60" Width="150" />
<TextBlock Text="{Binding Localization[Unit_Seconds]}" VerticalAlignment="Center" />
</StackPanel>
<!-- File Processing Timeout -->
<!-- Free Memory -->
<StackPanel Grid.Row="8" Grid.Column="0">
<TextBlock Text="{Binding Localization[Settings_FileTimeout]}" FontWeight="Bold" />
<TextBlock Text="{Binding Localization[Settings_FileTimeoutDesc]}" FontSize="12"
<TextBlock Text="{Binding Localization[Settings_FreeMemory]}" FontWeight="Bold" />
<TextBlock Text="{Binding Localization[Settings_FreeMemoryDesc]}" FontSize="12"
Opacity="0.7" />
</StackPanel>
<StackPanel Grid.Row="8" Grid.Column="1" Orientation="Horizontal" Spacing="10"
IsEnabled="{Binding !IsSettingsLocked}">
<ToggleSwitch IsChecked="{Binding Prefs.IsFileTimeoutEnabled}" />
<NumericUpDown Value="{Binding Prefs.FileTimeoutSeconds}" Minimum="10" Maximum="3600"
Width="100"
IsEnabled="{Binding Prefs.IsFileTimeoutEnabled}" />
<TextBlock Text="{Binding Localization[Unit_Seconds]}" VerticalAlignment="Center" />
</StackPanel>
<Button Grid.Row="8" Grid.Column="1"
Content="{Binding Localization[Settings_BtnFreeMemory]}"
Command="{Binding FreeMemoryCommand}" />
<!-- Force Quit Button -->
<StackPanel Grid.Row="10" Grid.Column="0">
@@ -286,7 +351,7 @@
<TextBlock Text="{Binding Localization[Settings_ResetDesc]}" FontSize="12" Opacity="0.7" />
</StackPanel>
<Button Grid.Row="2" Grid.Column="1"
Command="{Binding ResetAppearanceCommand}"
Command="{Binding ResetSettingsCommand}"
Content="{Binding Localization[Settings_Reset]}"
IsEnabled="{Binding !IsSettingsLocked}" />
+6
View File
@@ -1,4 +1,5 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace CheckHash.Views;
@@ -8,4 +9,9 @@ public partial class SettingsView : UserControl
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
+6
View File
@@ -1,4 +1,5 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace CheckHash.Views;
@@ -8,4 +9,9 @@ public partial class UpdateView : UserControl
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
@@ -1,26 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<CopyLocalSatelliteAssemblies>false</CopyLocalSatelliteAssemblies>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\CheckHash.csproj" />
</ItemGroup>
</Project>
@@ -1,89 +0,0 @@
using Xunit;
using CheckHash.ViewModels;
using CheckHash.Services;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Linq;
namespace CheckHash.Tests;
public class LocalizationTests
{
[Fact]
public void UpdateViewModel_ShouldUpdateProperties_WhenLanguageChanges()
{
// Arrange
var vm = new UpdateViewModel();
bool versionChanged = false;
bool localizationChanged = false;
vm.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(vm.CurrentVersionText))
{
versionChanged = true;
}
if (e.PropertyName == nameof(vm.Localization))
{
localizationChanged = true;
}
};
// Act
// Switch to a different language
var targetLangCode = LocalizationService.Instance.SelectedLanguage.Code == "vi-VN" ? "en-US" : "vi-VN";
var targetLang = LocalizationService.Instance.AvailableLanguages.First(x => x.Code == targetLangCode);
LocalizationService.Instance.SelectedLanguage = targetLang;
// Assert
Assert.True(versionChanged, "CurrentVersionText property changed event should be raised");
Assert.True(localizationChanged, "Localization property changed event should be raised");
}
[Fact]
public void SettingsViewModel_ShouldNotifyLocalizationChanged_WhenLanguageChanges()
{
// Arrange
var vm = new SettingsViewModel();
bool notified = false;
vm.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(vm.Localization))
{
notified = true;
}
};
// Act
var targetLangCode = LocalizationService.Instance.SelectedLanguage.Code == "vi-VN" ? "en-US" : "vi-VN";
var targetLang = LocalizationService.Instance.AvailableLanguages.First(x => x.Code == targetLangCode);
LocalizationService.Instance.SelectedLanguage = targetLang;
// Assert
Assert.True(notified, "SettingsViewModel should raise PropertyChanged for 'Localization'");
}
[Fact]
public void DeveloperViewModel_ShouldNotifyLocalizationChanged_WhenLanguageChanges()
{
// Arrange
var vm = new DeveloperViewModel();
bool notified = false;
vm.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(vm.Localization))
{
notified = true;
}
};
// Act
var targetLangCode = LocalizationService.Instance.SelectedLanguage.Code == "vi-VN" ? "en-US" : "vi-VN";
var targetLang = LocalizationService.Instance.AvailableLanguages.First(x => x.Code == targetLangCode);
LocalizationService.Instance.SelectedLanguage = targetLang;
// Assert
Assert.True(notified, "DeveloperViewModel should raise PropertyChanged for 'Localization'");
}
}
-50
View File
@@ -1,50 +0,0 @@
using Xunit;
using CheckHash.ViewModels;
using CheckHash.Services;
using System.Reflection;
using System.IO;
using System.Threading.Tasks;
using System;
namespace CheckHash.Tests;
public class SecurityTests
{
public SecurityTests()
{
// Disable UI logging to avoid Dispatcher issues since we are not in an Avalonia App
LoggerService.Instance.IsRecording = false;
}
[Fact]
public async Task Test_ReadHashFromFile_LargeFile_DoS_Prevention()
{
// Arrange
var tempFile = Path.GetTempFileName();
try
{
// Write 2MB of data (Hex characters so it might match the regex if read)
var largeContent = new string('A', 2 * 1024 * 1024);
await File.WriteAllTextAsync(tempFile, largeContent);
var viewModel = new CheckHashViewModel();
var methodInfo = typeof(CheckHashViewModel).GetMethod("ReadHashFromFile", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(methodInfo);
// Act
// Invoke the private method
var task = (Task<string>)methodInfo!.Invoke(viewModel, new object[] { tempFile })!;
var result = await task;
// Assert
// After fix, it should return empty string because file is too large (assuming 1MB limit)
// Before fix, it would read the file and likely return a match (128 chars of 'A')
Assert.Equal("", result);
}
finally
{
if (File.Exists(tempFile)) File.Delete(tempFile);
}
}
}