Refactor application settings

Settings can now contains application specific settings (and not only
conversion preset).
Add options: QuitApplicationWhenConversionsFinished and
DurationBetweenEndOfConversionsAndApplicationQuit
This commit is contained in:
Tichau committed 2015-12-13 08:43:07 +01:00
1 parent 45162328a9
commit 3a2950190f
8 files changed
+207 -87

No files matched your search

+29 -28
View File
@@ -72,7 +72,7 @@ namespace FileConverter
public Settings Settings
{
get;
private set;
set;
}
public bool ShowSettings
@@ -99,8 +99,7 @@ namespace FileConverter
// Load settigns.
Debug.Log("Load settings...");
this.Settings = new Settings();
this.Settings.Load();
this.Settings = Settings.Load();
// Retrieve arguments.
Debug.Log("Retrieve arguments...");
@@ -123,21 +122,22 @@ namespace FileConverter
args[6] = @"D:\Test\Track03.mp3";
args[7] = @"D:\Test\Track04.mp3";
System.Array.Resize(ref args, 2);
args[1] = "--settings";
//System.Array.Resize(ref args, 2);
//args[1] = "--settings";
//System.Array.Resize(ref args, 4);
//System.Array.Resize(ref args, 5);
//args[1] = "--conversion-preset";
//args[2] = "To Ogg";
//args[2] = "To Png";
//args[3] = "--verbose";
//args[4] = @"D:\Test\ApplicationIcon.ico";
//System.Array.Resize(ref args, 6);
//args[1] = "--conversion-preset";
//args[2] = "Extract CDA To Ogg";
//args[3] = "--verbose";
System.Array.Resize(ref args, 6);
args[1] = "--conversion-preset";
args[2] = "Extract CDA To Ogg";
args[3] = "--verbose";
args[4] = @"E:\Track01.cda";
args[5] = @"E:\Track02.cda";
//args[4] = @"E:\Track01.cda";
//args[5] = @"E:\Track02.cda";
}
#endif
@@ -304,25 +304,26 @@ namespace FileConverter
Thread.Sleep(50);
}
#if !DEBUG
bool allConversionsSucceed = true;
for (int index = 0; index < this.conversionJobs.Count; index++)
if (this.Settings.QuitApplicationWhenConversionsFinished)
{
allConversionsSucceed &= this.conversionJobs[index].State == ConversionJob.ConversionState.Done;
}
if (allConversionsSucceed)
{
System.Threading.Thread.Sleep(3000);
if (this.cancelAutoExit)
bool allConversionsSucceed = true;
for (int index = 0; index < this.conversionJobs.Count; index++)
{
return;
allConversionsSucceed &= this.conversionJobs[index].State == ConversionJob.ConversionState.Done;
}
Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown()));
if (allConversionsSucceed)
{
System.Threading.Thread.Sleep((int)this.Settings.DurationBetweenEndOfConversionsAndApplicationQuit * 1000);
if (this.cancelAutoExit)
{
return;
}
Dispatcher.BeginInvoke((Action)(() => Application.Current.Shutdown()));
}
}
#endif
}
private void ExecuteConversionJob(object parameter)
@@ -257,6 +257,24 @@ namespace FileConverter
}
}
public void Clean()
{
// Remove unrelevant settings.
List<string> settingsToRemove = new List<string>();
foreach (string settingsKey in this.settings.Keys)
{
if (!this.IsRelevantSetting(settingsKey))
{
settingsToRemove.Add(settingsKey);
}
}
for (int index = 0; index < settingsToRemove.Count; index++)
{
this.settings.Remove(settingsToRemove[index]);
}
}
public void OnDeserializationComplete()
{
for (int index = 0; index < this.InputTypes.Count; index++)
@@ -431,12 +449,12 @@ namespace FileConverter
{
if (outputType == OutputType.Wav)
{
this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioEncodingMode, EncodingMode.Wav16.ToString());
this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioEncodingMode, EncodingMode.Wav16.ToString(), true);
}
if (outputType == OutputType.Mp3)
{
this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioEncodingMode, EncodingMode.Mp3VBR.ToString());
this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioEncodingMode, EncodingMode.Mp3VBR.ToString(), true);
this.InitializeSettingsValue(ConversionPreset.ConversionSettingKeys.AudioBitrate, "190");
}
@@ -468,7 +486,7 @@ namespace FileConverter
this.OnPropertyChanged("Settings");
}
private void InitializeSettingsValue(string settingsKey, string value)
private void InitializeSettingsValue(string settingsKey, string value, bool force = false)
{
if (string.IsNullOrEmpty(settingsKey))
{
@@ -484,6 +502,10 @@ namespace FileConverter
{
this.settings.Add(settingsKey, value);
}
else if (force)
{
this.settings[settingsKey] = value;
}
}
private string Validate(string propertyName)
@@ -101,6 +101,7 @@
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
</Compile>
<Compile Include="Settings.Settings.cs" />
<Compile Include="ValueConverters\ApplicationVersionToApplicationName.cs" />
<Compile Include="ConversionPreset\ConversionPreset.cs" />
<Compile Include="ValueConverters\BitrateToString.cs" />
@@ -0,0 +1,86 @@
// <copyright file="Settings.Settings.cs" company="AAllard">License: http://www.gnu.org/licenses/gpl.html GPL version 3.</copyright>
using System.Linq;
namespace FileConverter
{
using System.Collections.ObjectModel;
using System.Xml.Serialization;
public partial class Settings : IXmlSerializable
{
private bool quitApplicationWhenConversionsFinished = true;
private float durationBetweenEndOfConversionsAndApplicationQuit = 3f;
private ObservableCollection<ConversionPreset> conversionPresets = new ObservableCollection<ConversionPreset>();
[XmlIgnore]
public ObservableCollection<ConversionPreset> ConversionPresets
{
get
{
return this.conversionPresets;
}
set
{
this.conversionPresets = value;
this.OnPropertyChanged();
}
}
[XmlElement]
public bool QuitApplicationWhenConversionsFinished
{
get
{
return this.quitApplicationWhenConversionsFinished;
}
set
{
this.quitApplicationWhenConversionsFinished = value;
this.OnPropertyChanged();
}
}
[XmlElement]
public float DurationBetweenEndOfConversionsAndApplicationQuit
{
get
{
return this.durationBetweenEndOfConversionsAndApplicationQuit;
}
set
{
this.durationBetweenEndOfConversionsAndApplicationQuit = 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]);
}
}
}
public void OnDeserializationComplete()
{
for (int index = 0; index < this.ConversionPresets.Count; index++)
{
this.ConversionPresets[index].OnDeserializationComplete();
}
}
}
}
+33 -27
View File
@@ -12,27 +12,22 @@ namespace FileConverter
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Principal;
using System.Xml.Serialization;
using System.Windows;
using Microsoft.Win32;
using FileConverter.Annotations;
using FileConverter.Diagnostics;
public class Settings : INotifyPropertyChanged, IDataErrorInfo
[XmlRoot]
[XmlType]
public partial class Settings : INotifyPropertyChanged, IDataErrorInfo
{
private const char PresetSeparator = ';';
private ObservableCollection<ConversionPreset> conversionPresets = new ObservableCollection<ConversionPreset>();
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<ConversionPreset> ConversionPresets
{
get { return this.conversionPresets; }
set { this.conversionPresets = value; }
}
[XmlIgnore]
public string Error
{
get
@@ -58,6 +53,7 @@ namespace FileConverter
}
}
[XmlIgnore]
public string this[string columnName]
{
get
@@ -75,18 +71,18 @@ namespace FileConverter
return;
}
ICollection<ConversionPreset> conversionPresets = new ObservableCollection<ConversionPreset>();
XmlHelpers.LoadFromFile("Settings", temporaryFilePath, ref conversionPresets);
Settings settings = new Settings();
XmlHelpers.LoadFromFile("Settings", temporaryFilePath, ref settings);
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\FileConverter");
if (registryKey == null)
{
MessageBox.Show("Can't apply settings in registry. (code 0x03)", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
Diagnostics.Debug.LogError("Can't apply settings in registry. (code 0x03)");
return;
}
// Compute the registry entries data from settings.
Dictionary<string, List<string>> registryEntries = ComputeRegistryEntriesFromConvertionPresets(conversionPresets);
Dictionary<string, List<string>> registryEntries = ComputeRegistryEntriesFromConvertionPresets(settings.ConversionPresets);
bool succeed = Settings.ApplyRegistryModifications(registryEntries);
@@ -99,20 +95,13 @@ namespace FileConverter
}
}
public ConversionPreset GetPresetFromName(string presetName)
public static Settings Load()
{
return this.conversionPresets.FirstOrDefault(match => match.Name == presetName);
}
public void Load()
{
ICollection<ConversionPreset> presets = this.ConversionPresets;
presets.Clear();
Settings settings = new Settings();
string userFilePath = Settings.GetUserSettingsFilePath();
if (File.Exists(userFilePath))
{
XmlHelpers.LoadFromFile<ConversionPreset>("Settings", userFilePath, ref presets);
XmlHelpers.LoadFromFile<Settings>("Settings", userFilePath, ref settings);
}
else
{
@@ -120,20 +109,29 @@ namespace FileConverter
string defaultFilePath = Settings.GetDefaultSettingsFilePath();
if (File.Exists(defaultFilePath))
{
XmlHelpers.LoadFromFile<ConversionPreset>("Settings", defaultFilePath, ref presets);
XmlHelpers.LoadFromFile<Settings>("FileConverter", defaultFilePath, ref settings);
}
else
{
Diagnostics.Debug.Log("Default settings not found. You should try to reinstall the application.");
Diagnostics.Debug.LogError("Default settings not found. You should try to reinstall the application.");
}
}
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.ConversionPresets);
XmlHelpers.SaveToFile("Settings", temporaryFilePath, this);
// Compute the registry entries data from settings.
Dictionary<string, List<string>> registryEntries = Settings.ComputeRegistryEntriesFromConvertionPresets(this.ConversionPresets);
@@ -171,6 +169,14 @@ namespace FileConverter
}
}
public void Clean()
{
for (int index = 0; index < this.ConversionPresets.Count; index++)
{
this.ConversionPresets[index].Clean();
}
}
private static bool ApplyRegistryModifications(Dictionary<string, List<string>> registryEntries)
{
if (!Settings.IsInAdmininstratorPrivileges)
@@ -83,7 +83,7 @@
<DockPanel>
<Label Content="Quality :" />
<controls:EncodingQualitySliderControl x:Name="EncodingQualitySlider"
EncodingMode="{Binding SelectedPreset.Settings, ConverterParameter=AudioEncodingMode|FileConverter.EncodingMode, Converter={StaticResource ConversionSettingsToEnum}, ElementName=window, Mode=OneWay, TargetNullValue=VBR}"
EncodingMode="{Binding SelectedPreset.Settings, ConverterParameter=AudioEncodingMode|FileConverter.Controls.EncodingMode, Converter={StaticResource ConversionSettingsToEnum}, ElementName=window, Mode=OneWay, TargetNullValue=VBR}"
Bitrate="{Binding SelectedPreset.Settings, ConverterParameter=AudioBitrate|System.Double, Converter={StaticResource ConversionSettingsToValueType}, ElementName=window, Mode=TwoWay, TargetNullValue=190}" />
</DockPanel>
</StackPanel>
@@ -119,7 +119,7 @@
<DockPanel>
<Label Content="Quality :" ToolTip="{x:Static project:Resources.VideoEncodingQualityTooltip}"/>
<Slider x:Name="QualitySlider" Value="{Binding SelectedPreset.Settings, ConverterParameter=VideoQuality|System.Double, Converter={StaticResource ConversionSettingsToValueType}, ElementName=window, Mode=TwoWay, TargetNullValue=23}"
Margin="0,2,0,0" VerticalAlignment="Top" AutoToolTipPlacement="TopLeft" IsSnapToTickEnabled="True" IsSelectionRangeEnabled="True" SelectionStart="23" SelectionEnd="33" Minimum="0" Maximum="51" TickPlacement="BottomRight" SmallChange="3" LargeChange="6" TickFrequency="1" Foreground="#004B82" />
Margin="0,2,0,0" VerticalAlignment="Top" AutoToolTipPlacement="TopLeft" IsSnapToTickEnabled="True" IsSelectionRangeEnabled="True" SelectionStart="23" SelectionEnd="33" Minimum="0" Maximum="51" TickPlacement="BottomRight" SmallChange="1" LargeChange="6" TickFrequency="1" Foreground="#004B82" />
</DockPanel>
<Label Content="Recommended quality range in blue" Foreground="#E5004B82" FontSize="11" />
@@ -268,7 +268,7 @@ namespace FileConverter
{
// Load previous preset in order to cancel changes.
Application application = Application.Current as Application;
application.Settings.Load();
application.Settings = Settings.Load();
this.Hide();
+30 -26
View File
@@ -10,19 +10,24 @@ namespace FileConverter
public class XmlHelpers
{
public static void LoadFromFile<T>(string root, string path, ref ICollection<T> collection)
public static void LoadFromFile<T>(string root, string path, ref T deserializedObject)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
if (deserializedObject == null)
{
throw new ArgumentNullException("deserializedObject");
}
XmlRootAttribute xmlRoot = new XmlRootAttribute
{
ElementName = root
};
XmlSerializer serializer = new XmlSerializer(typeof(List<T>), xmlRoot);
XmlSerializer serializer = new XmlSerializer(typeof(T), xmlRoot);
try
{
@@ -30,48 +35,46 @@ namespace FileConverter
{
XmlReaderSettings xmlReaderSettings = new XmlReaderSettings
{
IgnoreWhitespace = true, IgnoreComments = true
IgnoreWhitespace = true,
IgnoreComments = true
};
using (XmlReader xmlReader = XmlReader.Create(reader, xmlReaderSettings))
{
List<T> elements = (List<T>)serializer.Deserialize(xmlReader);
for (int index = 0; index < elements.Count; index++)
{
T item = elements[index];
if (item is IXmlSerializable)
{
(item as IXmlSerializable).OnDeserializationComplete();
}
collection.Add(item);
}
deserializedObject = (T)serializer.Deserialize(xmlReader);
}
}
}
catch (System.Exception exception)
{
Diagnostics.Debug.Log("The database of type '" + typeof(T) + "' failed to load the asset. The following exception was raised:\n " + exception.Message);
Diagnostics.Debug.LogError("Fail to load asset of type '" + typeof(T) + "'. The following exception was raised:\n " + exception.Message);
}
IXmlSerializable xmlSerializableObject = deserializedObject as IXmlSerializable;
if (xmlSerializableObject != null)
{
xmlSerializableObject.OnDeserializationComplete();
}
}
public static void SaveToFile<T>(string root, string path, ICollection<T> objectsToSerialize)
public static void SaveToFile<T>(string root, string path, T objectToSerialize)
{
if (string.IsNullOrEmpty(path))
{
return;
throw new ArgumentNullException("path");
}
List<T> list = new List<T>();
list.AddRange(objectsToSerialize);
if (objectToSerialize == null)
{
throw new ArgumentNullException("objectToSerialize");
}
XmlRootAttribute xmlRoot = new XmlRootAttribute
{
ElementName = root
};
XmlSerializer serializer = new XmlSerializer(typeof(List<T>), xmlRoot);
XmlSerializer serializer = new XmlSerializer(typeof(T), xmlRoot);
try
{
@@ -79,18 +82,19 @@ namespace FileConverter
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{
Indent = true, IndentChars = " "
Indent = true,
IndentChars = " "
};
using (XmlWriter xmlWriter = XmlWriter.Create(writer, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, list);
serializer.Serialize(xmlWriter, objectToSerialize);
}
}
}
catch (System.Exception exception)
{
Diagnostics.Debug.Log("The database of type '" + typeof(T) + "' failed to load the asset. The following exception was raised:\n " + exception.Message);
Diagnostics.Debug.LogError("Fail to save asset of type '" + typeof(T) + "'. The following exception was raised:\n " + exception.Message);
}
}
}