浏览代码

Synchronize Config file saving functionality to better save and load from the same directory.

Ruben 4 月之前
父节点
当前提交
8c792ecb1d

+ 5 - 5
src/PicView.Avalonia/Input/KeybindingManager.cs

@@ -18,14 +18,14 @@ public static class KeybindingManager
 
     public static async Task LoadKeybindings(IPlatformSpecificService platformSpecificService)
     {
-        try
+        var keybindings = await KeybindingFunctions.LoadKeyBindingsFile().ConfigureAwait(false);
+        if (string.IsNullOrWhiteSpace(keybindings))
         {
-            var keybindings = await KeybindingFunctions.LoadKeyBindingsFile().ConfigureAwait(false);
-            await UpdateKeybindings(keybindings).ConfigureAwait(false);
+            await SetDefaultKeybindings(platformSpecificService).ConfigureAwait(false);
         }
-        catch (Exception)
+        else
         {
-            await SetDefaultKeybindings(platformSpecificService).ConfigureAwait(false);
+            await UpdateKeybindings(keybindings).ConfigureAwait(false);
         }
     }
 

+ 156 - 0
src/PicView.Core/Config/ConfigFileManager.cs

@@ -0,0 +1,156 @@
+using System.Runtime.InteropServices;
+using System.Text.Json.Serialization;
+using PicView.Core.DebugTools;
+using PicView.Core.FileHandling;
+using PicView.Core.FileHistory;
+using PicView.Core.Keybindings;
+
+namespace PicView.Core.Config;
+
+public enum ConfigFileType
+{
+    UserSettings,
+    FileHistory,
+    KeyBindings
+}
+
+public static class ConfigFileManager
+{
+    public static async Task<string?> SaveConfigFileAndReturnPathAsync(ConfigFileType type, string? path, object? value, Type inputType, JsonSerializerContext context)
+    {
+        path ??= type switch
+        {
+            // If null, try to get the current user file, if exist
+            ConfigFileType.UserSettings => SettingsConfiguration.CurrentUserSettingsPath,
+            ConfigFileType.FileHistory => FileHistoryConfiguration.CurrentUserFileHistoryPath,
+            ConfigFileType.KeyBindings => KeyBindingsConfiguration.CurrentUserKeybindingsPath,
+            _ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
+        };
+
+        try
+        {
+            if (string.IsNullOrWhiteSpace(path))
+            {
+                return await TrySaveLocal();
+            }
+
+            CleanupOldConfigPath();
+            await JsonFileHelper.WriteJsonAsync(path, value, inputType, context).ConfigureAwait(false);
+
+            return path;
+
+        }
+        catch (UnauthorizedAccessException)
+        {
+            // If unauthorized, try saving to roaming app data
+            try
+            {
+                return await TrySaveRoaming();
+            }
+            catch (Exception ex)
+            {
+                DebugHelper.LogDebug(nameof(ConfigFileManager), nameof(SaveConfigFileAndReturnPathAsync), ex);
+                return null;
+            }
+        }
+        catch (Exception ex)
+        {
+            DebugHelper.LogDebug(nameof(ConfigFileManager), nameof(SaveConfigFileAndReturnPathAsync), ex);
+            return null;
+        }
+
+        async Task<string> TrySaveRoaming()
+        {
+            var roamingPath = type switch
+            {
+                ConfigFileType.UserSettings => SettingsConfiguration.RoamingSettingsPath,
+                ConfigFileType.FileHistory => FileHistoryConfiguration.RoamingFileHistoryPath,
+                ConfigFileType.KeyBindings => KeyBindingsConfiguration.RoamingKeybindingsPath,
+                _ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
+            };
+            
+            FileHelper.EnsureDirectoryExists(roamingPath);
+            await JsonFileHelper.WriteJsonAsync(roamingPath, value, inputType, context).ConfigureAwait(false);
+            
+            return roamingPath;
+        }
+        
+        async Task<string> TrySaveLocal()
+        {
+            var localPath = type switch
+            {
+                ConfigFileType.UserSettings => SettingsConfiguration.LocalSettingsPath,
+                ConfigFileType.FileHistory => FileHistoryConfiguration.LocalFileHistoryPath,
+                ConfigFileType.KeyBindings => KeyBindingsConfiguration.LocalKeybindingsPath,
+                _ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
+            };
+
+            if (type is ConfigFileType.KeyBindings)
+            {
+                File.Create(localPath);
+            }
+            else
+            {
+                await JsonFileHelper.WriteJsonAsync(localPath, value, inputType, context).ConfigureAwait(false);
+            }
+
+            
+            return localPath;
+        }
+
+        // TODO delete this after next release
+        void CleanupOldConfigPath()
+        {
+            if (!File.Exists(SettingsConfiguration.OldLocalSettingsPath))
+            {
+                return;
+            }
+
+            File.Delete(SettingsConfiguration.OldLocalSettingsPath);
+            
+            var firstDirectory = Path.GetDirectoryName(SettingsConfiguration.OldLocalSettingsPath);
+            if (Directory.Exists(firstDirectory))
+            {
+                Directory.Delete(firstDirectory);
+            }
+            var secondDirectory = Path.GetDirectoryName(firstDirectory);
+            if (Directory.Exists(secondDirectory))
+            {
+                Directory.Delete(secondDirectory);
+            }
+            var thirdDirectory = Path.GetDirectoryName(secondDirectory);
+            if (Directory.Exists(thirdDirectory))
+            {
+                Directory.Delete(thirdDirectory);
+            }
+
+            path = SettingsConfiguration.LocalSettingsPath;
+        }
+    }
+
+    public static string TryGetConfigFilePath(ConfigFileType type)
+    {
+        // On macOS, always use the roaming path. We can't save inside an app bundle.
+        if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
+        {
+            return type switch
+            {
+                // If null, try to get the current user file, if exist
+                ConfigFileType.UserSettings => SettingsConfiguration.RoamingSettingsPath,
+                ConfigFileType.FileHistory => FileHistoryConfiguration.RoamingFileHistoryPath,
+                ConfigFileType.KeyBindings => KeyBindingsConfiguration.RoamingKeybindingsPath,
+                _ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
+            };
+        }
+        var path = type switch
+        {
+            // If null, try to get the current user file, if exist
+            ConfigFileType.UserSettings => SettingsConfiguration.CurrentUserSettingsPath,
+            ConfigFileType.FileHistory => FileHistoryConfiguration.CurrentUserFileHistoryPath,
+            ConfigFileType.KeyBindings => KeyBindingsConfiguration.CurrentUserKeybindingsPath,
+            _ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
+        };
+        
+        return path.Replace("/", "\\");
+    }
+}

