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