Merge branch 'dev' into load_image_async

This commit is contained in:
Jack Ye 2025-04-04 16:47:02 +08:00 committed by GitHub
commit 35febd348f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 361 additions and 130 deletions

View file

@ -22,7 +22,7 @@ namespace Flow.Launcher.Core.Configuration
/// As at Squirrel.Windows version 1.5.2, UpdateManager needs to be disposed after finish
/// </summary>
/// <returns></returns>
private UpdateManager NewUpdateManager()
private static UpdateManager NewUpdateManager()
{
var applicationFolderName = Constant.ApplicationDirectory
.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.None)
@ -81,20 +81,16 @@ namespace Flow.Launcher.Core.Configuration
public void RemoveShortcuts()
{
using (var portabilityUpdater = NewUpdateManager())
{
portabilityUpdater.RemoveShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.StartMenu);
portabilityUpdater.RemoveShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.Desktop);
portabilityUpdater.RemoveShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.Startup);
}
using var portabilityUpdater = NewUpdateManager();
portabilityUpdater.RemoveShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.StartMenu);
portabilityUpdater.RemoveShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.Desktop);
portabilityUpdater.RemoveShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.Startup);
}
public void RemoveUninstallerEntry()
{
using (var portabilityUpdater = NewUpdateManager())
{
portabilityUpdater.RemoveUninstallerRegistryEntry();
}
using var portabilityUpdater = NewUpdateManager();
portabilityUpdater.RemoveUninstallerRegistryEntry();
}
public void MoveUserDataFolder(string fromLocation, string toLocation)
@ -110,12 +106,10 @@ namespace Flow.Launcher.Core.Configuration
public void CreateShortcuts()
{
using (var portabilityUpdater = NewUpdateManager())
{
portabilityUpdater.CreateShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.StartMenu, false);
portabilityUpdater.CreateShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.Desktop, false);
portabilityUpdater.CreateShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.Startup, false);
}
using var portabilityUpdater = NewUpdateManager();
portabilityUpdater.CreateShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.StartMenu, false);
portabilityUpdater.CreateShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.Desktop, false);
portabilityUpdater.CreateShortcutsForExecutable(Constant.ApplicationFileName, ShortcutLocation.Startup, false);
}
public void CreateUninstallerEntry()
@ -129,18 +123,14 @@ namespace Flow.Launcher.Core.Configuration
subKey2.SetValue("DisplayIcon", Path.Combine(Constant.ApplicationDirectory, "app.ico"), RegistryValueKind.String);
}
using (var portabilityUpdater = NewUpdateManager())
{
_ = portabilityUpdater.CreateUninstallerRegistryEntry();
}
using var portabilityUpdater = NewUpdateManager();
_ = portabilityUpdater.CreateUninstallerRegistryEntry();
}
internal void IndicateDeletion(string filePathTodelete)
private static void IndicateDeletion(string filePathTodelete)
{
var deleteFilePath = Path.Combine(filePathTodelete, DataLocation.DeletionIndicatorFile);
using (var _ = File.CreateText(deleteFilePath))
{
}
using var _ = File.CreateText(deleteFilePath);
}
///<summary>

View file

@ -23,6 +23,8 @@ namespace Flow.Launcher.Core.Plugin
protected ConcurrentDictionary<string, object?> Settings { get; set; } = null!;
public required IPublicAPI API { get; init; }
private static readonly string ClassName = nameof(JsonRPCPluginSettings);
private JsonStorage<ConcurrentDictionary<string, object?>> _storage = null!;
private static readonly Thickness SettingPanelMargin = (Thickness)Application.Current.FindResource("SettingPanelMargin");
@ -122,12 +124,26 @@ namespace Flow.Launcher.Core.Plugin
public async Task SaveAsync()
{
await _storage.SaveAsync();
try
{
await _storage.SaveAsync();
}
catch (System.Exception e)
{
API.LogException(ClassName, $"Failed to save plugin settings to path: {SettingPath}", e);
}
}
public void Save()
{
_storage.Save();
try
{
_storage.Save();
}
catch (System.Exception e)
{
API.LogException(ClassName, $"Failed to save plugin settings to path: {SettingPath}", e);
}
}
public bool NeedCreateSettingPanel()