+ 3 - 3
src/PicView.Core/Config/SettingsConfiguration.cs

@@ -13,14 +13,14 @@ public static class SettingsConfiguration
             ConfigPath);
     
     // TODO delete this after next release
-    public static string BadLocalSettingsPath =>
+    public static string OldLocalSettingsPath =>
         Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigPath);
     
     public static string LocalSettingsPath =>
         Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", ConfigFileName);
 
-    public static string UserSettingsPath =>
+    public static string CurrentUserSettingsPath =>
         File.Exists(RoamingSettingsPath) ? RoamingSettingsPath :
         File.Exists(LocalSettingsPath) ? LocalSettingsPath : 
-        File.Exists(BadLocalSettingsPath) ? BadLocalSettingsPath : string.Empty;
+        File.Exists(OldLocalSettingsPath) ? OldLocalSettingsPath : string.Empty;
 }

+ 19 - 160
src/PicView.Core/Config/SettingsManager.cs

@@ -4,6 +4,7 @@ using System.Runtime.InteropServices;
 using System.Text.Json;
 using System.Text.Json.Serialization;
 using PicView.Core.DebugTools;
+using PicView.Core.FileHandling;
 
 namespace PicView.Core.Config;
 
@@ -16,38 +17,20 @@ internal partial class SettingsGenerationContext : JsonSerializerContext;
 /// </summary>
 public static class SettingsManager
 {
-    /// Gets the file path of the currently loaded settings.
-    /// This property represents the path to the settings file that was most recently
-    /// loaded into the application. If no settings file has been loaded, this property
-    /// will return null.
-    /// This value is updated whenever settings are read from a file, and it is used as
-    /// the default path for saving settings back to a file. The path is normalized to use
-    /// backslashes as directory separators.
-    /// This property is read-only and can only be set internally within the `SettingsManager`
-    /// class.
     public static string? CurrentSettingsPath { get; private set; }
 
-    /// Gets or sets the current application settings.
-    /// This property holds the application's configuration settings encapsulated in an `AppSettings` instance.
-    /// It is updated when settings are loaded, either from a file using `LoadSettingsAsync` or by setting default
-    /// values with the `SetDefaults` method.
-    /// Changes made to this property will affect the behavior and appearance of the application during runtime.
-    /// This property is managed internally within the `SettingsManager` class and cannot be set externally.
     public static AppSettings? Settings { get; private set; }
     
     public static async Task<bool> LoadSettingsAsync()
     {
         try
         {
-            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-            {
-                return await LoadFromPathAsync(SettingsConfiguration.RoamingSettingsPath).ConfigureAwait(false);
-            }
-
-            var path = SettingsConfiguration.UserSettingsPath;
+            var path = ConfigFileManager.TryGetConfigFilePath(ConfigFileType.UserSettings);
             if (!string.IsNullOrEmpty(path))
             {
-                return await LoadFromPathAsync(path).ConfigureAwait(false);
+                CurrentSettingsPath = path;
+                await ReadSettingsFromPathAsync(path).ConfigureAwait(false);
+                return true;
             }
 
             SetDefaults();
@@ -124,45 +107,7 @@ public static class SettingsManager
             }
         }
     }
