From ad9b40bb07526c25272c044c6f22d9cfa173540d Mon Sep 17 00:00:00 2001 From: Adrien Allard Date: Tue, 12 Mar 2019 18:41:36 +0100 Subject: [PATCH] Rework settings service. --- Application/FileConverter/Application.xaml.cs | 16 +- .../FileConverter/FileConverter.csproj | 1 - .../Properties/Settings.Designer.cs | 2 +- .../Services/ISettingsService.cs | 6 + .../SettingsService.Migration.cs} | 15 +- .../FileConverter/Services/SettingsService.cs | 430 +++++++++++- .../FileConverter/Settings.Settings.cs | 210 ------ Application/FileConverter/Settings.cs | 633 ++++++------------ .../ViewModels/SettingsViewModel.cs | 2 +- 9 files changed, 657 insertions(+), 658 deletions(-) rename Application/FileConverter/{Settings.Migration.cs => Services/SettingsService.Migration.cs} (84%) delete mode 100644 Application/FileConverter/Settings.Settings.cs diff --git a/Application/FileConverter/Application.xaml.cs b/Application/FileConverter/Application.xaml.cs index 41776b7..54ea771 100644 --- a/Application/FileConverter/Application.xaml.cs +++ b/Application/FileConverter/Application.xaml.cs @@ -18,6 +18,7 @@ namespace FileConverter using System; using System.Collections.Generic; using System.Diagnostics; + using System.Security.Principal; using System.Threading; using System.Windows; @@ -49,6 +50,14 @@ namespace FileConverter public static Version ApplicationVersion => Application.Version; + public static bool IsInAdmininstratorPrivileges + { + get + { + return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); + } + } + public void CancelAutoExit() { this.cancelAutoExit = true; @@ -228,6 +237,8 @@ namespace FileConverter return; } + ISettingsService settingsService = SimpleIoc.Default.GetInstance(); + // Parse arguments. List filePaths = new List(); string conversionPresetName = null; @@ -247,7 +258,7 @@ namespace FileConverter switch (parameterTitle) { case "post-install-init": - Settings.PostInstallationInitialization(); + settingsService.PostInstallationInitialization(); Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); return; @@ -261,7 +272,7 @@ namespace FileConverter break; case "apply-settings": - Settings.ApplyTemporarySettings(); + settingsService.ApplyTemporarySettings(); Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown())); return; @@ -295,7 +306,6 @@ namespace FileConverter } } - ISettingsService settingsService = SimpleIoc.Default.GetInstance(); if (settingsService.Settings == null) { Diagnostics.Debug.LogError("The application will now shutdown. If you want to fix the problem yourself please edit or delete the file: C:\\Users\\UserName\\AppData\\Local\\FileConverter\\Settings.user.xml."); diff --git a/Application/FileConverter/FileConverter.csproj b/Application/FileConverter/FileConverter.csproj index 9d22af4..20ddd59 100644 --- a/Application/FileConverter/FileConverter.csproj +++ b/Application/FileConverter/FileConverter.csproj @@ -189,7 +189,6 @@ - diff --git a/Application/FileConverter/Properties/Settings.Designer.cs b/Application/FileConverter/Properties/Settings.Designer.cs index 91876a2..eeccaf4 100644 --- a/Application/FileConverter/Properties/Settings.Designer.cs +++ b/Application/FileConverter/Properties/Settings.Designer.cs @@ -12,7 +12,7 @@ namespace FileConverter.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.8.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); diff --git a/Application/FileConverter/Services/ISettingsService.cs b/Application/FileConverter/Services/ISettingsService.cs index 84ed632..acbf016 100644 --- a/Application/FileConverter/Services/ISettingsService.cs +++ b/Application/FileConverter/Services/ISettingsService.cs @@ -9,6 +9,12 @@ namespace FileConverter.Services get; } + void PostInstallationInitialization(); + + void ApplyTemporarySettings(); + + void SaveSettings(); + void RevertSettings(); } } diff --git a/Application/FileConverter/Settings.Migration.cs b/Application/FileConverter/Services/SettingsService.Migration.cs similarity index 84% rename from Application/FileConverter/Settings.Migration.cs rename to Application/FileConverter/Services/SettingsService.Migration.cs index 0bfb3e6..d993c2d 100644 --- a/Application/FileConverter/Settings.Migration.cs +++ b/Application/FileConverter/Services/SettingsService.Migration.cs @@ -1,14 +1,13 @@ -// // License: http://www.gnu.org/licenses/gpl.html GPL version 3. +// License: http://www.gnu.org/licenses/gpl.html GPL version 3. -namespace FileConverter +namespace FileConverter.Services { using System; - using FileConverter.ConversionJobs; - public partial class Settings + public partial class SettingsService { - private static void MigrateSettingsToCurrentVersion(Settings settings) + private void MigrateSettingsToCurrentVersion(Settings settings) { int settingsVersion = settings.SerializationVersion; @@ -17,12 +16,12 @@ namespace FileConverter { foreach (ConversionPreset conversionPreset in settings.ConversionPresets) { - Settings.MigrateConversionPresetToCurrentVersion(conversionPreset, settingsVersion); + this.MigrateConversionPresetToCurrentVersion(conversionPreset, settingsVersion); } } } - private static void MigrateConversionPresetToCurrentVersion(ConversionPreset preset, int settingsVersion) + private void MigrateConversionPresetToCurrentVersion(ConversionPreset preset, int settingsVersion) { if (settingsVersion <= 2) { @@ -72,4 +71,4 @@ namespace FileConverter } } } -} \ No newline at end of file +} diff --git a/Application/FileConverter/Services/SettingsService.cs b/Application/FileConverter/Services/SettingsService.cs index 8040aec..c2085f2 100644 --- a/Application/FileConverter/Services/SettingsService.cs +++ b/Application/FileConverter/Services/SettingsService.cs @@ -2,18 +2,29 @@ namespace FileConverter.Services { - using FileConverter.Diagnostics; + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Reflection; + using System.Windows; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Ioc; - public class SettingsService : ObservableObject, ISettingsService + using Microsoft.Win32; + + using Debug = FileConverter.Diagnostics.Debug; + + public partial class SettingsService : ObservableObject, ISettingsService { + private const char PresetSeparator = ';'; + public SettingsService() { // Load settigns. Debug.Log("Load settings..."); - this.Settings = Settings.Load(); + this.Settings = this.Load(); SimpleIoc.Default.Register(() => this); } @@ -24,10 +35,421 @@ namespace FileConverter.Services private set; } + private string DefaultSettingsFilePath + { + get + { + string path = Assembly.GetEntryAssembly().Location; + path = Path.GetDirectoryName(path); + + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + + path = Path.Combine(path, "Settings.default.xml"); + return path; + } + } + + private string UserSettingsFilePath + { + get + { + string path = PathHelpers.GetUserDataFolderPath(); + path = Path.Combine(path, "Settings.user.xml"); + return path; + } + } + + private string UserSettingsTemporaryFilePath + { + get + { + string path = PathHelpers.GetUserDataFolderPath(); + path = Path.Combine(path, "Settings.temp.xml"); + return path; + } + } + + public void PostInstallationInitialization() + { + Settings defaultSettings = null; + + // Load the default settings. + if (File.Exists(this.DefaultSettingsFilePath)) + { + try + { + XmlHelpers.LoadFromFile("Settings", this.DefaultSettingsFilePath, out defaultSettings); + } + catch (Exception exception) + { + Debug.LogError("Fail to load file converter default settings. {0}", exception.Message); + } + } + else + { + Debug.LogError("Default settings not found at path {0}. You should try to reinstall the application.", this.DefaultSettingsFilePath); + } + + // Load user settings if exists. + Settings userSettings = null; + if (File.Exists(this.UserSettingsFilePath)) + { + try + { + XmlHelpers.LoadFromFile("Settings", this.UserSettingsFilePath, out userSettings); + } + catch (Exception) + { + File.Delete(this.UserSettingsFilePath); + } + + if (userSettings != null) + { + if (userSettings.SerializationVersion != Settings.Version) + { + this.MigrateSettingsToCurrentVersion(userSettings); + + Debug.Log("File converter settings have been imported from version {0} to version {1}.", userSettings.SerializationVersion, Settings.Version); + userSettings.SerializationVersion = Settings.Version; + } + + // Remove default settings. + if (userSettings.ConversionPresets != null) + { + for (int index = userSettings.ConversionPresets.Count - 1; index >= 0; index--) + { + if (userSettings.ConversionPresets[index].IsDefaultSettings) + { + userSettings.ConversionPresets.RemoveAt(index); + } + } + } + } + } + + Settings settings = userSettings != null ? userSettings.Merge(defaultSettings) : defaultSettings; + this.Save(settings); + } + + public void ApplyTemporarySettings() + { + // Load temporary settings. + if (!File.Exists(this.UserSettingsTemporaryFilePath)) + { + return; + } + + Settings settings = null; + XmlHelpers.LoadFromFile("Settings", this.UserSettingsTemporaryFilePath, out settings); + + RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\FileConverter"); + if (registryKey == null) + { + Debug.LogError("Can't apply settings in registry. (code 0x03)"); + return; + } + + // Compute the registry entries data from settings. + Dictionary> registryEntries = ComputeRegistryEntriesFromConversionPresets(settings.ConversionPresets); + + bool succeed = this.ApplyRegistryModifications(registryEntries); + + if (succeed) + { + // Copy temporary settings file to the real settings file. + File.Copy(this.UserSettingsTemporaryFilePath, this.UserSettingsFilePath, true); + File.Delete(this.UserSettingsTemporaryFilePath); + } + } + + public void SaveSettings() + { + this.Save(this.Settings); + } + public void RevertSettings() { // Load previous preset in order to cancel changes. - this.Settings = Settings.Load(); + this.Settings = this.Load(); } + + private Settings Load() + { + Settings settings = null; + if (File.Exists(this.UserSettingsFilePath)) + { + Settings userSettings = null; + try + { + XmlHelpers.LoadFromFile("Settings", this.UserSettingsFilePath, out userSettings); + settings = userSettings; + } + catch (Exception) + { + MessageBoxResult messageBoxResult = + MessageBox.Show( + "Can't load file converter user settings. Do you want to fall back to default settings ?", + "Error", + MessageBoxButton.YesNo, + MessageBoxImage.Exclamation); + + if (messageBoxResult == MessageBoxResult.Yes) + { + File.Delete(this.UserSettingsFilePath); + return this.Load(); + } + else if (messageBoxResult == MessageBoxResult.No) + { + return null; + } + } + + if (userSettings != null && userSettings.SerializationVersion != Settings.Version) + { + this.MigrateSettingsToCurrentVersion(userSettings); + + Diagnostics.Debug.Log("File converter settings has been imported from version {0} to version {1}.", userSettings.SerializationVersion, Settings.Version); + userSettings.SerializationVersion = Settings.Version; + this.Save(userSettings); + } + } + else + { + // Load the default settings. + if (File.Exists(this.DefaultSettingsFilePath)) + { + Settings defaultSettings = null; + try + { + XmlHelpers.LoadFromFile("Settings", this.DefaultSettingsFilePath, out defaultSettings); + settings = defaultSettings; + } + catch (Exception exception) + { + Debug.LogError("Fail to load file converter default settings. {0}", exception.Message); + } + } + else + { + Debug.LogError("Default settings not found at path {0}. You should try to reinstall the application.", this.DefaultSettingsFilePath); + } + } + + return settings; + } + + private void Save(Settings settings) + { + if (settings == null) + { + throw new ArgumentNullException(nameof(settings)); + } + + settings.Clean(); + + // Save the settings in a temporary files (we'll write the settings file when we'll succeed to write the registry keys). + XmlHelpers.SaveToFile("Settings", this.UserSettingsTemporaryFilePath, settings); + + // Compute the registry entries data from settings. + Dictionary> registryEntries = ComputeRegistryEntriesFromConversionPresets(settings.ConversionPresets); + + // Detect if existing registry configuration need to be modified. + bool registryNeedModifications = this.DoesRegistryNeedModifications(registryEntries); + + if (registryNeedModifications) + { + // Write the settings in registry. + bool succeed = this.ApplyRegistryModifications(registryEntries); + if (succeed) + { + // ... and copy temporary settings file to the real settings file. + File.Copy(this.UserSettingsTemporaryFilePath, this.UserSettingsFilePath, true); + File.Delete(this.UserSettingsTemporaryFilePath); + } + else + { + if (!FileConverter.Application.IsInAdmininstratorPrivileges) + { + // Run the application in admin mode in order to perform modifications. + Debug.Log("Can't apply registry modifications, fallback to admin privileges."); + this.RunSaveInAdminMode(); + } + else + { + MessageBox.Show("Can't apply settings in registry. (code 0x09)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + } + } + } + else + { + // Copy temporary settings file to the real settings file. + File.Copy(this.UserSettingsTemporaryFilePath, this.UserSettingsFilePath, true); + File.Delete(this.UserSettingsTemporaryFilePath); + } + } + + private void RunSaveInAdminMode() + { + ProcessStartInfo processStartInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().Location, "--apply-settings") + { + UseShellExecute = true, + Verb = "runas", // indicates to elevate privileges + }; + + Process process = new Process + { + EnableRaisingEvents = true, // enable WaitForExit() + StartInfo = processStartInfo + }; + + try + { + process.Start(); + process.WaitForExit(); + } + catch (Exception) + { + MessageBox.Show("Can't apply settings in registry because the application has no administrator privileges. (code 0x08)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + return; + } + } + + private bool DoesRegistryNeedModifications(Dictionary> registryEntries) + { + // Compare to registry entries. + RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\FileConverter"); + if (registryKey == null) + { + return true; + } + + string[] subKeyNames = registryKey.GetSubKeyNames(); + if (subKeyNames.Length == registryEntries.Count) + { + for (int index = 0; index < subKeyNames.Length; index++) + { + string subKeyName = subKeyNames[index]; + if (!registryEntries.ContainsKey(subKeyName)) + { + return true; + } + + List presetsList = registryEntries[subKeyName]; + + RegistryKey subKey = registryKey.OpenSubKey(subKeyName); + if (subKey == null) + { + return true; + } + + string presetsString = subKey.GetValue("Presets", string.Empty) as string; + string[] presets = presetsString != null ? presetsString.Split(PresetSeparator) : new string[0]; + if (presets.Length != presetsList.Count) + { + return true; + } + + for (int presetIndex = 0; presetIndex < presets.Length; presetIndex++) + { + if (presetsList[presetIndex] != presets[presetIndex]) + { + return true; + } + } + } + } + else + { + return true; + } + + return false; + } + + private bool ApplyRegistryModifications(Dictionary> registryEntries) + { + RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\FileConverter", RegistryKeyPermissionCheck.ReadWriteSubTree); + if (registryKey == null) + { + MessageBox.Show("Can't apply settings in registry. (code 0x05)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + return false; + } + + // Delete previous settings. + string[] subKeyNames = registryKey.GetSubKeyNames(); + for (int index = 0; index < subKeyNames.Length; index++) + { + try + { + registryKey.DeleteSubKey(subKeyNames[index]); + } + catch (Exception) + { + MessageBox.Show("Can't apply settings in registry. (code 0x06)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + return false; + } + } + + // Apply settings in registry. + foreach (KeyValuePair> registryEntry in registryEntries) + { + string presets = string.Empty; + for (int index = 0; index < registryEntry.Value.Count; index++) + { + if (index > 0) + { + presets += ";"; + } + + presets += registryEntry.Value[index]; + } + + RegistryKey subKey = null; + try + { + subKey = registryKey.CreateSubKey(registryEntry.Key); + } + catch (Exception exception) + { + Debug.Log(exception.Message); + } + + if (subKey == null) + { + MessageBox.Show("Can't apply settings in registry. (code 0x07)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + return false; + } + + subKey.SetValue("Presets", presets); + } + + return true; + } + + private static Dictionary> ComputeRegistryEntriesFromConversionPresets(ICollection conversionPresets) + { + Dictionary> registryEntries = new Dictionary>(); + + foreach (ConversionPreset conversionPreset in conversionPresets) + { + List inputTypes = conversionPreset.InputTypes; + for (int inputIndex = 0; inputIndex < inputTypes.Count; inputIndex++) + { + string inputType = inputTypes[inputIndex].ToLowerInvariant(); + if (!registryEntries.ContainsKey(inputType)) + { + registryEntries.Add(inputType, new List()); + } + + registryEntries[inputType].Add(conversionPreset.Name); + } + } + + return registryEntries; + } + } } diff --git a/Application/FileConverter/Settings.Settings.cs b/Application/FileConverter/Settings.Settings.cs deleted file mode 100644 index 74760f0..0000000 --- a/Application/FileConverter/Settings.Settings.cs +++ /dev/null @@ -1,210 +0,0 @@ -// License: http://www.gnu.org/licenses/gpl.html GPL version 3. - -namespace FileConverter -{ - using System.Collections.ObjectModel; - using System.Globalization; - using System.Linq; - using System.Xml.Serialization; - - public partial class Settings : IXmlSerializable - { - public const int Version = 4; - - private bool exitApplicationWhenConversionsFinished = true; - private float durationBetweenEndOfConversionsAndApplicationExit = 3f; - private ObservableCollection conversionPresets = new ObservableCollection(); - private bool checkUpgradeAtStartup = true; - private CultureInfo applicationLanguage; - private int maximumNumberOfSimultaneousConversions; - - [XmlAttribute] - public int SerializationVersion - { - get; - set; - } = Version; - - [XmlIgnore] - public CultureInfo ApplicationLanguage - { - get - { - return this.applicationLanguage; - } - - set - { - if (this.applicationLanguage != null && this.applicationLanguage.Equals(value)) - { - return; - } - - this.applicationLanguage = value; - if (this.applicationLanguage != null) - { - System.Threading.Thread.CurrentThread.CurrentCulture = this.applicationLanguage; - System.Threading.Thread.CurrentThread.CurrentUICulture = this.applicationLanguage; - } - - this.OnPropertyChanged(); - } - } - - [XmlElement] - public string ApplicationLanguageName - { - get - { - if (this.ApplicationLanguage == null) - { - return string.Empty; - } - - return this.ApplicationLanguage.Name; - } - - set - { - if (string.IsNullOrEmpty(value)) - { - this.ApplicationLanguage = null; - return; - } - - this.ApplicationLanguage = CultureInfo.GetCultureInfo(value); - } - } - - [XmlIgnore] - public ObservableCollection ConversionPresets - { - get - { - return this.conversionPresets; - } - - set - { - this.conversionPresets = value; - this.OnPropertyChanged(); - } - } - - [XmlElement] - public bool ExitApplicationWhenConversionsFinished - { - get - { - return this.exitApplicationWhenConversionsFinished; - } - - set - { - this.exitApplicationWhenConversionsFinished = value; - this.OnPropertyChanged(); - } - } - - [XmlElement] - public float DurationBetweenEndOfConversionsAndApplicationExit - { - get - { - return this.durationBetweenEndOfConversionsAndApplicationExit; - } - - set - { - this.durationBetweenEndOfConversionsAndApplicationExit = value; - this.OnPropertyChanged(); - } - } - - [XmlElement] - public int MaximumNumberOfSimultaneousConversions - { - get - { - return this.maximumNumberOfSimultaneousConversions; - } - - set - { - this.maximumNumberOfSimultaneousConversions = value; - this.OnPropertyChanged(); - } - } - - [XmlElement("ConversionPreset")] - public ConversionPreset[] SerializableConversionPresets - { - get - { - return this.ConversionPresets.ToArray(); - } - - set - { - for (int index = 0; index < value.Length; index++) - { - this.ConversionPresets.Add(value[index]); - } - } - } - - [XmlElement] - public bool CheckUpgradeAtStartup - { - get - { - return this.checkUpgradeAtStartup; - } - - set - { - this.checkUpgradeAtStartup = value; - this.OnPropertyChanged(); - } - } - - public void OnDeserializationComplete() - { - this.DurationBetweenEndOfConversionsAndApplicationExit = System.Math.Max(0, System.Math.Min(10, this.DurationBetweenEndOfConversionsAndApplicationExit)); - - for (int index = 0; index < this.ConversionPresets.Count; index++) - { - this.ConversionPresets[index].OnDeserializationComplete(); - } - - // Initialize application if it was not deserialized from the settings. - if (this.ApplicationLanguage == null) - { - CultureInfo bestCandidate = null; - CultureInfo currentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; - foreach (CultureInfo culture in Helpers.GetSupportedCultures()) - { - if (culture.Equals(currentUICulture)) - { - bestCandidate = culture; - break; - } - else if (culture.Equals(currentUICulture.Parent)) - { - bestCandidate = culture; - } - } - - if (bestCandidate != null) - { - this.ApplicationLanguage = bestCandidate; - } - else - { - Diagnostics.Debug.Log("Can't find supported culture info for culture {0}. Fallback to default culture.", currentUICulture); - this.ApplicationLanguage = CultureInfo.GetCultureInfo("en"); - } - } - } - } -} diff --git a/Application/FileConverter/Settings.cs b/Application/FileConverter/Settings.cs index c2858c9..48a6b56 100644 --- a/Application/FileConverter/Settings.cs +++ b/Application/FileConverter/Settings.cs @@ -2,28 +2,26 @@ namespace FileConverter { - using System; - using System.Collections.Generic; using System.ComponentModel; - using System.Diagnostics; - using System.IO; using System.Linq; - using System.Reflection; - using System.Runtime.CompilerServices; - using System.Security.Principal; - using System.Windows; using System.Xml.Serialization; + using System.Collections.ObjectModel; + using System.Globalization; - using FileConverter.Annotations; - using Microsoft.Win32; + using GalaSoft.MvvmLight; [XmlRoot] [XmlType] - public partial class Settings : INotifyPropertyChanged, IDataErrorInfo + public class Settings : ObservableObject, IDataErrorInfo, IXmlSerializable { - private const char PresetSeparator = ';'; + public const int Version = 4; - public event PropertyChangedEventHandler PropertyChanged; + private bool exitApplicationWhenConversionsFinished = true; + private float durationBetweenEndOfConversionsAndApplicationExit = 3f; + private ObservableCollection conversionPresets = new ObservableCollection(); + private bool checkUpgradeAtStartup = true; + private CultureInfo applicationLanguage; + private int maximumNumberOfSimultaneousConversions; [XmlIgnore] public string Error @@ -43,14 +41,6 @@ namespace FileConverter } } - private static bool IsInAdmininstratorPrivileges - { - get - { - return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); - } - } - [XmlIgnore] public string this[string columnName] { @@ -59,223 +49,11 @@ namespace FileConverter return this.Error; } } - - public static void ApplyTemporarySettings() - { - // Load temporary settings. - string temporaryFilePath = Settings.GetUserSettingsTemporaryFilePath(); - if (!File.Exists(temporaryFilePath)) - { - return; - } - - Settings settings = null; - XmlHelpers.LoadFromFile("Settings", temporaryFilePath, out settings); - - RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\FileConverter"); - if (registryKey == null) - { - Diagnostics.Debug.LogError("Can't apply settings in registry. (code 0x03)"); - return; - } - - // Compute the registry entries data from settings. - Dictionary> registryEntries = ComputeRegistryEntriesFromConvertionPresets(settings.ConversionPresets); - - bool succeed = Settings.ApplyRegistryModifications(registryEntries); - - if (succeed) - { - // Copy temporary settings file to the real settings file. - string userFilePath = Settings.GetUserSettingsFilePath(); - File.Copy(temporaryFilePath, userFilePath, true); - File.Delete(temporaryFilePath); - } - } - - public static void PostInstallationInitialization() - { - Settings defaultSettings = null; - - // Load the default settings. - string defaultFilePath = Settings.GetDefaultSettingsFilePath(); - if (File.Exists(defaultFilePath)) - { - try - { - XmlHelpers.LoadFromFile("Settings", defaultFilePath, out defaultSettings); - } - catch (Exception exception) - { - Diagnostics.Debug.LogError("Fail to load file converter default settings. {0}", exception.Message); - } - } - else - { - Diagnostics.Debug.LogError("Default settings not found at path {0}. You should try to reinstall the application.", defaultFilePath); - } - - // Load user settings if exists. - Settings userSettings = null; - string userFilePath = Settings.GetUserSettingsFilePath(); - if (File.Exists(userFilePath)) - { - try - { - XmlHelpers.LoadFromFile("Settings", userFilePath, out userSettings); - } - catch (Exception) - { - System.IO.File.Delete(userFilePath); - } - - if (userSettings != null) - { - if (userSettings.SerializationVersion != Version) - { - Settings.MigrateSettingsToCurrentVersion(userSettings); - - Diagnostics.Debug.Log("File converter settings have been imported from version {0} to version {1}.", userSettings.SerializationVersion, Version); - userSettings.SerializationVersion = Version; - } - - // Remove default settings. - if (userSettings.ConversionPresets != null) - { - for (int index = userSettings.ConversionPresets.Count - 1; index >= 0; index--) - { - if (userSettings.ConversionPresets[index].IsDefaultSettings) - { - userSettings.ConversionPresets.RemoveAt(index); - } - } - } - } - } - - Settings settings = userSettings != null ? userSettings.Merge(defaultSettings) : defaultSettings; - settings.Save(); - } - - public static Settings Load() - { - Settings settings = null; - string userFilePath = Settings.GetUserSettingsFilePath(); - if (File.Exists(userFilePath)) - { - Settings userSettings = null; - try - { - XmlHelpers.LoadFromFile("Settings", userFilePath, out userSettings); - settings = userSettings; - } - catch (Exception) - { - MessageBoxResult messageBoxResult = - MessageBox.Show( - "Can't load file converter user settings. Do you want to fall back to default settings ?", - "Error", - MessageBoxButton.YesNo, - MessageBoxImage.Exclamation); - - if (messageBoxResult == MessageBoxResult.Yes) - { - System.IO.File.Delete(userFilePath); - return Settings.Load(); - } - else if (messageBoxResult == MessageBoxResult.No) - { - return null; - } - } - - if (userSettings != null && userSettings.SerializationVersion != Version) - { - Settings.MigrateSettingsToCurrentVersion(userSettings); - - Diagnostics.Debug.Log("File converter settings has been imported from version {0} to version {1}.", userSettings.SerializationVersion, Version); - userSettings.SerializationVersion = Version; - userSettings.Save(); - } - } - else - { - // Load the default settings. - string defaultFilePath = Settings.GetDefaultSettingsFilePath(); - if (File.Exists(defaultFilePath)) - { - Settings defaultSettings = null; - try - { - XmlHelpers.LoadFromFile("Settings", defaultFilePath, out defaultSettings); - settings = defaultSettings; - } - catch (Exception exception) - { - Diagnostics.Debug.LogError("Fail to load file converter default settings. {0}", exception.Message); - } - } - else - { - Diagnostics.Debug.LogError("Default settings not found at path {0}. You should try to reinstall the application.", defaultFilePath); - } - } - - return settings; - } - + public ConversionPreset GetPresetFromName(string presetName) { return this.conversionPresets.FirstOrDefault(match => match.Name == presetName); } - - public void Save() - { - this.Clean(); - - // Save the settings in a temporary files (we'll write the settings file when we'll succeed to write the registry keys). - string temporaryFilePath = Settings.GetUserSettingsTemporaryFilePath(); - XmlHelpers.SaveToFile("Settings", temporaryFilePath, this); - - // Compute the registry entries data from settings. - Dictionary> registryEntries = Settings.ComputeRegistryEntriesFromConvertionPresets(this.ConversionPresets); - - // Detect if existing registry configuration need to be modified. - bool registryNeedModifications = Settings.IsRegistryNeedModifications(registryEntries); - - if (registryNeedModifications) - { - // Write the settings in registry. - bool succeed = Settings.ApplyRegistryModifications(registryEntries); - if (succeed) - { - // ... and copy temporary settings file to the real settings file. - string userFilePath = Settings.GetUserSettingsFilePath(); - File.Copy(temporaryFilePath, userFilePath, true); - File.Delete(temporaryFilePath); - } - else - { - if (!Settings.IsInAdmininstratorPrivileges) - { - // Run the application in admin mode in order to perform modifications. - Diagnostics.Debug.Log("Can't apply registry modifications, fallback to admin privileges."); - Settings.RunSaveInAdminMode(); - } - else - { - MessageBox.Show("Can't apply settings in registry. (code 0x09)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); - } - } - } - else - { - // Copy temporary settings file to the real settings file. - string userFilePath = Settings.GetUserSettingsFilePath(); - File.Copy(temporaryFilePath, userFilePath, true); - File.Delete(temporaryFilePath); - } - } public void Clean() { @@ -284,202 +62,8 @@ namespace FileConverter this.ConversionPresets[index].Clean(); } } - - private static bool ApplyRegistryModifications(Dictionary> registryEntries) - { - RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\FileConverter", RegistryKeyPermissionCheck.ReadWriteSubTree); - if (registryKey == null) - { - MessageBox.Show("Can't apply settings in registry. (code 0x05)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); - return false; - } - - // Delete previous settings. - string[] subKeyNames = registryKey.GetSubKeyNames(); - for (int index = 0; index < subKeyNames.Length; index++) - { - try - { - registryKey.DeleteSubKey(subKeyNames[index]); - } - catch (Exception) - { - MessageBox.Show("Can't apply settings in registry. (code 0x06)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); - return false; - } - } - - // Apply settings in registry. - foreach (KeyValuePair> registryEntry in registryEntries) - { - string presets = string.Empty; - for (int index = 0; index < registryEntry.Value.Count; index++) - { - if (index > 0) - { - presets += ";"; - } - - presets += registryEntry.Value[index]; - } - - RegistryKey subKey = null; - try - { - subKey = registryKey.CreateSubKey(registryEntry.Key); - } - catch (Exception exception) - { - Diagnostics.Debug.Log(exception.Message); - } - - if (subKey == null) - { - MessageBox.Show("Can't apply settings in registry. (code 0x07)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); - return false; - } - - subKey.SetValue("Presets", presets); - } - - return true; - } - - private static Dictionary> ComputeRegistryEntriesFromConvertionPresets(ICollection conversionPresets) - { - Dictionary> registryEntries = new Dictionary>(); - - foreach (ConversionPreset conversionPreset in conversionPresets) - { - List inputTypes = conversionPreset.InputTypes; - for (int inputIndex = 0; inputIndex < inputTypes.Count; inputIndex++) - { - string inputType = inputTypes[inputIndex].ToLowerInvariant(); - if (!registryEntries.ContainsKey(inputType)) - { - registryEntries.Add(inputType, new List()); - } - - registryEntries[inputType].Add(conversionPreset.Name); - } - } - - return registryEntries; - } - - private static string GetDefaultSettingsFilePath() - { - string path = Assembly.GetEntryAssembly().Location; - path = Path.GetDirectoryName(path); - - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - path = Path.Combine(path, "Settings.default.xml"); - return path; - } - - private static string GetUserSettingsFilePath() - { - string path = PathHelpers.GetUserDataFolderPath(); - path = Path.Combine(path, "Settings.user.xml"); - return path; - } - - private static string GetUserSettingsTemporaryFilePath() - { - string path = PathHelpers.GetUserDataFolderPath(); - path = Path.Combine(path, "Settings.temp.xml"); - return path; - } - - private static bool IsRegistryNeedModifications(Dictionary> registryEntries) - { - // Compare to registry entries. - RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\FileConverter"); - if (registryKey == null) - { - return true; - } - - string[] subKeyNames = registryKey.GetSubKeyNames(); - if (subKeyNames.Length == registryEntries.Count) - { - for (int index = 0; index < subKeyNames.Length; index++) - { - string subKeyName = subKeyNames[index]; - if (!registryEntries.ContainsKey(subKeyName)) - { - return true; - } - - List presetsList = registryEntries[subKeyName]; - - RegistryKey subKey = registryKey.OpenSubKey(subKeyName); - if (subKey == null) - { - return true; - } - - string presetsString = subKey.GetValue("Presets", string.Empty) as string; - string[] presets = presetsString != null ? presetsString.Split(Settings.PresetSeparator) : new string[0]; - if (presets.Length != presetsList.Count) - { - return true; - } - - for (int presetIndex = 0; presetIndex < presets.Length; presetIndex++) - { - if (presetsList[presetIndex] != presets[presetIndex]) - { - return true; - } - } - } - } - else - { - return true; - } - - return false; - } - - private static void RunSaveInAdminMode() - { - ProcessStartInfo processStartInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().Location, "--apply-settings") - { - UseShellExecute = true, - Verb = "runas", // indicates to elevate privileges - }; - - Process process = new Process - { - EnableRaisingEvents = true, // enable WaitForExit() - StartInfo = processStartInfo - }; - - try - { - process.Start(); - process.WaitForExit(); - } - catch (Exception) - { - MessageBox.Show("Can't apply settings in registry because the application has no administrator privileges. (code 0x08)", "Error", MessageBoxButton.OK, MessageBoxImage.Error); - return; - } - } - - [NotifyPropertyChangedInvocator] - private void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - - private Settings Merge(Settings settings) + + public Settings Merge(Settings settings) { if (settings == null || settings.conversionPresets == null) { @@ -499,5 +83,194 @@ namespace FileConverter return this; } + + [XmlAttribute] + public int SerializationVersion + { + get; + set; + } = Version; + + [XmlIgnore] + public CultureInfo ApplicationLanguage + { + get + { + return this.applicationLanguage; + } + + set + { + if (this.applicationLanguage != null && this.applicationLanguage.Equals(value)) + { + return; + } + + this.applicationLanguage = value; + if (this.applicationLanguage != null) + { + System.Threading.Thread.CurrentThread.CurrentCulture = this.applicationLanguage; + System.Threading.Thread.CurrentThread.CurrentUICulture = this.applicationLanguage; + } + + this.RaisePropertyChanged(); + } + } + + [XmlElement] + public string ApplicationLanguageName + { + get + { + if (this.ApplicationLanguage == null) + { + return string.Empty; + } + + return this.ApplicationLanguage.Name; + } + + set + { + if (string.IsNullOrEmpty(value)) + { + this.ApplicationLanguage = null; + return; + } + + this.ApplicationLanguage = CultureInfo.GetCultureInfo(value); + } + } + + [XmlIgnore] + public ObservableCollection ConversionPresets + { + get + { + return this.conversionPresets; + } + + set + { + this.conversionPresets = value; + this.RaisePropertyChanged(); + } + } + + [XmlElement] + public bool ExitApplicationWhenConversionsFinished + { + get + { + return this.exitApplicationWhenConversionsFinished; + } + + set + { + this.exitApplicationWhenConversionsFinished = value; + this.RaisePropertyChanged(); + } + } + + [XmlElement] + public float DurationBetweenEndOfConversionsAndApplicationExit + { + get + { + return this.durationBetweenEndOfConversionsAndApplicationExit; + } + + set + { + this.durationBetweenEndOfConversionsAndApplicationExit = value; + this.RaisePropertyChanged(); + } + } + + [XmlElement] + public int MaximumNumberOfSimultaneousConversions + { + get + { + return this.maximumNumberOfSimultaneousConversions; + } + + set + { + this.maximumNumberOfSimultaneousConversions = value; + this.RaisePropertyChanged(); + } + } + + [XmlElement("ConversionPreset")] + public ConversionPreset[] SerializableConversionPresets + { + get + { + return this.ConversionPresets.ToArray(); + } + + set + { + for (int index = 0; index < value.Length; index++) + { + this.ConversionPresets.Add(value[index]); + } + } + } + + [XmlElement] + public bool CheckUpgradeAtStartup + { + get + { + return this.checkUpgradeAtStartup; + } + + set + { + this.checkUpgradeAtStartup = value; + this.RaisePropertyChanged(); + } + } + + public void OnDeserializationComplete() + { + this.DurationBetweenEndOfConversionsAndApplicationExit = System.Math.Max(0, System.Math.Min(10, this.DurationBetweenEndOfConversionsAndApplicationExit)); + + for (int index = 0; index < this.ConversionPresets.Count; index++) + { + this.ConversionPresets[index].OnDeserializationComplete(); + } + + // Initialize application if it was not deserialized from the settings. + if (this.ApplicationLanguage == null) + { + CultureInfo bestCandidate = null; + CultureInfo currentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; + foreach (CultureInfo culture in Helpers.GetSupportedCultures()) + { + if (culture.Equals(currentUICulture)) + { + bestCandidate = culture; + break; + } + else if (culture.Equals(currentUICulture.Parent)) + { + bestCandidate = culture; + } + } + + if (bestCandidate != null) + { + this.ApplicationLanguage = bestCandidate; + } + else + { + Diagnostics.Debug.Log("Can't find supported culture info for culture {0}. Fallback to default culture.", currentUICulture); + this.ApplicationLanguage = CultureInfo.GetCultureInfo("en"); + } + } + } } } diff --git a/Application/FileConverter/ViewModels/SettingsViewModel.cs b/Application/FileConverter/ViewModels/SettingsViewModel.cs index 2d8830c..a930e20 100644 --- a/Application/FileConverter/ViewModels/SettingsViewModel.cs +++ b/Application/FileConverter/ViewModels/SettingsViewModel.cs @@ -368,7 +368,7 @@ namespace FileConverter.ViewModels { // Save changes. ISettingsService settingsService = SimpleIoc.Default.GetInstance(); - settingsService.Settings.Save(); + settingsService.SaveSettings(); INavigationService navigationService = SimpleIoc.Default.GetInstance(); navigationService.Close(Pages.Settings, false);