OSDN Git Service

Reverting 3452
[handbrake-jp/handbrake-jp-git.git] / win / C# / Presets / PresetsHandler.cs
1 /*  PresetHandler.cs $\r
2     This file is part of the HandBrake source code.\r
3     Homepage: <http://handbrake.fr>.\r
4     It may be used under the terms of the GNU General Public License. */\r
5 \r
6 namespace Handbrake.Presets\r
7 {\r
8     using System;\r
9     using System.Collections.Generic;\r
10     using System.Diagnostics;\r
11     using System.Drawing;\r
12     using System.IO;\r
13     using System.Linq;\r
14     using System.Text.RegularExpressions;\r
15     using System.Windows.Forms;\r
16     using System.Xml.Serialization;\r
17 \r
18     /// <summary>\r
19     /// The Preset Handler Class\r
20     /// </summary>\r
21     public class PresetsHandler\r
22     {\r
23         /// <summary>\r
24         /// The User Preset file\r
25         /// </summary>\r
26         private readonly string userPresetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\user_presets.xml";\r
27 \r
28         /// <summary>\r
29         /// The Built In Presets File\r
30         /// </summary>\r
31         private readonly string hbPresetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\presets.xml";\r
32 \r
33         /// <summary>\r
34         /// XML Serializer\r
35         /// </summary>\r
36         private static readonly XmlSerializer Ser = new XmlSerializer(typeof(List<Preset>));\r
37 \r
38         /// <summary>\r
39         /// A List of built-in presets\r
40         /// </summary>\r
41         private List<Preset> presets = new List<Preset>();\r
42 \r
43         /// <summary>\r
44         /// A List of user presets\r
45         /// </summary>\r
46         private List<Preset> userPresets = new List<Preset>();\r
47 \r
48         /// <summary>\r
49         ///  Last preset added\r
50         /// </summary>\r
51         public Preset LastPresetAdded { get; set; }\r
52 \r
53         /// <summary>\r
54         /// Add a new preset to the system\r
55         /// </summary>\r
56         /// <param name="presetName">\r
57         /// String, The name of the new preset\r
58         /// </param>\r
59         /// <param name="query">\r
60         /// String, the CLI query for the new preset\r
61         /// </param>\r
62         /// <param name="pictureSettings">\r
63         /// Bool, store crop/picture sizes in the Presets\r
64         /// </param>\r
65         /// <returns>\r
66         /// The add.\r
67         /// </returns>\r
68         public bool Add(string presetName, string query, bool pictureSettings)\r
69         {\r
70             if (this.CheckIfPresetExists(presetName) == false)\r
71             {\r
72                 Preset newPreset = new Preset\r
73                                        {\r
74                                            Name = presetName, \r
75                                            Query = query, \r
76                                            CropSettings = pictureSettings, \r
77                                            Version = Properties.Settings.Default.hb_version\r
78                                        };\r
79                 this.userPresets.Add(newPreset);\r
80                 this.UpdatePresetFiles();\r
81                 this.LastPresetAdded = newPreset;\r
82                 return true;\r
83             }\r
84             return false;\r
85         }\r
86 \r
87         /// <summary>\r
88         /// Remove a preset with a given name from either the built in or user preset list.\r
89         /// </summary>\r
90         /// <param name="name">String, the preset name</param>\r
91         public void Remove(string name)\r
92         {\r
93             List<Preset> newPresets = new List<Preset>();\r
94             List<Preset> newUserPresets = new List<Preset>();\r
95 \r
96             // Built In Presets\r
97             foreach (Preset item in this.presets)\r
98             {\r
99                 if (item.Name != name)\r
100                 {\r
101                     newPresets.Add(item);\r
102                 }\r
103             }\r
104             this.presets = newPresets;\r
105 \r
106             // User Presets\r
107             foreach (Preset item in this.userPresets)\r
108             {\r
109                 if (item.Name != name)\r
110                 {\r
111                     newUserPresets.Add(item);\r
112                 }\r
113             }\r
114             this.userPresets = newUserPresets;\r
115 \r
116             // Rebuild the UserPresets.xml file\r
117             this.UpdatePresetFiles();\r
118             this.UpdatePresetFiles();\r
119         }\r
120 \r
121         /// <summary>\r
122         /// Remove all built in Presets;\r
123         /// </summary>\r
124         public void RemoveBuiltInPresets()\r
125         {\r
126             this.presets.Clear();\r
127             this.UpdatePresetFiles();\r
128         }\r
129 \r
130         /// <summary>\r
131         /// Save changes to a given preset in the user preset list.\r
132         /// </summary>\r
133         /// <param name="presetName">String, The name of the new preset</param>\r
134         /// <param name="query">String, the CLI query for the new preset</param>\r
135         /// <param name="pictureSettings"> Bool, store crop/picture sizes in the preset</param>\r
136         public void Update(string presetName, string query, bool pictureSettings)\r
137         {\r
138             // User Presets\r
139             foreach (Preset item in this.userPresets)\r
140             {\r
141                 if (item.Name == presetName)\r
142                 {\r
143                     item.Query = query;\r
144                     item.CropSettings = pictureSettings;\r
145                     MessageBox.Show(\r
146                         "Changes to \"" + presetName + "\" Saved",\r
147                                     "Success",\r
148                                     MessageBoxButtons.OK, \r
149                                     MessageBoxIcon.Information);\r
150                     this.UpdatePresetFiles();\r
151                 }\r
152             }\r
153         }\r
154 \r
155         /// <summary>\r
156         /// Return the CLI query for a preset name given in name\r
157         /// </summary>\r
158         /// <param name="name">String, The preset's name</param>\r
159         /// <returns>String, the CLI query for the given preset name</returns>    not\r
160         public Preset GetPreset(string name)\r
161         {\r
162             // Built In Presets\r
163             foreach (Preset item in this.presets)\r
164             {\r
165                 if (item.Name == name)\r
166                     return item;\r
167             }\r
168 \r
169             // User Presets\r
170             return this.userPresets.FirstOrDefault(item => item.Name == name);\r
171         }\r
172 \r
173         /// <summary>\r
174         /// Reads the CLI's CLI output format and load's them into the preset List Preset\r
175         /// </summary>\r
176         public void UpdateBuiltInPresets()\r
177         {\r
178             // Create a new tempory file and execute the CLI to get the built in Presets.\r
179             string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");\r
180             string presetsPath = Path.Combine(Path.GetTempPath(), "temp_presets.dat");\r
181             string strCmdLine = String.Format(@"cmd /c """"{0}"" --preset-list >""{1}"" 2>&1""", handbrakeCLIPath, presetsPath);\r
182 \r
183             ProcessStartInfo hbGetPresets = new ProcessStartInfo("CMD.exe", strCmdLine)\r
184                                                 {\r
185                                                    WindowStyle = ProcessWindowStyle.Hidden\r
186                                                 };\r
187             Process hbproc = Process.Start(hbGetPresets);\r
188             if (hbproc != null)\r
189             {\r
190                 hbproc.WaitForExit();\r
191                 hbproc.Dispose();\r
192                 hbproc.Close();\r
193             }\r
194 \r
195             // Clear the current built in Presets and now parse the tempory Presets file.\r
196             this.presets.Clear();\r
197 \r
198             if (File.Exists(presetsPath))\r
199             {\r
200                 StreamReader presetInput = new StreamReader(presetsPath);\r
201 \r
202                 string category = String.Empty;\r
203 \r
204                 while (!presetInput.EndOfStream)\r
205                 {\r
206                     string line = presetInput.ReadLine();\r
207                     if (line.Contains("<") && !line.Contains("<<")) // Found the beginning of a preset block \r
208                         category = line.Replace("<", string.Empty).Trim();\r
209 \r
210                     if (line.Contains("+")) // A Preset\r
211                     {\r
212                         Regex r = new Regex("(:  )"); // Split on hyphens. \r
213                         string[] presetName = r.Split(line);\r
214 \r
215                         bool pic = false;\r
216                         if (presetName[2].Contains("crop"))\r
217                             pic = true;\r
218 \r
219                         Preset newPreset = new Preset\r
220                                                {\r
221                                                    Category = category, \r
222                                                    Name = presetName[0].Replace("+", string.Empty).Trim(), \r
223                                                    Query = presetName[2], \r
224                                                    Version = Properties.Settings.Default.hb_version, \r
225                                                    CropSettings = pic\r
226                                                };\r
227                         this.presets.Add(newPreset);\r
228                     }\r
229                 }\r
230                 presetInput.Close();\r
231                 presetInput.Dispose();\r
232             }\r
233 \r
234             // Finally, Create a new or update the current Presets.xml file\r
235             this.UpdatePresetFiles();\r
236         }\r
237 \r
238         /// <summary>\r
239         /// Setup the frmMain preset panel\r
240         /// </summary>\r
241         /// <param name="presetPanel">The Preset Panel from the Main Window</param>\r
242         public void GetPresetPanel(ref TreeView presetPanel)\r
243         {\r
244             this.LoadPresetData();\r
245             presetPanel.Nodes.Clear();\r
246             string category = string.Empty;\r
247             TreeNode rootNode = null;\r
248 \r
249             if (this.presets.Count != 0) // Built In Presets\r
250             {\r
251                 foreach (Preset preset in this.presets)\r
252                 {\r
253                     if (preset.Category != category)\r
254                     {\r
255                         rootNode = new TreeNode(preset.Category);\r
256                         presetPanel.Nodes.Add(rootNode);\r
257                         category = preset.Category;\r
258                     }\r
259 \r
260                     if (preset.Category == category && rootNode != null)\r
261                         rootNode.Nodes.Add(preset.Name);\r
262                 }\r
263             }\r
264 \r
265             rootNode = null;\r
266             category = null;\r
267             foreach (Preset preset in this.userPresets) // User Presets\r
268             {\r
269                 if (preset.Category != category && preset.Category != string.Empty)\r
270                 {\r
271                     rootNode = new TreeNode(preset.Category) {ForeColor = Color.Black};\r
272                     presetPanel.Nodes.Add(rootNode);\r
273                     category = preset.Category;\r
274                 }\r
275 \r
276                 if (preset.Category == category && rootNode != null)\r
277                     rootNode.Nodes.Add(new TreeNode(preset.Name) {ForeColor = Color.Black});\r
278                 else\r
279                     presetPanel.Nodes.Add(new TreeNode(preset.Name) {ForeColor = Color.Black});\r
280             }\r
281         }\r
282 \r
283         /// <summary>\r
284         /// Check if the user preset "name" exists in UserPresets list.\r
285         /// </summary>\r
286         /// <param name="name">Name of the preset</param>\r
287         /// <returns>true if found</returns>\r
288         public bool CheckIfUserPresetExists(string name)\r
289         {\r
290             return name != string.Empty && this.userPresets.Any(item => item.Name == name);\r
291         }\r
292 \r
293         /// <summary>\r
294         /// Check if the built in Presets stored are not out of date.\r
295         /// Update them if they are.\r
296         /// </summary>\r
297         /// <returns>true if out of date</returns>\r
298         public bool CheckIfPresetsAreOutOfDate()\r
299         {\r
300             this.LoadPresetData();\r
301             // Update built-in Presets if the built-in Presets belong to an older version.\r
302             if (this.presets.Count != 0)\r
303                 if (this.presets[0].Version != Properties.Settings.Default.hb_version)\r
304                 {\r
305                     this.UpdateBuiltInPresets();\r
306                     return true;\r
307                 }\r
308 \r
309             return false;\r
310         }\r
311 \r
312         /// <summary>\r
313         /// Load in the preset data from Presets.xml and UserPresets.xml\r
314         /// Load it into the 2 arraylist's Presets and UserPresets\r
315         /// </summary>\r
316         private void LoadPresetData()\r
317         {\r
318             // First clear the Presets arraylists\r
319             this.presets.Clear();\r
320             this.userPresets.Clear();\r
321 \r
322             try\r
323             {\r
324                 // Load in the users Presets from UserPresets.xml\r
325                 if (File.Exists(this.hbPresetFile))\r
326                 {\r
327                     using (FileStream strm = new FileStream(this.hbPresetFile, FileMode.Open, FileAccess.Read))\r
328                     {\r
329                         if (strm.Length != 0)\r
330                         {\r
331                             List<Preset> list = Ser.Deserialize(strm) as List<Preset>;\r
332 \r
333                             if (list != null)\r
334                                 foreach (Preset preset in list)\r
335                                     this.presets.Add(preset);\r
336                         }\r
337                     }\r
338                 }\r
339             }\r
340             catch (Exception)\r
341             {\r
342                 MessageBox.Show(\r
343                     "HandBrakes preset file appears to have been corrupted. This file will now be re-generated!\n" +\r
344                     "If the problem presists, please delete the file: \n\n" + this.hbPresetFile, \r
345                     "Error",\r
346                     MessageBoxButtons.OK, \r
347                     MessageBoxIcon.Error);\r
348                 this.UpdateBuiltInPresets();\r
349             }\r
350 \r
351             try\r
352             {\r
353                 // Load in the users Presets from UserPresets.xml\r
354                 if (File.Exists(this.userPresetFile))\r
355                 {\r
356                     using (FileStream strm = new FileStream(this.userPresetFile, FileMode.Open, FileAccess.Read))\r
357                     {\r
358                         if (strm.Length != 0)\r
359                         {\r
360                             List<Preset> list = Ser.Deserialize(strm) as List<Preset>;\r
361 \r
362                             if (list != null)\r
363                                 foreach (Preset preset in list)\r
364                                     this.userPresets.Add(preset);\r
365                         }\r
366                     }\r
367                 }\r
368             }\r
369             catch (Exception)\r
370             {\r
371                 MessageBox.Show(\r
372                     "Your User presets file appears to have been corrupted.\n" +\r
373                     "Your presets will not be loaded. You may need to re-create your presets.\n\n" +\r
374                     "Your user presets file has been renamed to 'user_presets.xml.old' and is located in:\n " +\r
375                     Path.GetDirectoryName(this.userPresetFile) + "\n" + \r
376                     "You may be able to recover some presets if you know the XML language.", \r
377                     "Error",\r
378                     MessageBoxButtons.OK, \r
379                     MessageBoxIcon.Error);\r
380 \r
381                 // Recover from Error.\r
382                 if (File.Exists(this.userPresetFile))\r
383                 {\r
384                     string disabledFile = this.userPresetFile + ".old";\r
385                     if (File.Exists(disabledFile))\r
386                         File.Delete(disabledFile);\r
387                     File.Move(this.userPresetFile, disabledFile);\r
388                 }\r
389             }\r
390         }\r
391 \r
392         /// <summary>\r
393         /// Update the preset files\r
394         /// </summary>\r
395         private void UpdatePresetFiles()\r
396         {\r
397             try\r
398             {\r
399                 using (FileStream strm = new FileStream(this.hbPresetFile, FileMode.Create, FileAccess.Write))\r
400                 {\r
401                     Ser.Serialize(strm, this.presets);\r
402                     strm.Close();\r
403                     strm.Dispose();\r
404                 }\r
405 \r
406                 using (FileStream strm = new FileStream(this.userPresetFile, FileMode.Create, FileAccess.Write))\r
407                 {\r
408                     Ser.Serialize(strm, this.userPresets);\r
409                     strm.Close();\r
410                     strm.Dispose();\r
411                 }\r
412             }\r
413             catch (Exception exc)\r
414             {\r
415                 MessageBox.Show(\r
416                     "Unable to write to the file. Please make sure the location has the correct permissions for file writing.\n Error Information: \n\n" +\r
417                     exc, \r
418                     "Error", \r
419                     MessageBoxButtons.OK, \r
420                     MessageBoxIcon.Hand);\r
421             }\r
422         }\r
423 \r
424         /// <summary>\r
425         /// Check if the preset "name" exists in either Presets or UserPresets lists.\r
426         /// </summary>\r
427         /// <param name="name">Name of the preset</param>\r
428         /// <returns>True if found</returns>\r
429         private bool CheckIfPresetExists(string name)\r
430         {\r
431             if (name == string.Empty)\r
432                 return true;\r
433 \r
434             // Built In Presets\r
435             foreach (Preset item in this.presets)\r
436             {\r
437                 if (item.Name == name)\r
438                     return true;\r
439             }\r
440 \r
441             // User Presets\r
442             return this.userPresets.Any(item => item.Name == name);\r
443         }\r
444     }\r
445 }