OSDN Git Service

LinGui: make Help->Guide work on windows/mingw
[handbrake-jp/handbrake-jp-git.git] / win / C# / Presets / PresetsHandler.cs
index e29c4d2..1a47a4d 100644 (file)
@@ -1,35 +1,80 @@
-using System;\r
-using System.Collections.Generic;\r
-using System.Windows.Forms;\r
-using System.IO;\r
-using System.Text.RegularExpressions;\r
-using System.Diagnostics;\r
-using System.Xml.Serialization;\r
+/*  PresetHandler.cs $\r
+    This file is part of the HandBrake source code.\r
+    Homepage: <http://handbrake.fr>.\r
+    It may be used under the terms of the GNU General Public License. */\r
 \r
 namespace Handbrake.Presets\r
 {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics;\r
+    using System.Drawing;\r
+    using System.IO;\r
+    using System.Linq;\r
+    using System.Text.RegularExpressions;\r
+    using System.Windows.Forms;\r
+    using System.Xml.Serialization;\r
+\r
+    /// <summary>\r
+    /// The Preset Handler Class\r
+    /// </summary>\r
     public class PresetsHandler\r
     {\r
-        List<Preset> presets = new List<Preset>();  // Category+Level+Preset Name: Query\r
-        List<Preset> user_presets = new List<Preset>(); // Preset Name: Query\r
-        private static readonly XmlSerializer ser = new XmlSerializer(typeof(List<Preset>));\r
+        /// <summary>\r
+        /// The User Preset file\r
+        /// </summary>\r
+        private readonly string userPresetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\user_presets.xml";\r
+\r
+        /// <summary>\r
+        /// The Built In Presets File\r
+        /// </summary>\r
+        private readonly string hbPresetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\presets.xml";\r
+\r
+        /// <summary>\r
+        /// XML Serializer\r
+        /// </summary>\r
+        private static readonly XmlSerializer Ser = new XmlSerializer(typeof(List<Preset>));\r
+\r
+        /// <summary>\r
+        /// A List of built-in presets\r
+        /// </summary>\r
+        private List<Preset> presets = new List<Preset>();\r
+\r
+        /// <summary>\r
+        /// A List of user presets\r
+        /// </summary>\r
+        private List<Preset> userPresets = new List<Preset>();\r
 \r
         /// <summary>\r
         /// Add a new preset to the system\r
         /// </summary>\r
-        /// <param name="presetName">String, The name of the new preset</param>\r
-        /// <param name="query">String, the CLI query for the new preset</param>\r
-        /// <param name="pictureSettings"> Bool, store crop/picture sizes in the presets</param>\r
-        public Boolean addPreset(string presetName, string query, Boolean pictureSettings)\r
+        /// <param name="presetName">\r
+        /// String, The name of the new preset\r
+        /// </param>\r
+        /// <param name="query">\r
+        /// String, the CLI query for the new preset\r
+        /// </param>\r
+        /// <param name="pictureSettings">\r
+        /// Bool, store crop/picture sizes in the Presets\r
+        /// </param>\r
+        /// <returns>\r
+        /// The add.\r
+        /// </returns>\r
+        public bool Add(string presetName, string query, bool pictureSettings)\r
         {\r
-            if (checkIfPresetExists(presetName) == false)\r
+            if (this.CheckIfPresetExists(presetName) == false)\r
             {\r
-                Preset newPreset = new Preset {Name = presetName, Query = query, PictureSettings = pictureSettings};\r
-                user_presets.Add(newPreset);\r
-                updateUserPresetsFile();\r
+                Preset newPreset = new Preset\r
+                                       {\r
+                                           Name = presetName, \r
+                                           Query = query, \r
+                                           PictureSettings = pictureSettings, \r
+                                           Version = Properties.Settings.Default.hb_version\r
+                                       };\r
+                this.userPresets.Add(newPreset);\r
+                this.UpdatePresetFiles();\r
                 return true;\r
             }\r
-            MessageBox.Show("Sorry, that preset name already exists. Please choose another!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
             return false;\r
         }\r
 \r
@@ -37,34 +82,43 @@ namespace Handbrake.Presets
         /// Remove a preset with a given name from either the built in or user preset list.\r
         /// </summary>\r
         /// <param name="name">String, the preset name</param>\r
-        public void remove(string name)\r
+        public void Remove(string name)\r
         {\r
             List<Preset> newPresets = new List<Preset>();\r
             List<Preset> newUserPresets = new List<Preset>();\r
 \r
             // Built In Presets\r
-            foreach (Preset item in presets)\r
+            foreach (Preset item in this.presets)\r
             {\r
                 if (item.Name != name)\r
                 {\r
                     newPresets.Add(item);\r
                 }\r
             }\r
-            presets = newPresets;\r
+            this.presets = newPresets;\r
 \r
             // User Presets\r
-            foreach (Preset item in user_presets)\r
+            foreach (Preset item in this.userPresets)\r
             {\r
                 if (item.Name != name)\r
                 {\r
                     newUserPresets.Add(item);\r
                 }\r
             }\r
-            user_presets = newUserPresets;\r
+            this.userPresets = newUserPresets;\r
+\r
+            // Rebuild the UserPresets.xml file\r
+            this.UpdatePresetFiles();\r
+            this.UpdatePresetFiles();\r
+        }\r
 \r
-            // Rebuild the user_presets.xml file\r
-            updateUserPresetsFile();\r
-            updatePresetsFile();\r
+        /// <summary>\r
+        /// Remove all built in Presets;\r
+        /// </summary>\r
+        public void RemoveBuiltInPresets()\r
+        {\r
+            this.presets.Clear();\r
+            this.UpdatePresetFiles();\r
         }\r
 \r
         /// <summary>\r
@@ -73,85 +127,57 @@ namespace Handbrake.Presets
         /// <param name="presetName">String, The name of the new preset</param>\r
         /// <param name="query">String, the CLI query for the new preset</param>\r
         /// <param name="pictureSettings"> Bool, store crop/picture sizes in the preset</param>\r
-        public void updatePreset(string presetName, string query, Boolean pictureSettings)\r
+        public void Update(string presetName, string query, bool pictureSettings)\r
         {\r
             // User Presets\r
-            foreach (Preset item in user_presets)\r
+            foreach (Preset item in this.userPresets)\r
             {\r
                 if (item.Name == presetName)\r
                 {\r
                     item.Query = query;\r
                     item.PictureSettings = pictureSettings;\r
-                    MessageBox.Show("Changes to \"" + presetName + "\" Saved", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);\r
-                    updateUserPresetsFile();\r
+                    MessageBox.Show(\r
+                        "Changes to \"" + presetName + "\" Saved",\r
+                                    "Success",\r
+                                    MessageBoxButtons.OK, \r
+                                    MessageBoxIcon.Information);\r
+                    this.UpdatePresetFiles();\r
                 }\r
             }\r
         }\r
 \r
         /// <summary>\r
-        /// Get a List of all the built in preset names.\r
-        /// </summary>\r
-        /// <returns>List<String> of preset names</returns>\r
-        public List<Preset> getBuildInPresets()\r
-        {\r
-            return presets;\r
-        }\r
-\r
-        /// <summary>\r
-        /// Get a List of all the User preset names.\r
-        /// </summary>\r
-        /// <returns>List<String> of preset names</returns>\r
-        public List<string> getUserPresetNames()\r
-        {\r
-            List<string> names = new List<string>();\r
-\r
-            // User Presets\r
-            foreach (Preset item in user_presets)\r
-            {\r
-                names.Add(item.Name);\r
-            }\r
-\r
-            return names;\r
-        }\r
-\r
-        /// <summary>\r
         /// Return the CLI query for a preset name given in name\r
         /// </summary>\r
         /// <param name="name">String, The preset's name</param>\r
-        /// <returns>String, the CLI query for the given preset name</returns>\r
-        public Preset getPreset(string name)\r
+        /// <returns>String, the CLI query for the given preset name</returns>    not\r
+        public Preset GetPreset(string name)\r
         {\r
             // Built In Presets\r
-            foreach (Preset item in presets)\r
+            foreach (Preset item in this.presets)\r
             {\r
                 if (item.Name == name)\r
                     return item;\r
             }\r
 \r
             // User Presets\r
-            foreach (Preset item in user_presets)\r
-            {\r
-                if (item.Name == name)\r
-                    return item;\r
-            }\r
-\r
-            return null;\r
+            return this.userPresets.FirstOrDefault(item => item.Name == name);\r
         }\r
 \r
         /// <summary>\r
-        /// Reads the CLI's CLI output format and load's them into the preset List<Preset>\r
+        /// Reads the CLI's CLI output format and load's them into the preset List Preset\r
         /// </summary>\r
-        public void updateBuiltInPresets()\r
+        public void UpdateBuiltInPresets()\r
         {\r
-            // Create a new tempory file and execute the CLI to get the built in presets.\r
+            // Create a new tempory file and execute the CLI to get the built in Presets.\r
             string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");\r
             string presetsPath = Path.Combine(Path.GetTempPath(), "temp_presets.dat");\r
-\r
             string strCmdLine = String.Format(@"cmd /c """"{0}"" --preset-list >""{1}"" 2>&1""", handbrakeCLIPath, presetsPath);\r
 \r
             ProcessStartInfo hbGetPresets = new ProcessStartInfo("CMD.exe", strCmdLine)\r
-                                                {WindowStyle = ProcessWindowStyle.Hidden};\r
-\r
+                                                {\r
+                                                   WindowStyle = ProcessWindowStyle.Hidden\r
+                                                };\r
             Process hbproc = Process.Start(hbGetPresets);\r
             if (hbproc != null)\r
             {\r
@@ -160,195 +186,254 @@ namespace Handbrake.Presets
                 hbproc.Close();\r
             }\r
 \r
-            // Clear the current built in presets and now parse the tempory presets file.\r
-            presets.Clear();\r
-            string filePath = Path.Combine(Path.GetTempPath(), "temp_presets.dat");\r
-            if (File.Exists(filePath))\r
+            // Clear the current built in Presets and now parse the tempory Presets file.\r
+            this.presets.Clear();\r
+\r
+            if (File.Exists(presetsPath))\r
             {\r
-                StreamReader presetInput = new StreamReader(filePath);\r
-                int level = 1;\r
+                StreamReader presetInput = new StreamReader(presetsPath);\r
+\r
                 string category = String.Empty;\r
-                string level_1_category = String.Empty;\r
 \r
                 while (!presetInput.EndOfStream)\r
                 {\r
                     string line = presetInput.ReadLine();\r
-                    if (line.Contains("<") && !line.Contains("<<"))\r
-                    {\r
-                        level = 1;\r
-                        category = line.Replace("<", "").Trim();\r
-                        level_1_category = category;\r
-                    }\r
-\r
-                    if (line.Contains("<<"))\r
-                    {\r
-                        level = 2;\r
-                        category = line.Replace("<<", "").Trim();\r
-                    }\r
-\r
-                    if (line.Trim().Contains(">>"))\r
-                    {\r
-                        level = 1;\r
-                        category = level_1_category;\r
-                    }\r
+                    if (line.Contains("<") && !line.Contains("<<")) // Found the beginning of a preset block \r
+                        category = line.Replace("<", string.Empty).Trim();\r
 \r
-                    if (line.Contains("+"))\r
+                    if (line.Contains("+")) // A Preset\r
                     {\r
                         Regex r = new Regex("(:  )"); // Split on hyphens. \r
                         string[] presetName = r.Split(line);\r
 \r
+                        bool pic = false;\r
+                        if (presetName[2].Contains("crop"))\r
+                            pic = true;\r
+\r
                         Preset newPreset = new Preset\r
                                                {\r
-                                                   Level = level,\r
-                                                   Category = category,\r
-                                                   Name = presetName[0].Replace("+", "").Trim(),\r
-                                                   Query = presetName[2]\r
+                                                   Category = category, \r
+                                                   Name = presetName[0].Replace("+", string.Empty).Trim(), \r
+                                                   Query = presetName[2], \r
+                                                   Version = Properties.Settings.Default.hb_version, \r
+                                                   PictureSettings = pic\r
                                                };\r
-                        presets.Add(newPreset);\r
+                        this.presets.Add(newPreset);\r
                     }\r
                 }\r
                 presetInput.Close();\r
                 presetInput.Dispose();\r
             }\r
 \r
-            // Finally, Create a new or update the current presets.xml file\r
-            updatePresetsFile();\r
+            // Finally, Create a new or update the current Presets.xml file\r
+            this.UpdatePresetFiles();\r
         }\r
 \r
         /// <summary>\r
-        /// Load in the preset data from presets.xml and user_presets.xml\r
-        /// Load it into the 2 arraylist's presets and user_presets\r
+        /// Setup the frmMain preset panel\r
         /// </summary>\r
-        public void loadPresetData()\r
+        /// <param name="presetPanel">The Preset Panel from the Main Window</param>\r
+        public void GetPresetPanel(ref TreeView presetPanel)\r
         {\r
-            // First clear the presets arraylists\r
-            presets.Clear();\r
-            user_presets.Clear();\r
+            this.LoadPresetData();\r
+            presetPanel.Nodes.Clear();\r
+            string category = string.Empty;\r
+            TreeNode rootNode = null;\r
 \r
-            // Load in the users presets from user_presets.xml\r
-            string filePath = Application.StartupPath + "\\presets.xml";\r
-            if (File.Exists(filePath))\r
+            if (this.presets.Count != 0) // Built In Presets\r
             {\r
-                using (FileStream strm = new FileStream(filePath, FileMode.Open, FileAccess.Read))\r
+                foreach (Preset preset in this.presets)\r
                 {\r
-                    if (strm.Length != 0)\r
+                    if (preset.Category != category)\r
                     {\r
-                        List<Preset> list = ser.Deserialize(strm) as List<Preset>;\r
-\r
-                        if (list != null)\r
-                            foreach (Preset preset in list)\r
-                                presets.Add(preset);\r
+                        rootNode = new TreeNode(preset.Category);\r
+                        presetPanel.Nodes.Add(rootNode);\r
+                        category = preset.Category;\r
                     }\r
+\r
+                    if (preset.Category == category && rootNode != null)\r
+                        rootNode.Nodes.Add(preset.Name);\r
                 }\r
             }\r
 \r
-            // Load in the users presets from user_presets.xml\r
-            filePath = Application.StartupPath + "\\user_presets.xml";\r
-            if (File.Exists(filePath))\r
+            rootNode = null;\r
+            category = null;\r
+            foreach (Preset preset in this.userPresets) // User Presets\r
             {\r
-                using (FileStream strm = new FileStream(filePath, FileMode.Open, FileAccess.Read))\r
+                if (preset.Category != category && preset.Category != string.Empty)\r
                 {\r
-                    if (strm.Length != 0)\r
-                    {\r
-                        List<Preset> list = ser.Deserialize(strm) as List<Preset>;\r
-\r
-                        if (list != null)\r
-                            foreach (Preset preset in list)\r
-                                user_presets.Add(preset);\r
-                    }\r
+                    rootNode = new TreeNode(preset.Category) {ForeColor = Color.Black};\r
+                    presetPanel.Nodes.Add(rootNode);\r
+                    category = preset.Category;\r
                 }\r
+\r
+                if (preset.Category == category && rootNode != null)\r
+                    rootNode.Nodes.Add(new TreeNode(preset.Name) {ForeColor = Color.Black});\r
+                else\r
+                    presetPanel.Nodes.Add(new TreeNode(preset.Name) {ForeColor = Color.Black});\r
             }\r
         }\r
 \r
         /// <summary>\r
-        /// Updates the presets.xml file which contains the built in presets\r
-        /// It takes the List of Presets and converts them into XML which is stored in presets.xml\r
+        /// Check if the user preset "name" exists in UserPresets list.\r
+        /// </summary>\r
+        /// <param name="name">Name of the preset</param>\r
+        /// <returns>true if found</returns>\r
+        public bool CheckIfUserPresetExists(string name)\r
+        {\r
+            return name != string.Empty && this.userPresets.Any(item => item.Name == name);\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
+            this.LoadPresetData();\r
+            // Update built-in Presets if the built-in Presets belong to an older version.\r
+            if (this.presets.Count != 0)\r
+                if (this.presets[0].Version != Properties.Settings.Default.hb_version)\r
+                {\r
+                    this.UpdateBuiltInPresets();\r
+                    return true;\r
+                }\r
+\r
+            return false;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Load in the preset data from Presets.xml and UserPresets.xml\r
+        /// Load it into the 2 arraylist's Presets and UserPresets\r
         /// </summary>\r
-        private void updatePresetsFile()\r
+        private void LoadPresetData()\r
         {\r
-            string userPresets = Application.StartupPath + "\\presets.xml";\r
+            // First clear the Presets arraylists\r
+            this.presets.Clear();\r
+            this.userPresets.Clear();\r
+\r
             try\r
             {\r
-                using (FileStream strm = new FileStream(userPresets, FileMode.Create, FileAccess.Write))\r
+                // Load in the users Presets from UserPresets.xml\r
+                if (File.Exists(this.hbPresetFile))\r
                 {\r
-                    ser.Serialize(strm, presets);\r
-                    strm.Close();\r
-                    strm.Dispose();\r
+                    using (FileStream strm = new FileStream(this.hbPresetFile, FileMode.Open, FileAccess.Read))\r
+                    {\r
+                        if (strm.Length != 0)\r
+                        {\r
+                            List<Preset> list = Ser.Deserialize(strm) as List<Preset>;\r
+\r
+                            if (list != null)\r
+                                foreach (Preset preset in list)\r
+                                    this.presets.Add(preset);\r
+                        }\r
+                    }\r
                 }\r
             }\r
-            catch (Exception exc)\r
+            catch (Exception)\r
             {\r
-                MessageBox.Show("Unable to write to the file. Please make sure the location has the correct permissions for file writing.\n Error Information: \n\n" + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);\r
+                MessageBox.Show(\r
+                    "HandBrakes preset file appears to have been corrupted. This file will now be re-generated!\n" +\r
+                    "If the problem presists, please delete the file: \n\n" + this.hbPresetFile, \r
+                    "Error",\r
+                    MessageBoxButtons.OK, \r
+                    MessageBoxIcon.Error);\r
+                this.UpdateBuiltInPresets();\r
+            }\r
+\r
+            try\r
+            {\r
+                // Load in the users Presets from UserPresets.xml\r
+                if (File.Exists(this.userPresetFile))\r
+                {\r
+                    using (FileStream strm = new FileStream(this.userPresetFile, FileMode.Open, FileAccess.Read))\r
+                    {\r
+                        if (strm.Length != 0)\r
+                        {\r
+                            List<Preset> list = Ser.Deserialize(strm) as List<Preset>;\r
+\r
+                            if (list != null)\r
+                                foreach (Preset preset in list)\r
+                                    this.userPresets.Add(preset);\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+            catch (Exception)\r
+            {\r
+                MessageBox.Show(\r
+                    "Your User presets file appears to have been corrupted.\n" +\r
+                    "Your presets will not be loaded. You may need to re-create your presets.\n\n" +\r
+                    "Your user presets file has been renamed to 'user_presets.xml.old' and is located in:\n " +\r
+                    Path.GetDirectoryName(this.userPresetFile) + "\n" + \r
+                    "You may be able to recover some presets if you know the XML language.", \r
+                    "Error",\r
+                    MessageBoxButtons.OK, \r
+                    MessageBoxIcon.Error);\r
+\r
+                // Recover from Error.\r
+                if (File.Exists(this.userPresetFile))\r
+                {\r
+                    string disabledFile = this.userPresetFile + ".old";\r
+                    if (File.Exists(disabledFile))\r
+                        File.Delete(disabledFile);\r
+                    File.Move(this.userPresetFile, disabledFile);\r
+                }\r
             }\r
         }\r
 \r
         /// <summary>\r
-        /// Updates the user_presets.xml file which contains the built in presets\r
-        /// It takes the List of Presets and converts them into XML which is stored in user_presets.xml\r
+        /// Update the preset files\r
         /// </summary>\r
-        private void updateUserPresetsFile()\r
+        private void UpdatePresetFiles()\r
         {\r
-            string userPresets = Application.StartupPath + "\\user_presets.xml";\r
             try\r
             {\r
-                using (FileStream strm = new FileStream(userPresets, FileMode.Create, FileAccess.Write))\r
+                using (FileStream strm = new FileStream(this.hbPresetFile, FileMode.Create, FileAccess.Write))\r
                 {\r
-                    ser.Serialize(strm, user_presets);\r
+                    Ser.Serialize(strm, this.presets);\r
+                    strm.Close();\r
+                    strm.Dispose();\r
+                }\r
+\r
+                using (FileStream strm = new FileStream(this.userPresetFile, FileMode.Create, FileAccess.Write))\r
+                {\r
+                    Ser.Serialize(strm, this.userPresets);\r
                     strm.Close();\r
                     strm.Dispose();\r
                 }\r
             }\r
             catch (Exception exc)\r
             {\r
-                MessageBox.Show("Unable to write to the file. Please make sure the location has the correct permissions for file writing.\n Error Information: \n\n" + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);\r
+                MessageBox.Show(\r
+                    "Unable to write to the file. Please make sure the location has the correct permissions for file writing.\n Error Information: \n\n" +\r
+                    exc, \r
+                    "Error", \r
+                    MessageBoxButtons.OK, \r
+                    MessageBoxIcon.Hand);\r
             }\r
         }\r
 \r
         /// <summary>\r
-        /// Check if the preset "name" exists in either presets or user_presets lists.\r
+        /// Check if the preset "name" exists in either Presets or UserPresets lists.\r
         /// </summary>\r
-        /// <param name="name"></param>\r
-        /// <returns></returns>\r
-        private Boolean checkIfPresetExists(string name)\r
+        /// <param name="name">Name of the preset</param>\r
+        /// <returns>True if found</returns>\r
+        private bool CheckIfPresetExists(string name)\r
         {\r
             if (name == string.Empty)\r
                 return true;\r
 \r
             // Built In Presets\r
-            foreach (Preset item in presets)\r
+            foreach (Preset item in this.presets)\r
             {\r
                 if (item.Name == name)\r
                     return true;\r
             }\r
 \r
             // User Presets\r
-            foreach (Preset item in user_presets)\r
-            {\r
-                if (item.Name == name)\r
-                    return true;\r
-            }\r
-\r
-            return false;\r
-        }\r
-\r
-        /// <summary>\r
-        /// Check if the user preset "name" exists in user_presets list.\r
-        /// </summary>\r
-        /// <param name="name"></param>\r
-        /// <returns></returns>\r
-        public Boolean checkIfUserPresetExists(string name)\r
-        {\r
-            if (name == string.Empty)\r
-                return false;\r
-\r
-            // User Presets\r
-            foreach (Preset item in user_presets)\r
-            {\r
-                if (item.Name == name)\r
-                    return true;\r
-            }\r
-\r
-            return false;\r
+            return this.userPresets.Any(item => item.Name == name);\r
         }\r
     }\r
 }
\ No newline at end of file