-
-    /// <summary>
-    ///     Loads settings from the specified path
-    /// </summary>
-    private static async Task<bool> LoadFromPathAsync(string path)
-    {
-        try
-        {
-            await ReadSettingsFromPathAsync(path).ConfigureAwait(false);
-            return true;
-        }
-        catch (Exception)
-        {
-            // If primary path fails, try the alternative path
-            var alternativePath = Path.GetDirectoryName(path)?.Contains("ApplicationData") == true
-                ? SettingsConfiguration.LocalSettingsPath
-                : SettingsConfiguration.RoamingSettingsPath;
-
-            if (File.Exists(alternativePath))
-            {
-                try
-                {
-                    await ReadSettingsFromPathAsync(alternativePath).ConfigureAwait(false);
-                    return true;
-                }
-                catch (Exception)
-                {
-                    SetDefaults();
-                }
-            }
-            else
-            {
-                SetDefaults();
-            }
-
-            return false;
-        }
-    }
-
+    
     /// <summary>
     /// Reads and deserializes the settings from the specified file path asynchronously.
     /// </summary>
@@ -204,108 +149,15 @@ public static class SettingsManager
             return false;
         }
 
-        try
-        {
-            if (string.IsNullOrWhiteSpace(CurrentSettingsPath))
-            {
-                return await TrySaveLocal();
-            }
-
-            DeleteBadPath();
-            await SaveSettingsToPathAsync(CurrentSettingsPath).ConfigureAwait(false);
-
-            return true;
-
-        }
-        catch (UnauthorizedAccessException)
-        {
-            // If unauthorized, try saving to roaming app data
-            try
-            {
-                return await TrySaveRoaming();
-            }
-            catch (Exception ex)
-            {
-                DebugHelper.LogDebug(nameof(SettingsManager), nameof(SaveSettingsAsync), ex);
-                return false;
-            }
-        }
-        catch (Exception ex)
+        var saveLocation = await SaveConfigFileAndReturnPathAsync();
+        if (string.IsNullOrWhiteSpace(saveLocation))
         {
-            DebugHelper.LogDebug(nameof(SettingsManager), nameof(SaveSettingsAsync), ex);
+            DebugHelper.LogDebug(nameof(SettingsManager), nameof(SaveSettingsAsync), "Empty save location");
             return false;
         }
 
-        async Task<bool> TrySaveRoaming()
-        {
-            var roamingPath = SettingsConfiguration.RoamingSettingsPath;
-            EnsureDirectoryExists(roamingPath);
-            await SaveSettingsToPathAsync(roamingPath).ConfigureAwait(false);
-            return true;
-        }
-        
-        async Task<bool> TrySaveLocal()
-        {
-            var localPath = SettingsConfiguration.LocalSettingsPath;
-            EnsureDirectoryExists(localPath);
-            await SaveSettingsToPathAsync(localPath).ConfigureAwait(false);
-            return true;
-        }
-
-        // TODO delete this after next release
-        void DeleteBadPath()
-        {
-            if (!File.Exists(SettingsConfiguration.BadLocalSettingsPath))
-            {
-                return;
-            }
-
-            File.Delete(SettingsConfiguration.BadLocalSettingsPath);
-            
-            var firstDirectory = Path.GetDirectoryName(SettingsConfiguration.BadLocalSettingsPath);
-            if (Directory.Exists(firstDirectory))
-            {
-                Directory.Delete(firstDirectory);
-            }
-            var secondDirectory = Path.GetDirectoryName(firstDirectory);
-            if (Directory.Exists(secondDirectory))
-            {
-                Directory.Delete(secondDirectory);
-            }
-            var thirdDirectory = Path.GetDirectoryName(secondDirectory);
-            if (Directory.Exists(thirdDirectory))
-            {
-                Directory.Delete(thirdDirectory);
-            }
-
-            CurrentSettingsPath = SettingsConfiguration.LocalSettingsPath;
-        }
-    }
-
-    /// <summary>
-    ///     Ensures that the directory for a file path exists
-    /// </summary>
-    private static void EnsureDirectoryExists(string filePath)
-    {
-        var directory = Path.GetDirectoryName(filePath);
-        if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
-        {
-            Directory.CreateDirectory(directory);
-        }
-    }
-
-    /// <summary>
-    ///     Saves settings to the specified path
-    /// </summary>
-    private static async Task SaveSettingsToPathAsync(string path)
-    {
-        if (Settings == null)
-        {
-            return;
-        }
-
-        var json = JsonSerializer.Serialize(Settings, typeof(AppSettings), SettingsGenerationContext.Default);
-        await File.WriteAllTextAsync(path, json).ConfigureAwait(false);
+        CurrentSettingsPath = saveLocation;
+        return true;
     }
 
 
