OSDN Git Service

WinGui:
[handbrake-jp/handbrake-jp-git.git] / win / C# / Functions / Main.cs
1 /*  Main.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.Windows.Forms;\r
9 using System.IO;\r
10 using System.Diagnostics;\r
11 using System.Text.RegularExpressions;\r
12 using System.Collections.Generic;\r
13 using System.Xml.Serialization;\r
14 \r
15 namespace Handbrake.Functions\r
16 {\r
17     static class Main\r
18     {\r
19         // Private Variables\r
20         private static readonly XmlSerializer ser = new XmlSerializer(typeof(List<Queue.QueueItem>));\r
21 \r
22         /// <summary>\r
23         /// Calculate the duration of the selected title and chapters\r
24         /// </summary>\r
25         public static TimeSpan calculateDuration(string chapter_start, string chapter_end, Parsing.Title selectedTitle)\r
26         {\r
27             TimeSpan Duration = TimeSpan.FromSeconds(0.0);\r
28 \r
29             // Get the durations between the 2 chapter points and add them together.\r
30             if (chapter_start != "Auto" && chapter_end != "Auto")\r
31             {\r
32                 int start_chapter, end_chapter;\r
33                 int.TryParse(chapter_start, out start_chapter);\r
34                 int.TryParse(chapter_end, out end_chapter);\r
35 \r
36                 int position = start_chapter - 1;\r
37 \r
38                 if (start_chapter <= end_chapter)\r
39                 {\r
40                     if (end_chapter > selectedTitle.Chapters.Count)\r
41                         end_chapter = selectedTitle.Chapters.Count;\r
42 \r
43                     while (position != end_chapter)\r
44                     {\r
45                         TimeSpan dur = selectedTitle.Chapters[position].Duration;\r
46                         Duration = Duration + dur;\r
47                         position++;\r
48                     }\r
49                 }\r
50             }\r
51             return Duration;\r
52         }\r
53 \r
54         /// <summary>\r
55         /// Calculate the non-anamorphic resoltuion of the source\r
56         /// </summary>\r
57         /// <param name="width"></param>\r
58         /// <param name="top"></param>\r
59         /// <param name="bottom"></param>\r
60         /// <param name="left"></param>\r
61         /// <param name="right"></param>\r
62         /// <param name="selectedTitle"></param>\r
63         /// <returns></returns>\r
64         public static int cacluateNonAnamorphicHeight(int width, decimal top, decimal bottom, decimal left, decimal right, Parsing.Title selectedTitle)\r
65         {\r
66             float aspect = selectedTitle.AspectRatio;\r
67             int aw = 0;\r
68             int ah = 0;\r
69             if (aspect.ToString() == "1.78")\r
70             {\r
71                 aw = 16;\r
72                 ah = 9;\r
73             }\r
74             else if (aspect.ToString() == "1.33")\r
75             {\r
76                 aw = 4;\r
77                 ah = 3;\r
78             }\r
79 \r
80             if (aw != 0)\r
81             {\r
82                 double a = width * selectedTitle.Resolution.Width * ah * (selectedTitle.Resolution.Height - (double)top - (double)bottom);\r
83                 double b = selectedTitle.Resolution.Height * aw * (selectedTitle.Resolution.Width - (double)left - (double)right);\r
84 \r
85                 double y = a / b;\r
86 \r
87                 // If it's not Mod 16, make it mod 16\r
88                 if ((y % 16) != 0)\r
89                 {\r
90                     double mod16 = y % 16;\r
91                     if (mod16 >= 8)\r
92                     {\r
93                         mod16 = 16 - mod16;\r
94                         y = y + mod16;\r
95                     }\r
96                     else\r
97                     {\r
98                         y = y - mod16;\r
99                     }\r
100                 }\r
101 \r
102                 //16 * (421 / 16)\r
103                 //double z = ( 16 * (( y + 8 ) / 16 ) );\r
104                 int x = int.Parse(y.ToString());\r
105                 return x;\r
106             }\r
107             return 0;\r
108         }\r
109 \r
110         /// <summary>\r
111         /// Select the longest title in the DVD title dropdown menu on frmMain\r
112         /// </summary>\r
113         public static Parsing.Title selectLongestTitle(ComboBox drp_dvdtitle)\r
114         {\r
115             int current_largest = 0;\r
116             Parsing.Title title2Select;\r
117 \r
118             // Check if there are titles in the DVD title dropdown menu and make sure, it's not just "Automatic"\r
119             if (drp_dvdtitle.Items[0].ToString() != "Automatic")\r
120                 title2Select = (Parsing.Title)drp_dvdtitle.Items[0];\r
121             else\r
122                 title2Select = null;\r
123 \r
124             // So, If there are titles in the DVD Title dropdown menu, lets select the longest.\r
125             if (title2Select != null)\r
126             {\r
127                 foreach (Parsing.Title x in drp_dvdtitle.Items)\r
128                 {\r
129                     string title = x.ToString();\r
130                     if (title != "Automatic")\r
131                     {\r
132                         string[] y = title.Split(' ');\r
133                         string time = y[1].Replace("(", "").Replace(")", "");\r
134                         string[] z = time.Split(':');\r
135 \r
136                         int hours = int.Parse(z[0]) * 60 * 60;\r
137                         int minutes = int.Parse(z[1]) * 60;\r
138                         int seconds = int.Parse(z[2]);\r
139                         int total_sec = hours + minutes + seconds;\r
140 \r
141                         if (current_largest == 0)\r
142                         {\r
143                             current_largest = hours + minutes + seconds;\r
144                             title2Select = x;\r
145                         }\r
146                         else\r
147                         {\r
148                             if (total_sec > current_largest)\r
149                             {\r
150                                 current_largest = total_sec;\r
151                                 title2Select = x;\r
152                             }\r
153                         }\r
154                     }\r
155                 }\r
156             }\r
157             return title2Select;\r
158         }\r
159 \r
160         /// <summary>\r
161         /// Set's up the DataGridView on the Chapters tab (frmMain)\r
162         /// </summary>\r
163         public static DataGridView chapterNaming(DataGridView data_chpt, string chapter_end)\r
164         {\r
165             int i = 0, finish = 0;\r
166 \r
167             if (chapter_end != "Auto")\r
168                 int.TryParse(chapter_end, out finish);\r
169 \r
170             while (i < finish)\r
171             {\r
172                 int n = data_chpt.Rows.Add();\r
173                 data_chpt.Rows[n].Cells[0].Value = (i + 1);\r
174                 data_chpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);\r
175                 data_chpt.Rows[n].Cells[0].ValueType = typeof(int);\r
176                 data_chpt.Rows[n].Cells[1].ValueType = typeof(string);\r
177                 i++;\r
178             }\r
179 \r
180             return data_chpt;\r
181         }\r
182 \r
183         /// <summary>\r
184         /// Function which generates the filename and path automatically based on \r
185         /// the Source Name, DVD title and DVD Chapters\r
186         /// </summary>\r
187         public static string autoName(ComboBox drp_dvdtitle, string chapter_start, string chatper_end, string source, string dest, int format)\r
188         {\r
189             string AutoNamePath = string.Empty;\r
190             if (drp_dvdtitle.Text != "Automatic")\r
191             {\r
192                 // Get the Source Name \r
193                 string sourceName = Path.GetFileNameWithoutExtension(source);\r
194 \r
195                 // Get the Selected Title Number\r
196                 string[] titlesplit = drp_dvdtitle.Text.Split(' ');\r
197                 string dvdTitle = titlesplit[0].Replace("Automatic", "");\r
198 \r
199                 // Get the Chapter Start and Chapter End Numbers\r
200                 string chapterStart = chapter_start.Replace("Auto", "");\r
201                 string chapterFinish = chatper_end.Replace("Auto", "");\r
202                 string combinedChapterTag = chapterStart;\r
203                 if (chapterFinish != chapterStart && chapterFinish != "")\r
204                     combinedChapterTag = chapterStart + "-" + chapterFinish;\r
205 \r
206                 // Get the destination filename.\r
207                 string destination_filename;\r
208                 if (Properties.Settings.Default.autoNameFormat != "")\r
209                 {\r
210                     destination_filename = Properties.Settings.Default.autoNameFormat;\r
211                     destination_filename = destination_filename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace("{chapters}", combinedChapterTag);\r
212                 }\r
213                 else\r
214                     destination_filename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;\r
215 \r
216                 // Add the appropriate file extension\r
217                 if (format == 0)\r
218                     destination_filename += ".mp4";\r
219                 else if (format == 1)\r
220                     destination_filename += ".m4v";\r
221                 else if (format == 2)\r
222                     destination_filename += ".mkv";\r
223 \r
224                 // Now work out the path where the file will be stored.\r
225                 // First case: If the destination box doesn't already contain a path, make one.\r
226                 if (!dest.Contains(Path.DirectorySeparatorChar.ToString()))\r
227                 {\r
228                     // If there is an auto name path, use it...\r
229                     if (Properties.Settings.Default.autoNamePath.Trim() != "" && Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")\r
230                         AutoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destination_filename);\r
231                     else // ...otherwise, output to the source directory\r
232                         AutoNamePath = null;\r
233                 }\r
234                 else // Otherwise, use the path that is already there.\r
235                 {\r
236                     // Use the path and change the file extension to match the previous destination\r
237                     AutoNamePath = Path.Combine(Path.GetDirectoryName(dest), destination_filename);\r
238                     AutoNamePath = Path.ChangeExtension(AutoNamePath, Path.GetExtension(dest));\r
239                 }\r
240             }\r
241 \r
242             return AutoNamePath;\r
243         }\r
244 \r
245         /// <summary>\r
246         /// Checks for updates and returns true if an update is available.\r
247         /// </summary>\r
248         /// <param name="debug">Turns on debug mode. Don't use on program startup</param>\r
249         /// <returns>Boolean True = Update available</returns>\r
250         public static Boolean updateCheck(Boolean debug)\r
251         {\r
252             try\r
253             {\r
254                 AppcastReader rssRead = new AppcastReader();\r
255                 rssRead.getInfo(); // Initializes the class.\r
256                 string build = rssRead.build();\r
257 \r
258                 int latest = int.Parse(build);\r
259                 int current = Properties.Settings.Default.hb_build;\r
260                 int skip = Properties.Settings.Default.skipversion;\r
261 \r
262                 if (latest == skip)\r
263                     return false;\r
264 \r
265                 Boolean update = (latest > current);\r
266                 return update;\r
267             }\r
268             catch (Exception exc)\r
269             {\r
270                 if (debug)\r
271                     MessageBox.Show("Unable to check for updates, Please try again later. \n" + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
272                 return false;\r
273             }\r
274         }\r
275 \r
276         /// <summary>\r
277         /// Get's HandBrakes version data from the CLI.\r
278         /// </summary>\r
279         /// <returns>Arraylist of Version Data. 0 = hb_version 1 = hb_build</returns>\r
280         public static void setCliVersionData()\r
281         {\r
282             String line;\r
283 \r
284             // 0 = SVN Build / Version\r
285             // 1 = Build Date\r
286             Process cliProcess = new Process();\r
287             ProcessStartInfo handBrakeCLI = new ProcessStartInfo("HandBrakeCLI.exe", " -u")\r
288                                                 {\r
289                                                     UseShellExecute = false,\r
290                                                     RedirectStandardError = true,\r
291                                                     RedirectStandardOutput = true,\r
292                                                     CreateNoWindow = true\r
293                                                 };\r
294             cliProcess.StartInfo = handBrakeCLI;\r
295 \r
296             try\r
297             {\r
298                 cliProcess.Start();\r
299                 cliProcess.Kill();\r
300                 // Retrieve standard output and report back to parent thread until the process is complete\r
301                 TextReader stdOutput = cliProcess.StandardError;\r
302 \r
303                 while (!cliProcess.HasExited)\r
304                 {\r
305                     line = stdOutput.ReadLine() ?? "";\r
306                     Match m = Regex.Match(line, @"HandBrake ([0-9\.]*)*(svn[0-9]*[M]*)* \([0-9]*\)");\r
307 \r
308                     if (m.Success)\r
309                     {\r
310                         string data = line.Replace("(", "").Replace(")", "").Replace("HandBrake ", "");\r
311                         string[] arr = data.Split(' ');\r
312 \r
313                         Properties.Settings.Default.hb_build = int.Parse(arr[1]);\r
314                         Properties.Settings.Default.hb_version = arr[0];\r
315                     }\r
316                     if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.\r
317                         killCLI();\r
318 \r
319                 }\r
320             }\r
321             catch (Exception e)\r
322             {\r
323                 MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);\r
324             }\r
325         }\r
326 \r
327         /// <summary>\r
328         /// Search through the running processes on the system and kill HandBrakeCLI\r
329         /// </summary>\r
330         private static void killCLI()\r
331         {\r
332             string AppName = "HandBrakeCLI";\r
333             AppName = AppName.ToUpper();\r
334 \r
335             Process[] prs = Process.GetProcesses();\r
336             foreach (Process proces in prs)\r
337             {\r
338                 if (proces.ProcessName.ToUpper() == AppName)\r
339                 {\r
340                     proces.Refresh();\r
341                     if (!proces.HasExited)\r
342                         proces.Kill();\r
343                 }\r
344             }\r
345         }\r
346 \r
347         /// <summary>\r
348         /// Check if the queue recovery file contains records.\r
349         /// If it does, it means the last queue did not complete before HandBrake closed.\r
350         /// So, return a boolean if true. \r
351         /// </summary>\r
352         public static Boolean check_queue_recovery()\r
353         {\r
354             try\r
355             {\r
356                 string tempPath = Path.Combine(Path.GetTempPath(), "hb_queue_recovery.xml");\r
357                 if (File.Exists(tempPath))\r
358                 {\r
359                     using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))\r
360                     {\r
361                         List<Queue.QueueItem> list = ser.Deserialize(strm) as List<Queue.QueueItem>;\r
362                         if (list != null)\r
363                             if (list.Count != 0)\r
364                                 return true;\r
365                     }\r
366                 }\r
367                 return false;\r
368             }\r
369             catch (Exception)\r
370             {\r
371                 return false; // Keep quiet about the error.\r
372             }\r
373         }\r
374 \r
375     }\r
376 }\r