View file

@ -4,10 +4,12 @@ using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using JetBrains.Annotations;
using Squirrel;
using CommunityToolkit.Mvvm.DependencyInjection;
using Flow.Launcher.Core.Resource;
using Flow.Launcher.Plugin.SharedCommands;
using Flow.Launcher.Infrastructure;
@ -15,8 +17,8 @@ using Flow.Launcher.Infrastructure.Http;
using Flow.Launcher.Infrastructure.Logger;
using Flow.Launcher.Infrastructure.UserSettings;
using Flow.Launcher.Plugin;
using System.Text.Json.Serialization;
using System.Threading;
using JetBrains.Annotations;
using Squirrel;
namespace Flow.Launcher.Core
{
@ -51,7 +53,7 @@ namespace Flow.Launcher.Core
var newReleaseVersion = Version.Parse(newUpdateInfo.FutureReleaseEntry.Version.ToString());
var currentVersion = Version.Parse(Constant.Version);
Log.Info($"|Updater.UpdateApp|Future Release <{newUpdateInfo.FutureReleaseEntry.Formatted()}>");
Log.Info($"|Updater.UpdateApp|Future Release <{Formatted(newUpdateInfo.FutureReleaseEntry)}>");
if (newReleaseVersion <= currentVersion)
{
@ -70,7 +72,7 @@ namespace Flow.Launcher.Core
if (DataLocation.PortableDataLocationInUse())
{
var targetDestination = updateManager.RootAppDirectory + $"\\app-{newReleaseVersion.ToString()}\\{DataLocation.PortableFolderName}";
var targetDestination = updateManager.RootAppDirectory + $"\\app-{newReleaseVersion}\\{DataLocation.PortableFolderName}";
FilesFolders.CopyAll(DataLocation.PortableDataPath, targetDestination, (s) => _api.ShowMsgBox(s));
if (!FilesFolders.VerifyBothFolderFilesEqual(DataLocation.PortableDataPath, targetDestination, (s) => _api.ShowMsgBox(s)))
_api.ShowMsgBox(string.Format(_api.GetTranslation("update_flowlauncher_fail_moving_portable_user_profile_data"),
@ -122,7 +124,7 @@ namespace Flow.Launcher.Core
}
// https://github.com/Squirrel/Squirrel.Windows/blob/master/src/Squirrel/UpdateManager.Factory.cs
private async Task<UpdateManager> GitHubUpdateManagerAsync(string repository)
private static async Task<UpdateManager> GitHubUpdateManagerAsync(string repository)
{
var uri = new Uri(repository);
var api = $"https://api.github.com/repos{uri.AbsolutePath}/releases";
@ -144,12 +146,22 @@ namespace Flow.Launcher.Core
return manager;
}
public string NewVersionTips(string version)
private static string NewVersionTips(string version)
{
var translator = InternationalizationManager.Instance;
var translator = Ioc.Default.GetRequiredService<Internationalization>();
var tips = string.Format(translator.GetTranslation("newVersionTips"), version);
return tips;
}
private static string Formatted<T>(T t)
{
var formatted = JsonSerializer.Serialize(t, new JsonSerializerOptions
{
WriteIndented = true
});
return formatted;
}
}
}

View file

@ -1,19 +1,11 @@
#nullable enable
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Flow.Launcher.Infrastructure
{
public static class Helper
{
static Helper()
{
jsonFormattedSerializerOptions.Converters.Add(new JsonStringEnumConverter());
}
/// <summary>
/// http://www.yinwang.org/blog-cn/2015/11/21/programming-philosophy
/// </summary>
@ -36,55 +28,5 @@ namespace Flow.Launcher.Infrastructure
throw new NullReferenceException();
}
}
public static void ValidateDataDirectory(string bundledDataDirectory, string dataDirectory)
{
if (!Directory.Exists(dataDirectory))
{
Directory.CreateDirectory(dataDirectory);
}
foreach (var bundledDataPath in Directory.GetFiles(bundledDataDirectory))
{
var data = Path.GetFileName(bundledDataPath);
var dataPath = Path.Combine(dataDirectory, data.NonNull());
if (!File.Exists(dataPath))
{
File.Copy(bundledDataPath, dataPath);
}
else
{
var time1 = new FileInfo(bundledDataPath).LastWriteTimeUtc;
var time2 = new FileInfo(dataPath).LastWriteTimeUtc;
if (time1 != time2)
{
File.Copy(bundledDataPath, dataPath, true);
}
}
}
}
public static void ValidateDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
private static readonly JsonSerializerOptions jsonFormattedSerializerOptions = new JsonSerializerOptions
{
WriteIndented = true
};
public static string Formatted<T>(this T t)
{
var formatted = JsonSerializer.Serialize(t, new JsonSerializerOptions
{
WriteIndented = true
});
return formatted;
}
}
}