@@ -339,13 +191,20 @@ public static class SettingsManager
 
             // Save the synchronized settings
             Settings = existingSettings;
-            await SaveSettingsToPathAsync(CurrentSettingsPath).ConfigureAwait(false);
+            await WriteJsonAsync();
         }
         catch (Exception ex)
         {
             DebugHelper.LogDebug(nameof(SettingsManager), nameof(SynchronizeSettingsAsync), ex);
         }
     }
+    
+    private static async Task WriteJsonAsync() =>
+        await JsonFileHelper.WriteJsonAsync(CurrentSettingsPath, Settings, typeof(AppSettings), SettingsGenerationContext.Default).ConfigureAwait(false);
+    
+    private static async Task<string?> SaveConfigFileAndReturnPathAsync() =>
+        await ConfigFileManager.SaveConfigFileAndReturnPathAsync(ConfigFileType.UserSettings, CurrentSettingsPath,
+            Settings, typeof(AppSettings), SettingsGenerationContext.Default).ConfigureAwait(false);
 
     private static void MergeObjects<T>(T existing, T defaults) where T : class
     {

+ 12 - 0
src/PicView.Core/FileHandling/FileHelper.cs

@@ -226,4 +226,16 @@ public static partial class FileHelper
             options
         );
     }
+    
+    /// <summary>
+    ///     Ensures that the directory for a file path exists
+    /// </summary>
+    public static void EnsureDirectoryExists(string filePath)
+    {
+        var directory = Path.GetDirectoryName(filePath);
+        if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
+        {
+            Directory.CreateDirectory(directory);
+        }
+    }
 }

+ 20 - 0
src/PicView.Core/FileHandling/JsonFileHelper.cs

@@ -0,0 +1,20 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using PicView.Core.DebugTools;
+
+namespace PicView.Core.FileHandling;
+
+public static class JsonFileHelper
+{
+    public static async Task WriteJsonAsync(string path, object? value, Type inputType, JsonSerializerContext context)
+    {
+        if (value is null || inputType is null || context is null)
+        {
+            DebugHelper.LogDebug(nameof(JsonFileHelper), nameof(WriteJsonAsync), "Types are null");
+            return;
+        }
+
+        var contents = JsonSerializer.Serialize(value, inputType, context);
+        await File.WriteAllTextAsync(path, contents).ConfigureAwait(false);
+    }
+}

+ 8 - 8
src/PicView.Core/FileHistory/FileHistoryConfiguration.cs

@@ -18,14 +18,14 @@ public static class FileHistoryConfiguration
     public const int MaxPinnedEntries = 5;
     
     public const string HistoryFileName = "FileHistory.json";
-    public static string GetHistoryFilePath() => Path.Combine(SettingsConfiguration.ConfigFolder, HistoryFileName);
-    public static string GetRoamingFileHistoryPath() =>
+    public static string HistoryFilePath => Path.Combine(SettingsConfiguration.ConfigFolder, HistoryFileName);
+    public static string RoamingFileHistoryPath =>
         Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
-            GetHistoryFilePath());
+            HistoryFilePath);
     
