Code Cleanup

This commit is contained in:
ema
2025-05-23 02:39:26 +08:00
parent 34f69cc4f4
commit 06e7dbaae7
10 changed files with 89 additions and 123 deletions

View File

@@ -92,7 +92,7 @@ public class ArchiveFileEntry : IComparable<ArchiveFileEntry>
if (IsFolder)
return $"{Name}";
var en = Encrypted ? "*" : "";
var en = Encrypted ? "*" : string.Empty;
return $"{Name}{en},{IsFolder},{Size},{ModifiedDate}";
}
}

View File

@@ -37,7 +37,7 @@ namespace QuickLook.Plugin.ArchiveViewer;
/// </summary>
public partial class ArchiveInfoPanel : UserControl, IDisposable, INotifyPropertyChanged
{
private readonly Dictionary<string, ArchiveFileEntry> _fileEntries = new Dictionary<string, ArchiveFileEntry>();
private readonly Dictionary<string, ArchiveFileEntry> _fileEntries = [];
private bool _disposed;
private double _loadPercent;
private ulong _totalZippedSize;
@@ -82,7 +82,7 @@ public partial class ArchiveInfoPanel : UserControl, IDisposable, INotifyPropert
_totalZippedSize = (ulong)new FileInfo(path).Length;
var root = new ArchiveFileEntry(Path.GetFileName(path), true);
_fileEntries.Add("", root);
_fileEntries.Add(string.Empty, root);
try
{
@@ -123,7 +123,7 @@ public partial class ArchiveInfoPanel : UserControl, IDisposable, INotifyPropert
if (_disposed)
return;
fileListView.SetDataContext(_fileEntries[""].Children.Keys);
fileListView.SetDataContext(_fileEntries[string.Empty].Children.Keys);
archiveCount.Content =
$"{_type} archive{t}";
archiveSizeC.Content =
@@ -137,38 +137,37 @@ public partial class ArchiveInfoPanel : UserControl, IDisposable, INotifyPropert
private void LoadItemsFromArchive(string path)
{
using (var stream = File.OpenRead(path))
using var stream = File.OpenRead(path);
// ReaderFactory is slow... so limit its usage
string[] useReader = [".tar.gz", ".tgz", ".tar.bz2", ".tar.lz", ".tar.xz"];
if (useReader.Any(path.ToLower().EndsWith))
{
// ReaderFactory is slow... so limit its usage
string[] useReader = { ".tar.gz", ".tgz", ".tar.bz2", ".tar.lz", ".tar.xz" };
var reader = ReaderFactory.Open(stream, new ChardetReaderOptions());
if (useReader.Any(path.ToLower().EndsWith))
_type = reader.ArchiveType.ToString();
while (reader.MoveToNextEntry())
{
var reader = ReaderFactory.Open(stream, new ChardetReaderOptions());
_type = reader.ArchiveType.ToString();
while (reader.MoveToNextEntry())
{
if (_disposed)
return;
LoadPercent = 100d * stream.Position / stream.Length;
ProcessByLevel(reader.Entry);
}
if (_disposed)
return;
LoadPercent = 100d * stream.Position / stream.Length;
ProcessByLevel(reader.Entry);
}
else
}
else
{
var archive = ArchiveFactory.Open(stream, new ChardetReaderOptions());
_type = archive.Type.ToString();
foreach (var entry in archive.Entries)
{
var archive = ArchiveFactory.Open(stream, new ChardetReaderOptions());
_type = archive.Type.ToString();
foreach (var entry in archive.Entries)
{
if (_disposed)
return;
LoadPercent = 100d * stream.Position / stream.Length;
ProcessByLevel(entry);
}
if (_disposed)
return;
LoadPercent = 100d * stream.Position / stream.Length;
ProcessByLevel(entry);
}
}
}
@@ -212,17 +211,17 @@ public partial class ArchiveInfoPanel : UserControl, IDisposable, INotifyPropert
{
var d = Path.GetDirectoryName(path);
return d ?? "";
return d ?? string.Empty;
}
private string[] GetPathFragments(string path)
{
if (string.IsNullOrEmpty(path))
return new string[0];
return [];
var frags = path.Split('\\', '/').Where(f => !string.IsNullOrEmpty(f)).ToArray();
return frags.Select((s, i) => frags.Take(i + 1).Aggregate((a, b) => a + "\\" + b)).ToArray();
return [.. frags.Select((s, i) => frags.Take(i + 1).Aggregate((a, b) => a + "\\" + b))];
}
[NotifyPropertyChangedInvocator]

View File

@@ -96,7 +96,7 @@ public class BooleanToAsteriskConverter : DependencyObject, IValueConverter
{
var b = (bool)value;
return b ? "*" : "";
return b ? "*" : string.Empty;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
@@ -112,7 +112,7 @@ public class SizePrettyPrintConverter : DependencyObject, IMultiValueConverter
var size = (ulong)values[0];
var isFolder = (bool)values[1];
return isFolder ? "" : ((long)size).ToPrettySize(2);
return isFolder ? string.Empty : ((long)size).ToPrettySize(2);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
@@ -128,7 +128,7 @@ public class DatePrintConverter : DependencyObject, IMultiValueConverter
var date = (DateTime)values[0];
var isFolder = (bool)values[1];
return isFolder ? "" : date.ToString(CultureInfo.CurrentCulture);
return isFolder ? string.Empty : date.ToString(CultureInfo.CurrentCulture);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)

View File

@@ -137,16 +137,10 @@ internal class ResourceManager
}
}
private class VersionInfo
private class VersionInfo(string embeddedHash, string extractedHash)
{
public string EmbeddedHash { get; set; }
public string ExtractedHash { get; set; }
public VersionInfo(string embeddedHash, string extractedHash)
{
EmbeddedHash = embeddedHash;
ExtractedHash = extractedHash;
}
public string EmbeddedHash { get; set; } = embeddedHash;
public string ExtractedHash { get; set; } = extractedHash;
}
private static string CalculateDirectoryHash(string directory)
@@ -169,8 +163,8 @@ internal class ResourceManager
combinedBytes.AddRange(contentBytes);
}
var hash = sha256.ComputeHash(combinedBytes.ToArray());
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
var hash = sha256.ComputeHash([.. combinedBytes]);
return BitConverter.ToString(hash).Replace("-", string.Empty).ToLowerInvariant();
}
}
@@ -190,32 +184,28 @@ internal class ResourceManager
private string CalculateEmbeddedResourcesHash()
{
var assembly = Assembly.GetExecutingAssembly();
using (var sha256 = SHA256.Create())
using var sha256 = SHA256.Create();
var combinedBytes = new List<byte>();
var resourceNames = assembly.GetManifestResourceNames()
.Where(name => name.StartsWith(_resourcePrefix) &&
!name.EndsWith(".version"))
.OrderBy(name => name)
.ToList();
foreach (var resourceName in resourceNames)
{
var combinedBytes = new List<byte>();
var resourceNames = assembly.GetManifestResourceNames()
.Where(name => name.StartsWith(_resourcePrefix) &&
!name.EndsWith(".version"))
.OrderBy(name => name)
.ToList();
var nameBytes = Encoding.UTF8.GetBytes(resourceName.ToLowerInvariant());
combinedBytes.AddRange(nameBytes);
foreach (var resourceName in resourceNames)
{
var nameBytes = Encoding.UTF8.GetBytes(resourceName.ToLowerInvariant());
combinedBytes.AddRange(nameBytes);
using (var stream = assembly.GetManifestResourceStream(resourceName))
{
if (stream == null) continue;
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
combinedBytes.AddRange(buffer);
}
}
var hash = sha256.ComputeHash(combinedBytes.ToArray());
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
using var stream = assembly.GetManifestResourceStream(resourceName);
if (stream == null) continue;
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
combinedBytes.AddRange(buffer);
}
var hash = sha256.ComputeHash([.. combinedBytes]);
return BitConverter.ToString(hash).Replace("-", string.Empty).ToLowerInvariant();
}
private void GenerateVersionFile()

