using System.IO;\r
using System.Linq;\r
using System.Windows;\r
- using System.Xml.Serialization;\r
\r
using HandBrake.ApplicationServices.Interop;\r
using HandBrake.ApplicationServices.Interop.Json.Presets;\r
{\r
#region Private Variables\r
\r
- private static readonly int CurrentPresetVersion = 5;\r
-\r
- /// <summary>\r
- /// User Preset Default Catgory Name\r
- /// </summary>\r
public static string UserPresetCatgoryName = "User Presets";\r
-\r
- /// <summary>\r
- /// The User Preset file\r
- /// </summary>\r
- private readonly string userPresetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\user_presets.json";\r
-\r
- /// <summary>\r
- /// The Legacy Preset file\r
- /// </summary>\r
- private readonly string legacyUserPresetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\user_presets.xml";\r
-\r
- /// <summary>\r
- /// The Built In Presets File\r
- /// </summary>\r
- private readonly string builtInPresetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\presets.json";\r
-\r
- /// <summary>\r
- /// A Collection of presets\r
- /// </summary>\r
+ private readonly string presetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\presets.json";\r
private readonly ObservableCollection<Preset> presets = new ObservableCollection<Preset>();\r
-\r
- /// <summary>\r
- /// The Error Service.\r
- /// </summary>\r
private readonly IErrorService errorService;\r
\r
#endregion\r
public void Load()\r
{\r
// If the preset file doesn't exist. Create it.\r
- if (!File.Exists(this.builtInPresetFile))\r
+ if (!File.Exists(this.presetFile))\r
{\r
this.UpdateBuiltInPresets();\r
}\r
\r
// Load the presets from file\r
this.LoadPresets();\r
-\r
- // Check they are up-to-date.\r
- if (this.CheckIfPresetsAreOutOfDate())\r
- {\r
- this.UpdateBuiltInPresets();\r
- this.LoadPresets(); // Reload again.\r
- }\r
}\r
\r
/// <summary>\r
this.LastPresetAdded = preset;\r
\r
// Update the presets file\r
- this.UpdatePresetFiles();\r
+ this.SavePresetFiles();\r
return true;\r
}\r
\r
return;\r
}\r
\r
- HBPreset hbPreset = container.PresetList.FirstOrDefault();\r
-\r
- Preset preset = null;\r
- try\r
+ // HBPreset Handling\r
+ IList<HBPreset> hbPresets = container.PresetList as IList<HBPreset>;\r
+ if (hbPresets != null)\r
{\r
- preset = JsonPresetFactory.ImportPreset(hbPreset);\r
- preset.Category = UserPresetCatgoryName;\r
-\r
- // IF we are using Source Max, Set the Max Width / Height values.\r
- if (preset.PictureSettingsMode == PresetPictureSettingsMode.SourceMaximum)\r
+ foreach (var hbPreset in hbPresets)\r
{\r
- preset.Task.MaxWidth = preset.Task.Height;\r
- preset.Task.MaxHeight = preset.Task.Width;\r
- }\r
- }\r
- catch (Exception exc)\r
- {\r
- this.errorService.ShowError(Resources.Main_PresetImportFailed, Resources.Main_PresetImportFailedSolution, exc);\r
- }\r
+ Preset preset = null;\r
+ try\r
+ {\r
+ preset = JsonPresetFactory.ImportPreset(hbPreset);\r
+ preset.Category = UserPresetCatgoryName;\r
\r
- if (preset == null)\r
- {\r
- this.errorService.ShowError(Resources.Main_PresetImportFailed, Resources.Main_PresetImportFailedSolution, string.Empty);\r
- return;\r
- }\r
+ // IF we are using Source Max, Set the Max Width / Height values.\r
+ if (preset.PictureSettingsMode == PresetPictureSettingsMode.SourceMaximum)\r
+ {\r
+ preset.Task.MaxWidth = preset.Task.Height;\r
+ preset.Task.MaxHeight = preset.Task.Width;\r
+ }\r
+ }\r
+ catch (Exception exc)\r
+ {\r
+ this.errorService.ShowError(Resources.Main_PresetImportFailed, Resources.Main_PresetImportFailedSolution, exc);\r
+ }\r
\r
- // TODO Better version checking.\r
- \r
- if (this.CheckIfPresetExists(preset.Name))\r
- {\r
- if (!CanUpdatePreset(preset.Name))\r
- {\r
- MessageBox.Show(Resources.Main_PresetErrorBuiltInName, Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);\r
- return;\r
- }\r
+ if (preset == null)\r
+ {\r
+ this.errorService.ShowError(Resources.Main_PresetImportFailed, Resources.Main_PresetImportFailedSolution, string.Empty);\r
+ return;\r
+ }\r
\r
- MessageBoxResult result = MessageBox.Show(Resources.Main_PresetOverwriteWarning, Resources.Overwrite, MessageBoxButton.YesNo, MessageBoxImage.Warning);\r
- if (result == MessageBoxResult.Yes)\r
- {\r
- Update(preset);\r
+ // TODO Better version checking.\r
+\r
+ if (this.CheckIfPresetExists(preset.Name))\r
+ {\r
+ if (!CanUpdatePreset(preset.Name))\r
+ {\r
+ MessageBox.Show(Resources.Main_PresetErrorBuiltInName, Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);\r
+ return;\r
+ }\r
+\r
+ MessageBoxResult result = MessageBox.Show(Resources.Main_PresetOverwriteWarning, Resources.Overwrite, MessageBoxButton.YesNo, MessageBoxImage.Warning);\r
+ if (result == MessageBoxResult.Yes)\r
+ {\r
+ Update(preset);\r
+ }\r
+ }\r
+ else\r
+ {\r
+ Add(preset);\r
+ }\r
}\r
}\r
- else\r
- {\r
- Add(preset);\r
- }\r
+\r
+ // Category Handling.\r
}\r
}\r
\r
/// </param>\r
public void Export(string filename, Preset preset, HBConfiguration configuration)\r
{\r
+ // TODO Add support for multiple export\r
PresetTransportContainer container = JsonPresetFactory.ExportPreset(preset, configuration);\r
HandBrakePresetService.ExportPreset(filename, container);\r
}\r
preset.SubtitleTrackBehaviours = update.SubtitleTrackBehaviours;\r
\r
// Update the presets file\r
- this.UpdatePresetFiles();\r
+ this.SavePresetFiles();\r
break;\r
}\r
}\r
}\r
\r
this.presets.Remove(preset);\r
- this.UpdatePresetFiles();\r
+ this.SavePresetFiles();\r
}\r
\r
/// <summary>\r
this.presets.Remove(preset);\r
}\r
\r
- this.UpdatePresetFiles();\r
+ this.SavePresetFiles();\r
}\r
\r
/// <summary>\r
}\r
\r
name.IsDefault = true;\r
- this.UpdatePresetFiles();\r
+ this.SavePresetFiles();\r
}\r
\r
/// <summary>\r
\r
IList<PresetCategory> presetCategories = HandBrakePresetService.GetBuiltInPresets();\r
\r
- foreach (var item in presetCategories)\r
+ foreach (var category in presetCategories)\r
{\r
- foreach (var hbpreset in item.ChildrenArray)\r
+ foreach (var hbpreset in category.ChildrenArray)\r
{\r
Preset preset = JsonPresetFactory.ImportPreset(hbpreset);\r
preset.Version = VersionHelper.GetVersion();\r
preset.IsBuildIn = true; // Older versions did not have this flag so explicitly make sure it is set.\r
- preset.Category = item.PresetName;\r
+ preset.Category = category.PresetName;\r
\r
if (preset.Name == "iPod")\r
{\r
}\r
\r
// Store the changes to disk\r
- this.UpdatePresetFiles();\r
- }\r
-\r
- /// <summary>\r
- /// Check if the built in Presets stored are not out of date.\r
- /// Update them if they are.\r
- /// </summary>\r
- /// <returns>true if out of date</returns>\r
- public bool CheckIfPresetsAreOutOfDate()\r
- {\r
- // Update built-in Presets if the built-in Presets belong to an older version.\r
- if (this.presets.Count != 0)\r
- {\r
- List<Preset> preset = this.presets.Where(p => p.IsBuildIn).ToList();\r
- if (preset.Count > 0)\r
- {\r
- if (preset[0].Version != VersionHelper.GetVersion())\r
- {\r
- this.UpdateBuiltInPresets();\r
- return true;\r
- }\r
- }\r
- }\r
-\r
- return false;\r
+ this.SavePresetFiles();\r
}\r
\r
/// <summary>\r
// First clear the Presets arraylists\r
this.presets.Clear();\r
\r
- // Load in the Presets from Presets.xml\r
+ // Load the presets file.\r
try\r
{\r
- if (File.Exists(this.builtInPresetFile))\r
+ // If we don't have a presets file. Create one for first load.\r
+ if (!File.Exists(this.presetFile))\r
+ {\r
+ this.UpdateBuiltInPresets();\r
+ return;\r
+ }\r
+\r
+ // Otherwise, we already have a file, so lets try load it.\r
+ using (StreamReader reader = new StreamReader(this.presetFile))\r
{\r
- using (StreamReader reader = new StreamReader(this.builtInPresetFile))\r
+ // New Preset Format.\r
+ PresetTransportContainer container = JsonConvert.DeserializeObject<PresetTransportContainer>(reader.ReadToEnd());\r
+\r
+ // Sanity Check. Did the container deserialise.\r
+ if (container == null)\r
+ {\r
+ // Close and Dispose of early.\r
+ reader.Close();\r
+ reader.Dispose();\r
+ RecoverFromCorruptedPresetFile(this.presetFile);\r
+ this.UpdateBuiltInPresets();\r
+ return;\r
+ }\r
+\r
+ // Version Check\r
+ // If we have old presets, or the container wasn't parseable, or we have a version mismatch, backup the user preset file \r
+ // incase something goes wrong.\r
+ if (container.VersionMajor != Constants.PresetVersionMajor || container.VersionMinor != Constants.PresetVersionMinor || container.VersionMicro != Constants.PresetVersionMicro)\r
{\r
- // New Preset Format.\r
- IList<PresetCategory> presetCategories = JsonConvert.DeserializeObject<IList<PresetCategory>>(reader.ReadToEnd());\r
+ string fileName = RecoverFromCorruptedPresetFile(this.presetFile);\r
+ this.UpdateBuiltInPresets();\r
+ this.errorService.ShowMessageBox(\r
+ Resources.PresetService_PresetsOutOfDate\r
+ + Environment.NewLine + Environment.NewLine + Resources.PresetService_ArchiveFile + fileName,\r
+ Resources.PresetService_UnableToLoad,\r
+ MessageBoxButton.OK,\r
+ MessageBoxImage.Exclamation);\r
+ return;\r
+ }\r
\r
- foreach (var item in presetCategories)\r
+\r
+ // Process the presets.\r
+ foreach (var item in container.PresetList)\r
+ {\r
+ object deserialisedItem = JsonConvert.DeserializeObject<PresetCategory>(item.ToString()); ;\r
+ \r
+ // Handle Categorised Presets.\r
+ PresetCategory category = deserialisedItem as PresetCategory;\r
+ if (category != null && category.Folder)\r
{\r
- foreach (var hbpreset in item.ChildrenArray)\r
+ foreach (HBPreset hbpreset in category.ChildrenArray)\r
{\r
Preset preset = JsonPresetFactory.ImportPreset(hbpreset);\r
- preset.Category = item.PresetName;\r
- preset.IsBuildIn = true;\r
+ preset.Category = category.PresetName;\r
+ preset.IsBuildIn = hbpreset.Type == 0;\r
\r
// IF we are using Source Max, Set the Max Width / Height values.\r
if (preset.PictureSettingsMode == PresetPictureSettingsMode.SourceMaximum)\r
this.presets.Add(preset);\r
}\r
}\r
- }\r
- }\r
- }\r
- catch (Exception)\r
- {\r
- RecoverFromCorruptedPresetFile(this.builtInPresetFile);\r
- this.UpdateBuiltInPresets();\r
- }\r
\r
- // Load in the users Presets from UserPresets.xml\r
- try\r
- {\r
- // Handle Legacy Preset Format.\r
- bool updatePresets = false;\r
- if (File.Exists(this.legacyUserPresetFile))\r
- {\r
- using (StreamReader reader = new StreamReader(this.legacyUserPresetFile))\r
- {\r
- try\r
- {\r
- XmlSerializer Ser = new XmlSerializer(typeof(List<Preset>));\r
- var oldPresets = (List<Preset>)Ser.Deserialize(reader);\r
- foreach (Preset oldPreset in oldPresets)\r
- {\r
- this.presets.Add(oldPreset);\r
- }\r
- updatePresets = true;\r
- }\r
- catch (Exception exc)\r
+ // Uncategorised Presets\r
+ deserialisedItem = JsonConvert.DeserializeObject<HBPreset>(item.ToString());\r
+ HBPreset hbPreset = deserialisedItem as HBPreset;\r
+ if (hbPreset != null && !hbPreset.Folder)\r
{\r
- // Do Nothing\r
- Debug.WriteLine(exc);\r
- }\r
- }\r
+ Preset preset = JsonPresetFactory.ImportPreset(hbPreset);\r
+ preset.Category = UserPresetCatgoryName;\r
+ preset.IsBuildIn = hbPreset.Type == 1;\r
\r
- // Archive the old file incase the user needs it.\r
- File.Move(this.legacyUserPresetFile, this.legacyUserPresetFile + ".archive." + GeneralUtilities.ProcessId);\r
- }\r
-\r
- // New JSON Format.\r
- if (File.Exists(this.userPresetFile))\r
- {\r
- // New Preset Format.\r
- bool createBackup = false;\r
- PresetTransportContainer presetContainer = null;\r
- using (StreamReader reader = new StreamReader(this.userPresetFile))\r
- {\r
- try\r
- {\r
- presetContainer = JsonConvert.DeserializeObject<PresetTransportContainer>(reader.ReadToEnd());\r
- }\r
- catch (Exception exc)\r
- {\r
- createBackup = true;\r
- Debug.WriteLine(exc);\r
- }\r
- }\r
-\r
- // If we have old presets, or the container wasn't parseable, or we have a version mismatch, backup the user preset file \r
- // incase something goes wrong.\r
- if (createBackup || (presetContainer.VersionMajor != Constants.PresetVersionMajor || presetContainer.VersionMinor != Constants.PresetVersionMinor || presetContainer.VersionMicro != Constants.PresetVersionMicro))\r
- {\r
- string fileName = RecoverFromCorruptedPresetFile(this.userPresetFile);\r
- this.errorService.ShowMessageBox(\r
- "HandBrake is unable to load your user presets because they are from an older version of HandBrake. Your old presets file has been renamed so that it doesn't get loaded on next launch."\r
- + Environment.NewLine + Environment.NewLine + "Archived File: " + fileName, \r
- "Unable to load user presets.", \r
- MessageBoxButton.OK, \r
- MessageBoxImage.Exclamation);\r
- return;\r
- }\r
-\r
- // Load the current presets.\r
- if (presetContainer.PresetList != null)\r
- {\r
- foreach (var item in presetContainer.PresetList)\r
- {\r
- Preset preset = JsonPresetFactory.ImportPreset(item);\r
- preset.Category = item.PresetName;\r
- preset.IsBuildIn = true;\r
-\r
- // If we are using Source Max, Set the Max Width / Height values.\r
+ // IF we are using Source Max, Set the Max Width / Height values.\r
if (preset.PictureSettingsMode == PresetPictureSettingsMode.SourceMaximum)\r
{\r
preset.Task.MaxWidth = preset.Task.Height;\r
}\r
}\r
}\r
-\r
- // We did a preset convertion, so save the updates.\r
- if (updatePresets)\r
- {\r
- this.UpdatePresetFiles();\r
- }\r
}\r
- catch (Exception exc)\r
+ catch (Exception ex)\r
{\r
- RecoverFromCorruptedPresetFile(this.userPresetFile);\r
- throw new GeneralApplicationException("HandBrake has detected a problem with your presets.", "Your old presets file has been renamed so that it doesn't get loaded on next launch.", exc);\r
+ Debug.WriteLine(ex);\r
+ RecoverFromCorruptedPresetFile(this.presetFile);\r
+ this.UpdateBuiltInPresets();\r
}\r
}\r
\r
/// <summary>\r
/// Update the preset files\r
/// </summary>\r
- private void UpdatePresetFiles()\r
+ private void SavePresetFiles()\r
{\r
try\r
{\r
- // Setup\r
- string directory = Path.GetDirectoryName(this.userPresetFile);\r
+ // Verify Directories.\r
+ string directory = Path.GetDirectoryName(this.presetFile);\r
if (!Directory.Exists(directory))\r
{\r
Directory.CreateDirectory(directory);\r
}\r
\r
- JsonSerializerSettings settings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore };\r
-\r
- // Built-in Presets\r
+ // Orgamise the Presets list into Json Equivilent objects.\r
Dictionary<string, PresetCategory> presetCategories = new Dictionary<string, PresetCategory>();\r
- foreach (var item in this.presets.Where(p => p.IsBuildIn).ToList())\r
+ List<HBPreset> uncategorisedPresets = new List<HBPreset>(); \r
+ foreach (Preset item in this.presets)\r
{\r
- HBPreset preset = JsonPresetFactory.CreateHbPreset(item, HBConfigurationFactory.Create());\r
- if (presetCategories.ContainsKey(item.Category))\r
+ if (string.IsNullOrEmpty(item.Category))\r
{\r
- presetCategories[item.Category].ChildrenArray.Add(preset);\r
+ uncategorisedPresets.Add(JsonPresetFactory.CreateHbPreset(item, HBConfigurationFactory.Create()));\r
}\r
else\r
{\r
- presetCategories[item.Category] = new PresetCategory { ChildrenArray = new List<HBPreset>(), Folder = true, PresetName = item.Category, Type = 0 };\r
- } \r
- }\r
-\r
- using (FileStream strm = new FileStream(this.builtInPresetFile, FileMode.Create, FileAccess.Write))\r
- {\r
- string presetsJson = JsonConvert.SerializeObject(presetCategories, Formatting.Indented, settings);\r
- using (StreamWriter writer = new StreamWriter(strm))\r
- {\r
- writer.WriteLine(presetsJson);\r
+ HBPreset preset = JsonPresetFactory.CreateHbPreset(item, HBConfigurationFactory.Create());\r
+ if (presetCategories.ContainsKey(item.Category))\r
+ {\r
+ presetCategories[item.Category].ChildrenArray.Add(preset);\r
+ }\r
+ else\r
+ {\r
+ presetCategories[item.Category] = new PresetCategory\r
+ {\r
+ ChildrenArray = new List<HBPreset> { preset },\r
+ Folder = true,\r
+ PresetName = item.Category,\r
+ Type = item.IsBuildIn ? 0 : 1\r
+ };\r
+ }\r
}\r
}\r
\r
- // User Presets\r
- using (FileStream strm = new FileStream(this.userPresetFile, FileMode.Create, FileAccess.Write))\r
+ // Wrap the categories in a container. \r
+ JsonSerializerSettings settings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore };\r
+ PresetTransportContainer container = new PresetTransportContainer(\r
+ Constants.PresetVersionMajor,\r
+ Constants.PresetVersionMinor,\r
+ Constants.PresetVersionMicro) { PresetList = new List<object>() };\r
+ container.PresetList.AddRange(presetCategories.Values);\r
+ container.PresetList.AddRange(uncategorisedPresets);\r
+\r
+ // Write the preset container out to file.\r
+ using (FileStream strm = new FileStream(this.presetFile, FileMode.Create, FileAccess.Write))\r
{\r
- List<Preset> userPresets = this.presets.Where(p => p.IsBuildIn == false).ToList();\r
- PresetTransportContainer container = JsonPresetFactory.ExportPresets(userPresets, HBConfigurationFactory.Create());\r
-\r
string presetsJson = JsonConvert.SerializeObject(container, Formatting.Indented, settings);\r
-\r
using (StreamWriter writer = new StreamWriter(strm))\r
{\r
writer.WriteLine(presetsJson);\r
}\r
catch (Exception exc)\r
{\r
+ Debug.WriteLine(exc);\r
throw new GeneralApplicationException("Unable to write to the presets file.", "The details section below may indicate why this error has occured.", exc);\r
}\r
}\r