-    private static string GetLocalFileHistoryPath() =>
-        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, GetHistoryFilePath());
-    public static string GetUserFileHistoryPath() =>
-        File.Exists(GetRoamingFileHistoryPath()) ? GetRoamingFileHistoryPath() :
-        File.Exists(GetLocalFileHistoryPath()) ? GetLocalFileHistoryPath() : string.Empty;
+    public static string LocalFileHistoryPath =>
+        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", HistoryFileName);
+    public static string CurrentUserFileHistoryPath =>
+        File.Exists(RoamingFileHistoryPath) ? RoamingFileHistoryPath :
+        File.Exists(LocalFileHistoryPath) ? LocalFileHistoryPath : string.Empty;
 }

+ 11 - 78
src/PicView.Core/FileHistory/FileHistoryManager.cs

@@ -1,7 +1,7 @@
-using System.Runtime.InteropServices;
-using System.Text.Json;
+using System.Text.Json;
 using System.Text.Json.Serialization;
 using PicView.Core.ArchiveHandling;
+using PicView.Core.Config;
 using PicView.Core.DebugTools;
 using PicView.Core.FileHandling;
 
@@ -73,73 +73,13 @@ public static class FileHistoryManager
     /// </summary>
     public static async Task InitializeAsync()
     {
-        var path = FileHistoryConfiguration.GetUserFileHistoryPath();
-        if (!File.Exists(path))
-        {
-            await CreateFileAsync().ConfigureAwait(false);
-        }
-        else
-        {
-            _fileLocation = path;
-        }
+        _fileLocation = ConfigFileManager.TryGetConfigFilePath(ConfigFileType.FileHistory);
         await LoadFromFileAsync().ConfigureAwait(false);
         
         // Set the current index to the most recent entry.
         CurrentIndex = Count > 0 ? Count - 1 : -1;
     }
 
-    private static async Task CreateFileAsync()
-    {
-        // On macOS, always use roaming path.
-        if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-        {
-            _fileLocation = FileHistoryConfiguration.GetRoamingFileHistoryPath();
-            try
-            {
-                await Create();
-            }
-            catch (Exception e)
-            {
-                DebugHelper.LogDebug(nameof(FileHistoryManager), nameof(CreateFileAsync), e);
-                throw;
-            }
-        }
-        else
-        {
-            try
-            {
-                _fileLocation = FileHistoryConfiguration.GetUserFileHistoryPath();
-                await Create();
-            }
-            catch (Exception)
-            {
-                _fileLocation = FileHistoryConfiguration.GetRoamingFileHistoryPath();
-                try
-                {
-                    await Create();
-                }
-                catch (Exception exception)
-                {
-                    DebugHelper.LogDebug(nameof(FileHistoryManager), nameof(CreateFileAsync), exception);
-                }
-            }
-        }
-
-        return;
-
-        async Task Create()
-        {
-            var directory = Path.GetDirectoryName(_fileLocation);
-            if (directory != null && !Directory.Exists(directory))
-            {
-                Directory.CreateDirectory(directory);
-            }
-
-            await using var fs = File.Create(_fileLocation);
-            fs.Seek(0, SeekOrigin.Begin);
-        }
-    }
-
     /// <summary>
     ///     Pins a file entry in history.
     /// </summary>
@@ -194,7 +134,7 @@ public static class FileHistoryManager
 
         if (existingIndex >= 0)
         {
-            // If entry already exists, just update current index to point to it.
+            // If entry already exists, update the current index to point to it.
             CurrentIndex = existingIndex;
             return;
         }
@@ -214,7 +154,7 @@ public static class FileHistoryManager
 
                 Entries.RemoveAt(i);
 