View File

@@ -41,18 +41,18 @@ public class RegFileObject
public RegFileObject()
{
regvalues = new Dictionary<string, Dictionary<string, RegValueObject>>();
regvalues = [];
}
public RegFileObject(string RegFileName)
{
regvalues = new Dictionary<string, Dictionary<string, RegValueObject>>();
regvalues = [];
Read(RegFileName);
}
public RegFileObject(byte[] RegFileContents)
{
regvalues = new Dictionary<string, Dictionary<string, RegValueObject>>();
regvalues = [];
Read(RegFileContents);
}
@@ -165,7 +165,7 @@ public class RegFileObject
if (sKey.EndsWith("=")) sKey = sKey.Substring(0, sKey.Length - 1);
sKey = StripeBraces(sKey);
if (sKey == "@")
sKey = "";
sKey = string.Empty;
else
sKey = StripeLeadingChars(sKey, "\"");
@@ -226,7 +226,7 @@ public class RegFileObject
while (sKey.EndsWith("\r\n")) sKey = sKey.Substring(0, sKey.Length - 2);
if (sKey == "@")
sKey = "";
sKey = string.Empty;
else
sKey = StripeLeadingChars(sKey, "\"");
@@ -443,7 +443,7 @@ public class RegValueObject
return "HKEY_CURRENT_USER";
}
return "";
return string.Empty;
}
/// <summary>
@@ -512,44 +512,21 @@ public class RegValueObject
private string SetRegEntryType(string sRegDataType)
{
switch (sRegDataType)
return sRegDataType switch
{
case "REG_QWORD":
return "hex(b):";
case "REG_RESOURCE_REQUIREMENTS_LIST":
return "hex(a):";
case "REG_FULL_RESOURCE_DESCRIPTOR":
return "hex(9):";
case "REG_RESOURCE_LIST":
return "hex(8):";
case "REG_MULTI_SZ":
return "hex(7):";
case "REG_LINK":
return "hex(6):";
case "REG_DWORD":
return "dword:";
case "REG_EXPAND_SZ":
return "hex(2):";
case "REG_NONE":
return "hex(0):";
case "REG_BINARY":
return "hex:";
case "REG_SZ":
return "";
default:
return "";
}
"REG_QWORD" => "hex(b):",
"REG_RESOURCE_REQUIREMENTS_LIST" => "hex(a):",
"REG_FULL_RESOURCE_DESCRIPTOR" => "hex(9):",
"REG_RESOURCE_LIST" => "hex(8):",
"REG_MULTI_SZ" => "hex(7):",
"REG_LINK" => "hex(6):",
"REG_DWORD" => "dword:",
"REG_EXPAND_SZ" => "hex(2):",
"REG_NONE" => "hex(0):",
"REG_BINARY" => "hex:",
"REG_SZ" => string.Empty,
_ => string.Empty,
};
/*
hex: REG_BINARY

View File

@@ -197,7 +197,7 @@ public partial class App : Application
{
TrayIconManager.GetInstance();
if (!e.Args.Contains("/autorun") && !IsUWP)
TrayIconManager.ShowNotification("", TranslationHelper.Get("APP_START"));
TrayIconManager.ShowNotification(string.Empty, TranslationHelper.Get("APP_START"));
if (e.Args.Contains("/first"))
AutoStartupHelper.CreateAutorunShortcut();

View File

@@ -49,7 +49,7 @@ internal static class AutoStartupHelper
catch (Exception e)
{
ProcessHelper.WriteLog(e.ToString());
TrayIconManager.ShowNotification("", "Failed to add QuickLook to Startup folder.");
TrayIconManager.ShowNotification(string.Empty, "Failed to add QuickLook to Startup folder.");
}
}
@@ -65,7 +65,7 @@ internal static class AutoStartupHelper
catch (Exception e)
{
ProcessHelper.WriteLog(e.ToString());
TrayIconManager.ShowNotification("", "Failed to delete QuickLook startup shortcut.");
TrayIconManager.ShowNotification(string.Empty, "Failed to delete QuickLook startup shortcut.");
}
}

View File

@@ -53,7 +53,7 @@ internal class Updater
{
if (!silent)
Application.Current.Dispatcher.Invoke(
() => TrayIconManager.ShowNotification("",
() => TrayIconManager.ShowNotification(string.Empty,
TranslationHelper.Get("Update_NoUpdate")));
return;
}
@@ -63,7 +63,7 @@ internal class Updater
Application.Current.Dispatcher.Invoke(
() =>
{
TrayIconManager.ShowNotification("",
TrayIconManager.ShowNotification(string.Empty,
string.Format(TranslationHelper.Get("Update_Found"), nVersion),
timeout: 20000,
clickEvent:
@@ -74,7 +74,7 @@ internal class Updater
{
Debug.WriteLine(e.Message);
Application.Current.Dispatcher.Invoke(
() => TrayIconManager.ShowNotification("",
() => TrayIconManager.ShowNotification(string.Empty,
string.Format(TranslationHelper.Get("Update_Error"), e.Message)));
}
});
@@ -110,7 +110,7 @@ internal class Updater
{
Debug.WriteLine(e.Message);
Application.Current.Dispatcher.Invoke(
() => TrayIconManager.ShowNotification("",
() => TrayIconManager.ShowNotification(string.Empty,
string.Format(TranslationHelper.Get("Update_Error"), e.Message)));
}
});

View File

@@ -53,7 +53,7 @@ internal class TrayIconManager : IDisposable
Icon = GetTrayIconByDPI(),
ContextMenu = new ContextMenu(
[
new MenuItem($"v{Application.ProductVersion}{(App.IsUWP ? " (UWP)" : "")}") {Enabled = false},
new MenuItem($"v{Application.ProductVersion}{(App.IsUWP ? " (UWP)" : string.Empty)}") {Enabled = false},
new MenuItem("-"),
new MenuItem(TranslationHelper.Get("Icon_CheckUpdate"), (_, _) => Updater.CheckForUpdates()),
new MenuItem(TranslationHelper.Get("Icon_GetPlugin"),