OSDN Git Service

WinGui:
[handbrake-jp/handbrake-jp-git.git] / win / C# / Functions / Main.cs
1 /*  Common.cs $\r
2         \r
3            This file is part of the HandBrake source code.\r
4            Homepage: <http://handbrake.fr>.\r
5            It may be used under the terms of the GNU General Public License. */\r
6 \r
7 using System;\r
8 using System.Collections;\r
9 using System.Text;\r
10 using System.Windows.Forms;\r
11 using System.Globalization;\r
12 using System.IO;\r
13 using System.Drawing;\r
14 using System.Diagnostics;\r
15 using System.Text.RegularExpressions;\r
16 \r
17 namespace Handbrake.Functions\r
18 {\r
19     class Main\r
20     {\r
21         /// <summary>\r
22         /// Take in a File destination and change it's file extension to a new Extension\r
23         /// </summary>\r
24         /// <param name="destination"></param>\r
25         /// <param name="newExtension"></param>\r
26         /// <returns>String of the new file path and extension</returns>\r
27         public string setExtension(string destination, string newExtension)\r
28         {\r
29             destination.Replace(".mp4", newExtension);\r
30             destination.Replace(".m4v", newExtension);\r
31             destination.Replace(".mkv", newExtension);\r
32             destination.Replace(".avi", newExtension);\r
33             destination.Replace(".ogm", newExtension);\r
34 \r
35             return destination;\r
36         }\r
37 \r
38         /// <summary>\r
39         /// Calculate the duration of the selected title and chapters\r
40         /// </summary>\r
41         public TimeSpan calculateDuration(string chapter_start, string chapter_end, Parsing.Title selectedTitle)\r
42         {\r
43             TimeSpan Duration = TimeSpan.FromSeconds(0.0);\r
44 \r
45             // Get the durations between the 2 chapter points and add them together.\r
46             if (chapter_start != "Auto" && chapter_end != "Auto")\r
47             {\r
48                 int start_chapter, end_chapter = 0;\r
49                 int.TryParse(chapter_start, out start_chapter);\r
50                 int.TryParse(chapter_end, out end_chapter);\r
51 \r
52                 int position = start_chapter - 1;\r
53 \r
54                 if (start_chapter <= end_chapter)\r
55                 {\r
56                     if (end_chapter > selectedTitle.Chapters.Count)\r
57                         end_chapter = selectedTitle.Chapters.Count;\r
58 \r
59                     while (position != end_chapter)\r
60                     {\r
61                         TimeSpan dur = selectedTitle.Chapters[position].Duration;\r
62                         Duration = Duration + dur;\r
63                         position++;\r
64                     }\r
65                 }\r
66             }\r
67             return Duration;\r
68         }\r
69 \r
70         /// <summary>\r
71         /// Calculate the non-anamorphic resoltuion of the source\r
72         /// </summary>\r
73         /// <param name="width"></param>\r
74         /// <returns></returns>\r
75         public int cacluateNonAnamorphicHeight(int width, decimal top, decimal bottom, decimal left, decimal right, Parsing.Title selectedTitle)\r
76         {\r
77             float aspect = selectedTitle.AspectRatio;\r
78             int aw;\r
79             int ah;\r
80             if (aspect.ToString() == "1.78")\r
81             {\r
82                 aw = 16;\r
83                 ah = 9;\r
84             }\r
85             else\r
86             {\r
87                 aw = 4;\r
88                 ah = 3;\r
89             }\r
90 \r
91             double a = width * selectedTitle.Resolution.Width * ah * (selectedTitle.Resolution.Height - (double)top - (double)bottom);\r
92             double b = selectedTitle.Resolution.Height * aw * (selectedTitle.Resolution.Width - (double)left - (double)right);\r
93 \r
94             double y = a / b;\r
95 \r
96             // If it's not Mod 16, make it mod 16\r
97             if ((y % 16) != 0)\r
98             {\r
99                 double mod16 = y % 16;\r
100                 if (mod16 >= 8)\r
101                 {\r
102                     mod16 = 16 - mod16;\r
103                     y = y + mod16;\r
104                 }\r
105                 else\r
106                 {\r
107                     y = y - mod16;\r
108                 }\r
109             }\r
110 \r
111             //16 * (421 / 16)\r
112             //double z = ( 16 * (( y + 8 ) / 16 ) );\r
113             int x = int.Parse(y.ToString());\r
114             return x;\r
115         }\r
116 \r
117         /// <summary>\r
118         /// Select the longest title in the DVD title dropdown menu on frmMain\r
119         /// </summary>\r
120         public Handbrake.Parsing.Title selectLongestTitle(ComboBox drp_dvdtitle)\r
121         {\r
122             int current_largest = 0;\r
123             Handbrake.Parsing.Title title2Select;\r
124 \r
125             // Check if there are titles in the DVD title dropdown menu and make sure, it's not just "Automatic"\r
126             if (drp_dvdtitle.Items[0].ToString() != "Automatic")\r
127                 title2Select = (Handbrake.Parsing.Title)drp_dvdtitle.Items[0];\r
128             else\r
129                 title2Select = null;\r
130 \r
131             // So, If there are titles in the DVD Title dropdown menu, lets select the longest.\r
132             if (title2Select != null)\r
133             {\r
134                 foreach (Handbrake.Parsing.Title x in drp_dvdtitle.Items)\r
135                 {\r
136                     string title = x.ToString();\r
137                     if (title != "Automatic")\r
138                     {\r
139                         string[] y = title.Split(' ');\r
140                         string time = y[1].Replace("(", "").Replace(")", "");\r
141                         string[] z = time.Split(':');\r
142 \r
143                         int hours = int.Parse(z[0]) * 60 * 60;\r
144                         int minutes = int.Parse(z[1]) * 60;\r
145                         int seconds = int.Parse(z[2]);\r
146                         int total_sec = hours + minutes + seconds;\r
147 \r
148                         if (current_largest == 0)\r
149                         {\r
150                             current_largest = hours + minutes + seconds;\r
151                             title2Select = x;\r
152                         }\r
153                         else\r
154                         {\r
155                             if (total_sec > current_largest)\r
156                             {\r
157                                 current_largest = total_sec;\r
158                                 title2Select = x;\r
159                             }\r
160                         }\r
161                     }\r
162                 }\r
163             }\r
164             return title2Select;\r
165         }\r
166 \r
167         /// <summary>\r
168         /// Set's up the DataGridView on the Chapters tab (frmMain)\r
169         /// </summary>\r
170         /// <param name="mainWindow"></param>\r
171         public DataGridView chapterNaming(DataGridView data_chpt, string chapter_start, string chapter_end)\r
172         {\r
173             try\r
174             {\r
175                 int i = 0;\r
176                 int rowCount = 0;\r
177                 int start = 0;\r
178                 int finish = 0;\r
179                 if (chapter_end != "Auto")\r
180                     finish = int.Parse(chapter_end);\r
181 \r
182                 if (chapter_start != "Auto")\r
183                     start = int.Parse(chapter_start);\r
184 \r
185                 rowCount = finish - (start - 1);\r
186 \r
187                 while (i < rowCount)\r
188                 {\r
189                     DataGridViewRow row = new DataGridViewRow();\r
190 \r
191                     data_chpt.Rows.Insert(i, row);\r
192                     data_chpt.Rows[i].Cells[0].Value = (i + 1);\r
193                     data_chpt.Rows[i].Cells[1].Value = "Chapter " + (i + 1);\r
194                     i++;\r
195                 }\r
196                 return data_chpt;\r
197             }\r
198             catch (Exception exc)\r
199             {\r
200                 MessageBox.Show("chapterNaming() Error has occured: \n" + exc.ToString());\r
201                 return null;\r
202             }\r
203         }\r
204 \r
205         /// <summary>\r
206         /// Function which generates the filename and path automatically based on \r
207         /// the Source Name, DVD title and DVD Chapters\r
208         /// </summary>\r
209         /// <param name="mainWindow"></param>\r
210         public string autoName(ComboBox drp_dvdtitle, string chapter_start, string chatper_end, string source, string dest, int format)\r
211         {\r
212 \r
213             string AutoNamePath = string.Empty;\r
214 \r
215             if (drp_dvdtitle.Text != "Automatic")\r
216             {\r
217                 // Todo: This code is a tad messy. Clean it up at some point.\r
218                 // Get the Source Name\r
219                 string[] sourceName = source.Split('\\');\r
220                 source = sourceName[sourceName.Length - 1].Replace(".iso", "").Replace(".mpg", "").Replace(".ts", "").Replace(".ps", "");\r
221 \r
222                 // Get the Selected Title Number\r
223                 string title = drp_dvdtitle.Text;\r
224                 string[] titlesplit = title.Split(' ');\r
225                 title = titlesplit[0];\r
226 \r
227                 // Get the Chapter Start and Chapter End Numbers\r
228                 string cs = chapter_start;\r
229                 string cf = chatper_end;\r
230 \r
231                 // Just incase the above are set to their default Automatic values, set the varible to ""\r
232                 if (title == "Automatic")\r
233                     title = "";\r
234                 if (cs == "Auto")\r
235                     cs = "";\r
236                 if (cf == "Auto")\r
237                     cf = "";\r
238 \r
239                 // If both CS and CF are populated, set the dash varible\r
240                 string dash = "";\r
241                 if (cf != "Auto")\r
242                     dash = "-";\r
243 \r
244                 // Get the destination filename.\r
245                 string destination_filename = "";\r
246                 if (Properties.Settings.Default.autoNameFormat != "")\r
247                 {\r
248                     destination_filename = Properties.Settings.Default.autoNameFormat;\r
249                     destination_filename = destination_filename.Replace("{source}", source).Replace("{title}", title).Replace("{chapters}", cs + dash + cf);\r
250                 }\r
251                 else\r
252                     destination_filename = source + "_T" + title + "_C" + cs + dash + cf;\r
253 \r
254                 // If the text box is blank\r
255                 if (!dest.Contains("\\"))\r
256                 {\r
257                     string filePath = "";\r
258                     if (Properties.Settings.Default.autoNamePath.Trim() != "")\r
259                     {\r
260                         if (Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")\r
261                             filePath = Properties.Settings.Default.autoNamePath + "\\";\r
262                     }\r
263 \r
264                     if (format == 0)\r
265                         AutoNamePath = filePath + destination_filename + ".mp4";\r
266                     else if (format == 1)\r
267                         AutoNamePath = filePath + destination_filename + ".m4v";\r
268                     else if (format == 2)\r
269                         AutoNamePath = filePath + destination_filename + ".mkv";\r
270                     else if (format == 3)\r
271                         AutoNamePath = filePath + destination_filename + ".avi";\r
272                     else if (format == 4)\r
273                         AutoNamePath = filePath + destination_filename + ".ogm";\r
274                 }\r
275                 else // If the text box already has a path and file\r
276                 {\r
277                     string destination = AutoNamePath;\r
278                     string[] destName = dest.Split('\\');\r
279                     string[] extension = dest.Split('.');\r
280                     string ext = extension[extension.Length - 1];\r
281 \r
282                     destName[destName.Length - 1] = destination_filename + "." + ext;\r
283 \r
284                     string fullDest = "";\r
285                     foreach (string part in destName)\r
286                     {\r
287                         if (fullDest != "")\r
288                             fullDest = fullDest + "\\" + part;\r
289                         else\r
290                             fullDest = fullDest + part;\r
291                     }\r
292                     return fullDest;\r
293                 }\r
294             }\r
295             return AutoNamePath;\r
296         }\r
297 \r
298         /// <summary>\r
299         /// Checks for updates and returns true if an update is available.\r
300         /// </summary>\r
301         /// <param name="debug">Turns on debug mode. Don't use on program startup</param>\r
302         /// <returns>Boolean True = Update available</returns>\r
303         public Boolean updateCheck(Boolean debug)\r
304         {\r
305             try\r
306             {\r
307                 Functions.AppcastReader rssRead = new Functions.AppcastReader();\r
308                 rssRead.getInfo(); // Initializes the class.\r
309                 string build = rssRead.build();\r
310 \r
311                 int latest = int.Parse(build);\r
312                 int current = Properties.Settings.Default.hb_build;\r
313                 int skip = Properties.Settings.Default.skipversion;\r
314 \r
315                 if (latest == skip)\r
316                     return false;\r
317                 else\r
318                 {\r
319                     Boolean update = (latest > current);\r
320                     return update;\r
321                 }\r
322             }\r
323             catch (Exception exc)\r
324             {\r
325                 if (debug == true)\r
326                     MessageBox.Show("Unable to check for updates, Please try again later. \n" + exc.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
327                 return false;\r
328             }\r
329         }\r
330 \r
331         /// <summary>\r
332         /// Get's HandBrakes version data from the CLI.\r
333         /// </summary>\r
334         /// <returns>Arraylist of Version Data. 0 = hb_version 1 = hb_build</returns>\r
335         public ArrayList getCliVersionData()\r
336         {\r
337             ArrayList cliVersionData = new ArrayList();\r
338             // 0 = SVN Build / Version\r
339             // 1 = Build Date\r
340 \r
341             Process cliProcess = new Process();\r
342             ProcessStartInfo handBrakeCLI = new ProcessStartInfo("HandBrakeCLI.exe", " -u");\r
343             handBrakeCLI.UseShellExecute = false;\r
344             handBrakeCLI.RedirectStandardError = true;\r
345             handBrakeCLI.RedirectStandardOutput = true;\r
346             handBrakeCLI.CreateNoWindow = true;\r
347             cliProcess.StartInfo = handBrakeCLI;\r
348             cliProcess.Start();\r
349 \r
350             // Retrieve standard output and report back to parent thread until the process is complete\r
351             String line;\r
352             TextReader stdOutput = cliProcess.StandardError;\r
353 \r
354             while (!cliProcess.HasExited)\r
355             {\r
356                 line = stdOutput.ReadLine();\r
357                 Match m = Regex.Match(line, @"HandBrake [0-9\.]*svn[0-9]*[M]* \([0-9]*\)");\r
358                 if (m.Success != false)\r
359                 {\r
360                     string data = line.Replace("(", "").Replace(")", "").Replace("HandBrake ", "");\r
361                     string[] arr = data.Split(' ');\r
362                     cliVersionData.Add(arr[0]);\r
363                     cliVersionData.Add(arr[1]);\r
364                     return cliVersionData;\r
365                 }\r
366             }\r
367             return null;\r
368         }\r
369 \r
370         /// <summary>\r
371         /// Check if the queue recovery file contains records.\r
372         /// If it does, it means the last queue did not complete before HandBrake closed.\r
373         /// So, return a boolean if true. \r
374         /// </summary>\r
375         public Boolean check_queue_recovery()\r
376         {\r
377             try\r
378             {\r
379                 string tempPath = Path.Combine(Path.GetTempPath(), "hb_queue_recovery.dat");\r
380                 using (StreamReader reader = new StreamReader(tempPath))\r
381                 {\r
382                     string queue_item = reader.ReadLine();\r
383                     if (queue_item == null)\r
384                     {\r
385                         reader.Close();\r
386                         reader.Dispose();\r
387                         return false;\r
388                     }\r
389                     else // There exists an item in the recovery queue file, so try and recovr it.\r
390                     {\r
391                         reader.Close();\r
392                         reader.Dispose();\r
393                         return true;\r
394                     }\r
395                 }\r
396             }\r
397             catch (Exception)\r
398             {\r
399                 // Keep quiet about the error.\r
400                 return false;\r
401             }\r
402         }\r
403 \r
404     }\r
405 }