-                // Adjust current index since we removed an item.
+                // Adjust the current index since we removed an item.
                 if (CurrentIndex > i)
                 {
                     CurrentIndex--;
@@ -372,9 +312,9 @@ public static class FileHistoryManager
     {
         try
         {
-            if (_fileLocation == null)
+            if (string.IsNullOrWhiteSpace(_fileLocation))
             {
-                return;
+                _fileLocation = ConfigFileManager.TryGetConfigFilePath(ConfigFileType.FileHistory);
             }
 
             // Create a new sorted list with pinned entries first (max 5), then unpinned entries (max MaxHistoryEntries)
@@ -391,9 +331,8 @@ public static class FileHistoryManager
                 Entries = sortedEntries,
                 IsSortingDescending = IsSortingDescending
             };
-            var json = JsonSerializer.Serialize(historyEntries, typeof(FileHistoryEntries),
-                FileHistoryGenerationContext.Default);
-            await File.WriteAllTextAsync(_fileLocation, json).ConfigureAwait(false);
+            _fileLocation = await ConfigFileManager.SaveConfigFileAndReturnPathAsync(ConfigFileType.FileHistory,
+                _fileLocation, historyEntries, typeof(FileHistoryEntries), FileHistoryGenerationContext.Default);
         }
         catch (Exception ex)
         {
@@ -404,17 +343,11 @@ public static class FileHistoryManager
     /// <summary>
     ///     Loads the history from the history file.
     /// </summary>
-    private static async Task LoadFromFileAsync(string? path = null)
+    private static async Task LoadFromFileAsync()
     {
         try
         {
-            var loadPath = path ?? _fileLocation;
-            if (string.IsNullOrEmpty(loadPath) || !File.Exists(loadPath))
-            {
-                return;
-            }
-
-            var jsonString = await File.ReadAllTextAsync(loadPath).ConfigureAwait(false);
+            var jsonString = await File.ReadAllTextAsync(_fileLocation).ConfigureAwait(false);
 
             if (JsonSerializer.Deserialize(jsonString, typeof(FileHistoryEntries),
                     FileHistoryGenerationContext.Default)

+ 19 - 0
src/PicView.Core/Keybindings/KeyBindingsConfiguration.cs

@@ -0,0 +1,19 @@
+using PicView.Core.Config;
+
+namespace PicView.Core.Keybindings;
+
+public static class KeyBindingsConfiguration
+{
+    public const string KeybindingsFileName = "keybindings.json";
+    public static string KeybindingsFilePath => Path.Combine(SettingsConfiguration.ConfigFolder, KeybindingsFileName);
+    public static string RoamingKeybindingsPath =>
+        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
+            KeybindingsFilePath);
+    
+    public static string LocalKeybindingsPath =>
+        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", KeybindingsFileName);
+    
+    public static string CurrentUserKeybindingsPath =>
+        File.Exists(RoamingKeybindingsPath) ? RoamingKeybindingsPath :
+        File.Exists(LocalKeybindingsPath) ? LocalKeybindingsPath : string.Empty;
+}

+ 17 - 39
src/PicView.Core/Keybindings/KeybindingFunctions.cs

@@ -1,60 +1,38 @@
-using System.Runtime.InteropServices;
+using PicView.Core.Config;
 
 namespace PicView.Core.Keybindings;
 
 public static class KeybindingFunctions
 {
-    private static string? _currentKeybindingsPath;
-    public static string? CurrentKeybindingsPath
-    {
-        get
-        {
-            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
-            {
-                return _currentKeybindingsPath.Replace("/", "\\");;
-            }
-            return _currentKeybindingsPath;
-        }
-    }
+    public static string? CurrentKeybindingsPath { get; private set; }
+    
     public static async Task SaveKeyBindingsFile(string json)
     {
         try
         {
-            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config/keybindings.json");
-            await using var writer = new StreamWriter(path);
+            await using var writer = new StreamWriter(CurrentKeybindingsPath);
             await writer.WriteAsync(json).ConfigureAwait(false);
         }
-        catch (Exception)
+        catch (UnauthorizedAccessException)
         {
-            var newPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Ruben2776/PicView/Config/keybindings.json");
-            if (!File.Exists(newPath))
-            {
-                var fileInfo = new FileInfo(newPath);
-                fileInfo.Directory?.Create();
-            }
-            await using var newWriter = new StreamWriter(newPath);
-            await newWriter.WriteAsync(json).ConfigureAwait(false);
+            await using var writer = new StreamWriter(KeyBindingsConfiguration.RoamingKeybindingsPath);
+            await writer.WriteAsync(json).ConfigureAwait(false);
         }
     }
 
-    public static async Task<string> LoadKeyBindingsFile()
+    public static async Task<string?> LoadKeyBindingsFile()
     {
-        var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config/keybindings.json");
-        if (File.Exists(path))
+        var path = ConfigFileManager.TryGetConfigFilePath(ConfigFileType.KeyBindings);
+        if (!File.Exists(path))
         {
-            var text = await File.ReadAllTextAsync(path).ConfigureAwait(false);
-            _currentKeybindingsPath = path;
-            return text;
+            return null;
         }
 
-        var newPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Ruben2776/PicView/Config/keybindings.json");
-        if (File.Exists(newPath))
-        {
-            var text = await File.ReadAllTextAsync(newPath).ConfigureAwait(false);
-            _currentKeybindingsPath = newPath;
-            return text;
-        }
-
-        throw new FileNotFoundException();
+        var text = await File.ReadAllTextAsync(path).ConfigureAwait(false);
+        
+        CurrentKeybindingsPath = path;
+        return text;
     }
+
+
 }