View file

@ -61,7 +61,7 @@ namespace Flow.Launcher.Infrastructure.Image
});
}
public static async Task Save()
public static async Task SaveAsync()
{
await storageLock.WaitAsync();
@ -71,12 +71,22 @@ namespace Flow.Launcher.Infrastructure.Image
.Select(x => x.Key)
.ToList());
}
catch (System.Exception e)
{
Log.Exception($"|ImageLoader.SaveAsync|Failed to save image cache to file", e);
}
finally
{
storageLock.Release();
}
}
public static async Task WaitSaveAsync()
{
await storageLock.WaitAsync();
storageLock.Release();
}
private static async Task<List<(string, bool)>> LoadStorageToConcurrentDictionaryAsync()
{
await storageLock.WaitAsync();

View file

@ -2,6 +2,7 @@
using System.Threading.Tasks;
using Flow.Launcher.Infrastructure.Logger;
using Flow.Launcher.Infrastructure.UserSettings;
using Flow.Launcher.Plugin.SharedCommands;
using MemoryPack;
namespace Flow.Launcher.Infrastructure.Storage
@ -21,7 +22,7 @@ namespace Flow.Launcher.Infrastructure.Storage
public BinaryStorage(string filename, string directoryPath = null)
{
directoryPath ??= DataLocation.CacheDirectory;
Helper.ValidateDirectory(directoryPath);
FilesFolders.ValidateDirectory(directoryPath);
FilePath = Path.Combine(directoryPath, $"{filename}{FileSuffix}");
}

View file

@ -1,17 +1,51 @@
using System.IO;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.DependencyInjection;
using Flow.Launcher.Infrastructure.UserSettings;
using Flow.Launcher.Plugin;
using Flow.Launcher.Plugin.SharedCommands;
namespace Flow.Launcher.Infrastructure.Storage
{
public class FlowLauncherJsonStorage<T> : JsonStorage<T> where T : new()
{
private static readonly string ClassName = "FlowLauncherJsonStorage";
// We should not initialize API in static constructor because it will create another API instance
private static IPublicAPI api = null;
private static IPublicAPI API => api ??= Ioc.Default.GetRequiredService<IPublicAPI>();
public FlowLauncherJsonStorage()
{
var directoryPath = Path.Combine(DataLocation.DataDirectory(), DirectoryName);
Helper.ValidateDirectory(directoryPath);
FilesFolders.ValidateDirectory(directoryPath);
var filename = typeof(T).Name;
FilePath = Path.Combine(directoryPath, $"{filename}{FileSuffix}");
}
public new void Save()
{
try
{
base.Save();
}
catch (System.Exception e)
{
API.LogException(ClassName, $"Failed to save FL settings to path: {FilePath}", e);
}
}
public new async Task SaveAsync()
{
try
{
await base.SaveAsync();
}
catch (System.Exception e)
{
API.LogException(ClassName, $"Failed to save FL settings to path: {FilePath}", e);
}
}
}
}
}

View file

@ -5,6 +5,7 @@ using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
using Flow.Launcher.Infrastructure.Logger;
using Flow.Launcher.Plugin.SharedCommands;
namespace Flow.Launcher.Infrastructure.Storage
{
@ -37,7 +38,7 @@ namespace Flow.Launcher.Infrastructure.Storage
FilePath = filePath;
DirectoryPath = Path.GetDirectoryName(filePath) ?? throw new ArgumentException("Invalid file path");
Helper.ValidateDirectory(DirectoryPath);
FilesFolders.ValidateDirectory(DirectoryPath);
}
public async Task<T> LoadAsync()

View file

@ -1,5 +1,9 @@
using System.IO;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.DependencyInjection;
using Flow.Launcher.Infrastructure.UserSettings;
using Flow.Launcher.Plugin;
using Flow.Launcher.Plugin.SharedCommands;
namespace Flow.Launcher.Infrastructure.Storage
{
@ -8,13 +12,19 @@ namespace Flow.Launcher.Infrastructure.Storage
// Use assembly name to check which plugin is using this storage
public readonly string AssemblyName;
private static readonly string ClassName = "PluginJsonStorage";
// We should not initialize API in static constructor because it will create another API instance
private static IPublicAPI api = null;
private static IPublicAPI API => api ??= Ioc.Default.GetRequiredService<IPublicAPI>();
public PluginJsonStorage()
{
// C# related, add python related below
var dataType = typeof(T);
AssemblyName = dataType.Assembly.GetName().Name;
DirectoryPath = Path.Combine(DataLocation.PluginSettingsDirectory, AssemblyName);
Helper.ValidateDirectory(DirectoryPath);
FilesFolders.ValidateDirectory(DirectoryPath);
FilePath = Path.Combine(DirectoryPath, $"{dataType.Name}{FileSuffix}");
}
@ -23,5 +33,29 @@ namespace Flow.Launcher.Infrastructure.Storage
{
Data = data;
}
public new void Save()
{
try
{
base.Save();
}
catch (System.Exception e)
{
API.LogException(ClassName, $"Failed to save plugin settings to path: {FilePath}", e);
}
}
public new async Task SaveAsync()
{
try
{
await base.SaveAsync();
}
catch (System.Exception e)
{
API.LogException(ClassName, $"Failed to save plugin settings to path: {FilePath}", e);
}
}
}
}

View file

@ -488,5 +488,16 @@ namespace Flow.Launcher.Infrastructure
}
#endregion
#region Notification
public static bool IsNotificationSupported()
{
// Notifications only supported on Windows 10 19041+
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
Environment.OSVersion.Version.Build >= 19041;
}
#endregion
}
}

View file

@ -318,5 +318,51 @@ namespace Flow.Launcher.Plugin.SharedCommands
{
return path.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
}
/// <summary>
/// Validates a directory, creating it if it doesn't exist
/// </summary>
/// <param name="path"></param>
public static void ValidateDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
/// <summary>
/// Validates a data directory, synchronizing it by ensuring all files from a bundled source directory exist in it.
/// If files are missing or outdated, they are copied from the bundled directory to the data directory.
/// </summary>
/// <param name="bundledDataDirectory"></param>
/// <param name="dataDirectory"></param>
public static void ValidateDataDirectory(string bundledDataDirectory, string dataDirectory)
{
if (!Directory.Exists(dataDirectory))
{
Directory.CreateDirectory(dataDirectory);
}
foreach (var bundledDataPath in Directory.GetFiles(bundledDataDirectory))
{
var data = Path.GetFileName(bundledDataPath);
if (data == null) continue;
var dataPath = Path.Combine(dataDirectory, data);
if (!File.Exists(dataPath))
{
File.Copy(bundledDataPath, dataPath);
}
else
{
var time1 = new FileInfo(bundledDataPath).LastWriteTimeUtc;
var time2 = new FileInfo(dataPath).LastWriteTimeUtc;
if (time1 != time2)
{
File.Copy(bundledDataPath, dataPath, true);
}
}
}
}
}
}

View file

@ -304,6 +304,14 @@ namespace Flow.Launcher
return;
}
// If we call Environment.Exit(0), the application dispose will be called before _mainWindow.Close()
// Accessing _mainWindow?.Dispatcher will cause the application stuck
// So here we need to check it and just return so that we will not acees _mainWindow?.Dispatcher
if (!_mainWindow.CanClose)
{
return;
}
_disposed = true;
}

View file

@ -325,6 +325,9 @@
<system:String x:Key="logfolder">Log Folder</system:String>
<system:String x:Key="clearlogfolder">Clear Logs</system:String>
<system:String x:Key="clearlogfolderMessage">Are you sure you want to delete all logs?</system:String>
<system:String x:Key="clearcachefolder">Clear Caches</system:String>
<system:String x:Key="clearcachefolderMessage">Are you sure you want to delete all caches?</system:String>
<system:String x:Key="clearfolderfailMessage">Failed to clear part of folders and files. Please see log file for more information</system:String>
<system:String x:Key="welcomewindow">Wizard</system:String>
<system:String x:Key="userdatapath">User Data Location</system:String>
<system:String x:Key="userdatapathToolTip">User settings and installed plugins are saved in the user data folder. This location may vary depending on whether it's in portable mode or not.</system:String>

View file

@ -32,6 +32,13 @@ namespace Flow.Launcher
{
public partial class MainWindow : IDisposable
{
#region Public Property
// Window Event: Close Event
public bool CanClose { get; set; } = false;
#endregion
#region Private Fields
// Dependency Injection
@ -45,8 +52,6 @@ namespace Flow.Launcher
private readonly ContextMenu _contextMenu = new();
private readonly MainViewModel _viewModel;
// Window Event: Close Event
private bool _canClose = false;
// Window Event: Key Event
private bool _isArrowKeyPressed = false;
@ -279,7 +284,7 @@ namespace Flow.Launcher
private async void OnClosing(object sender, CancelEventArgs e)
{
if (!_canClose)
if (!CanClose)
{
_notifyIcon.Visible = false;
App.API.SaveAppAllSettings();
@ -287,7 +292,7 @@ namespace Flow.Launcher
await PluginManager.DisposePluginsAsync();
Notification.Uninstall();
// After plugins are all disposed, we can close the main window
_canClose = true;
CanClose = true;
// Use this instead of Close() to avoid InvalidOperationException when calling Close() in OnClosing event
Application.Current.Shutdown();
}

View file

@ -9,8 +9,8 @@ namespace Flow.Launcher
{
internal static class Notification
{
internal static bool legacy = Environment.OSVersion.Version.Build < 19041;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
internal static bool legacy = !Win32Helper.IsNotificationSupported();
internal static void Uninstall()
{
if (!legacy)
@ -25,7 +25,6 @@ namespace Flow.Launcher
});
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
private static void ShowInternal(string title, string subTitle, string iconPath = null)
{
// Handle notification for win7/8/early win10

View file

@ -38,6 +38,8 @@ namespace Flow.Launcher
private readonly Internationalization _translater;
private readonly MainViewModel _mainVM;
private readonly object _saveSettingsLock = new();
#region Constructor
public PublicAPIInstance(Settings settings, Internationalization translater, MainViewModel mainVM)
@ -58,21 +60,28 @@ namespace Flow.Launcher
_mainVM.ChangeQueryText(query, requery);
}
public void RestartApp()
#pragma warning disable VSTHRD100 // Avoid async void methods
public async void RestartApp()
{
_mainVM.Hide();
// we must manually save
// We must manually save
// UpdateManager.RestartApp() will call Environment.Exit(0)
// which will cause ungraceful exit
SaveAppAllSettings();
// Wait for all image caches to be saved before restarting
await ImageLoader.WaitSaveAsync();
// Restart requires Squirrel's Update.exe to be present in the parent folder,
// it is only published from the project's release pipeline. When debugging without it,
// the project may not restart or just terminates. This is expected.
UpdateManager.RestartApp(Constant.ApplicationFileName);
}
#pragma warning restore VSTHRD100 // Avoid async void methods
public void ShowMainWindow() => _mainVM.Show();
public void HideMainWindow() => _mainVM.Hide();
@ -86,10 +95,13 @@ namespace Flow.Launcher
public void SaveAppAllSettings()
{
PluginManager.Save();
_mainVM.Save();
_settings.Save();
_ = ImageLoader.Save();
lock (_saveSettingsLock)
{
_settings.Save();
PluginManager.Save();
_mainVM.Save();
}
_ = ImageLoader.SaveAsync();
}
public Task ReloadAllPluginData() => PluginManager.ReloadDataAsync();

View file

@ -6,7 +6,6 @@ using System.Threading.Tasks;
using System.Windows;
using CommunityToolkit.Mvvm.Input;
using Flow.Launcher.Core;
using Flow.Launcher.Core.Resource;
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Logger;
using Flow.Launcher.Infrastructure.UserSettings;
@ -16,6 +15,8 @@ namespace Flow.Launcher.SettingPages.ViewModels;
public partial class SettingsPaneAboutViewModel : BaseModel
{
private static readonly string ClassName = nameof(SettingsPaneAboutViewModel);
private readonly Settings _settings;
private readonly Updater _updater;
@ -24,7 +25,16 @@ public partial class SettingsPaneAboutViewModel : BaseModel
get
{
var size = GetLogFiles().Sum(file => file.Length);
return $"{InternationalizationManager.Instance.GetTranslation("clearlogfolder")} ({BytesToReadableString(size)})";
return $"{App.API.GetTranslation("clearlogfolder")} ({BytesToReadableString(size)})";
}
}
public string CacheFolderSize
{
get
{
var size = GetCacheFiles().Sum(file => file.Length);
return $"{App.API.GetTranslation("clearcachefolder")} ({BytesToReadableString(size)})";
}
}
@ -42,7 +52,7 @@ public partial class SettingsPaneAboutViewModel : BaseModel
};
public string ActivatedTimes => string.Format(
InternationalizationManager.Instance.GetTranslation("about_activate_times"),
App.API.GetTranslation("about_activate_times"),
_settings.ActivateTimes
);
@ -88,14 +98,35 @@ public partial class SettingsPaneAboutViewModel : BaseModel
private void AskClearLogFolderConfirmation()
{
var confirmResult = App.API.ShowMsgBox(
InternationalizationManager.Instance.GetTranslation("clearlogfolderMessage"),
InternationalizationManager.Instance.GetTranslation("clearlogfolder"),
App.API.GetTranslation("clearlogfolderMessage"),
App.API.GetTranslation("clearlogfolder"),
MessageBoxButton.YesNo
);
if (confirmResult == MessageBoxResult.Yes)
{
ClearLogFolder();
if (!ClearLogFolder())
{
App.API.ShowMsgBox(App.API.GetTranslation("clearfolderfailMessage"));
}
}
}
[RelayCommand]
private void AskClearCacheFolderConfirmation()
{
var confirmResult = App.API.ShowMsgBox(
App.API.GetTranslation("clearcachefolderMessage"),
App.API.GetTranslation("clearcachefolder"),
MessageBoxButton.YesNo
);
if (confirmResult == MessageBoxResult.Yes)
{
if (!ClearCacheFolder())
{
App.API.ShowMsgBox(App.API.GetTranslation("clearfolderfailMessage"));
}
}
}
@ -113,7 +144,6 @@ public partial class SettingsPaneAboutViewModel : BaseModel
App.API.OpenDirectory(parentFolderPath);
}
[RelayCommand]
private void OpenLogsFolder()
{
@ -121,21 +151,47 @@ public partial class SettingsPaneAboutViewModel : BaseModel
}
[RelayCommand]
private Task UpdateApp() => _updater.UpdateAppAsync(false);
private Task UpdateAppAsync() => _updater.UpdateAppAsync(false);
private void ClearLogFolder()
private bool ClearLogFolder()
{
var success = true;
var logDirectory = GetLogDir();
var logFiles = GetLogFiles();
logFiles.ForEach(f => f.Delete());
logFiles.ForEach(f =>
{
try
{
f.Delete();
}
catch (Exception e)
{
App.API.LogException(ClassName, $"Failed to delete log file: {f.Name}", e);
success = false;
}
});
logDirectory.EnumerateDirectories("*", SearchOption.TopDirectoryOnly)
// Do not clean log files of current version
.Where(dir => !Constant.Version.Equals(dir.Name))
.ToList()
.ForEach(dir => dir.Delete());
.ForEach(dir =>
{
try
{
dir.Delete(true);
}
catch (Exception e)
{
App.API.LogException(ClassName, $"Failed to delete log directory: {dir.Name}", e);
success = false;
}
});
OnPropertyChanged(nameof(LogFolderSize));
return success;
}
private static DirectoryInfo GetLogDir(string version = "")
@ -148,6 +204,55 @@ public partial class SettingsPaneAboutViewModel : BaseModel
return GetLogDir(version).EnumerateFiles("*", SearchOption.AllDirectories).ToList();
}
private bool ClearCacheFolder()
{
var success = true;
var cacheDirectory = GetCacheDir();
var cacheFiles = GetCacheFiles();
cacheFiles.ForEach(f =>
{
try
{
f.Delete();
}
catch (Exception e)
{
App.API.LogException(ClassName, $"Failed to delete cache file: {f.Name}", e);
success = false;
}
});
cacheDirectory.EnumerateDirectories("*", SearchOption.TopDirectoryOnly)
.ToList()
.ForEach(dir =>
{
try
{
dir.Delete(true);
}
catch (Exception e)
{
App.API.LogException(ClassName, $"Failed to delete cache directory: {dir.Name}", e);
success = false;
}
});
OnPropertyChanged(nameof(CacheFolderSize));
return success;
}
private static DirectoryInfo GetCacheDir()
{
return new DirectoryInfo(DataLocation.CacheDirectory);
}
private static List<FileInfo> GetCacheFiles()
{
return GetCacheDir().EnumerateFiles("*", SearchOption.AllDirectories).ToList();
}
private static string BytesToReadableString(long bytes)
{
const int scale = 1024;
@ -156,8 +261,7 @@ public partial class SettingsPaneAboutViewModel : BaseModel
foreach (string order in orders)
{
if (bytes > max)
return $"{decimal.Divide(bytes, max):##.##} {order}";
if (bytes > max) return $"{decimal.Divide(bytes, max):##.##} {order}";
max /= scale;
}

View file

@ -90,6 +90,10 @@
Margin="0 12 0 0"
Icon="&#xf12b;">
<StackPanel Orientation="Horizontal">
<Button
Margin="0 0 12 0"
Command="{Binding AskClearCacheFolderConfirmationCommand}"
Content="{Binding CacheFolderSize, Mode=OneWay}" />
<Button
Margin="0 0 12 0"
Command="{Binding AskClearLogFolderConfirmationCommand}"

View file

@ -6,13 +6,13 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Infrastructure.Logger;
using Flow.Launcher.Infrastructure.Storage;
using Flow.Launcher.Infrastructure.UserSettings;
using Flow.Launcher.Plugin.Program.Programs;
using Flow.Launcher.Plugin.Program.Views;
using Flow.Launcher.Plugin.Program.Views.Models;
using Flow.Launcher.Plugin.SharedCommands;
using Microsoft.Extensions.Caching.Memory;
using Path = System.IO.Path;
using Stopwatch = Flow.Launcher.Infrastructure.Stopwatch;
@ -191,7 +191,7 @@ namespace Flow.Launcher.Plugin.Program
await Stopwatch.NormalAsync("|Flow.Launcher.Plugin.Program.Main|Preload programs cost", async () =>
{
Helper.ValidateDirectory(Context.CurrentPluginMetadata.PluginCacheDirectoryPath);
FilesFolders.ValidateDirectory(Context.CurrentPluginMetadata.PluginCacheDirectoryPath);
static void MoveFile(string sourcePath, string destinationPath)
{

View file

@ -5,7 +5,6 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using Flow.Launcher.Infrastructure;
using Flow.Launcher.Plugin.SharedCommands;
namespace Flow.Launcher.Plugin.WebSearch
@ -180,7 +179,7 @@ namespace Flow.Launcher.Plugin.WebSearch
// Default images directory is in the WebSearch's application folder
DefaultImagesDirectory = Path.Combine(pluginDirectory, Images);
Helper.ValidateDataDirectory(bundledImagesDirectory, DefaultImagesDirectory);
FilesFolders.ValidateDataDirectory(bundledImagesDirectory, DefaultImagesDirectory);
// Custom images directory is in the WebSearch's data location folder
CustomImagesDirectory = Path.Combine(_context.CurrentPluginMetadata.PluginSettingsDirectoryPath, "CustomIcons");