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 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 = 0;\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         /// <returns></returns>\r
60         public int cacluateNonAnamorphicHeight(int width, decimal top, decimal bottom, decimal left, decimal right, Parsing.Title selectedTitle)\r
61         {\r
62             float aspect = selectedTitle.AspectRatio;\r
63             int aw = 0;\r
64             int ah = 0;\r
65             if (aspect.ToString() == "1.78")\r
66             {\r
67                 aw = 16;\r
68                 ah = 9;\r
69             }\r
70             else if (aspect.ToString() == "1.33")\r
71             {\r
72                 aw = 4;\r
73                 ah = 3;\r
74             }\r
75 \r
76             if (aw != 0)\r
77             {\r
78                 double a = width * selectedTitle.Resolution.Width * ah * (selectedTitle.Resolution.Height - (double)top - (double)bottom);\r
79                 double b = selectedTitle.Resolution.Height * aw * (selectedTitle.Resolution.Width - (double)left - (double)right);\r
80 \r
81                 double y = a / b;\r
82 \r
83                 // If it's not Mod 16, make it mod 16\r
84                 if ((y % 16) != 0)\r
85                 {\r
86                     double mod16 = y % 16;\r
87                     if (mod16 >= 8)\r
88                     {\r
89                         mod16 = 16 - mod16;\r
90                         y = y + mod16;\r
91                     }\r
92                     else\r
93                     {\r
94                         y = y - mod16;\r
95                     }\r
96                 }\r
97 \r
98                 //16 * (421 / 16)\r
99                 //double z = ( 16 * (( y + 8 ) / 16 ) );\r
100                 int x = int.Parse(y.ToString());\r
101                 return x;\r
102             }\r
103             return 0;\r
104         }\r
105 \r
106         /// <summary>\r
107         /// Select the longest title in the DVD title dropdown menu on frmMain\r
108         /// </summary>\r
109         public Parsing.Title selectLongestTitle(ComboBox drp_dvdtitle)\r
110         {\r
111             int current_largest = 0;\r
112             Handbrake.Parsing.Title title2Select;\r
113 \r
114             // Check if there are titles in the DVD title dropdown menu and make sure, it's not just "Automatic"\r
115             if (drp_dvdtitle.Items[0].ToString() != "Automatic")\r
116                 title2Select = (Handbrake.Parsing.Title)drp_dvdtitle.Items[0];\r
117             else\r
118                 title2Select = null;\r
119 \r
120             // So, If there are titles in the DVD Title dropdown menu, lets select the longest.\r
121             if (title2Select != null)\r
122             {\r
123                 foreach (Handbrake.Parsing.Title x in drp_dvdtitle.Items)\r
124                 {\r
125                     string title = x.ToString();\r
126                     if (title != "Automatic")\r
127                     {\r
128                         string[] y = title.Split(' ');\r
129                         string time = y[1].Replace("(", "").Replace(")", "");\r
130                         string[] z = time.Split(':');\r
131 \r
132                         int hours = int.Parse(z[0]) * 60 * 60;\r
133                         int minutes = int.Parse(z[1]) * 60;\r
134                         int seconds = int.Parse(z[2]);\r
135                         int total_sec = hours + minutes + seconds;\r
136 \r
137                         if (current_largest == 0)\r
138                         {\r
139                             current_largest = hours + minutes + seconds;\r
140                             title2Select = x;\r
141                         }\r
142                         else\r
143                         {\r
144                             if (total_sec > current_largest)\r
145                             {\r
146                                 current_largest = total_sec;\r
147                                 title2Select = x;\r
148                             }\r
149                         }\r
150                     }\r
151                 }\r
152             }\r
153             return title2Select;\r
154         }\r
155 \r
156         /// <summary>\r
157         /// Set's up the DataGridView on the Chapters tab (frmMain)\r
158         /// </summary>\r
159         /// <param name="mainWindow"></param>\r
160         public DataGridView chapterNaming(DataGridView data_chpt, string chapter_end)\r
161         {\r
162             int i = 0, finish = 0;\r
163 \r
164             if (chapter_end != "Auto")\r
165                 int.TryParse(chapter_end, out finish);\r
166 \r
167             while (i < finish)\r
168             {\r
169                 int n = data_chpt.Rows.Add();\r
170                 data_chpt.Rows[n].Cells[0].Value = (i + 1);\r
171                 data_chpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);\r
172                 data_chpt.Rows[n].Cells[0].ValueType = typeof(int);\r
173                 data_chpt.Rows[n].Cells[1].ValueType = typeof(string);\r
174                 i++;\r
175             }\r
176     \r
177             return data_chpt;\r
178         }\r
179 \r
180         /// <summary>\r
181         /// Function which generates the filename and path automatically based on \r
182         /// the Source Name, DVD title and DVD Chapters\r
183         /// </summary>\r
184         /// <param name="mainWindow"></param>\r
185         public string autoName(ComboBox drp_dvdtitle, string chapter_start, string chatper_end, string source, string dest, int format)\r
186         {\r
187             string AutoNamePath = string.Empty;\r
188             if (drp_dvdtitle.Text != "Automatic")\r
189             {\r
190                 // Get the Source Name - THIS NEEDS FIXED\r
191                 string[] sourceName = source.Split('\\');\r
192                 source = sourceName[sourceName.Length - 1].Replace(".iso", "").Replace(".mpg", "").Replace(".ts", "").Replace(".ps", "");\r
193                 source.Replace(".wmv", "").Replace(".mp4", "").Replace(".m4v", "").Replace(".avi", "").Replace(".ogm", "").Replace(".tivo", "").Replace(".img", "");\r
194                 source.Replace(".mov", "").Replace(".rm", "");\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}", source).Replace("{title}", dvdTitle).Replace("{chapters}", combinedChapterTag);\r
213                 }\r
214                 else\r
215                     destination_filename = source + "_T" + dvdTitle + "_C" + combinedChapterTag;\r
216 \r
217                 // Now work out the path where the file will be stored.\r
218                 // First case: If the destination box doesn't already contain a path, make one.\r
219                 if (!dest.Contains("\\"))\r
220                 {\r
221                     string filePath = "";\r
222                     if (Properties.Settings.Default.autoNamePath.Trim() != "")\r
223                     {\r
224                         if (Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")\r
225                             filePath = Properties.Settings.Default.autoNamePath + "\\";\r
226                     }\r
227 \r
228                     if (format == 0)\r
229                         AutoNamePath = filePath + destination_filename + ".mp4";\r
230                     else if (format == 1)\r
231                         AutoNamePath = filePath + destination_filename + ".m4v";\r
232                     else if (format == 2)\r
233                         AutoNamePath = filePath + destination_filename + ".mkv";\r
234                     else if (format == 3)\r
235                         AutoNamePath = filePath + destination_filename + ".avi";\r
236                     else if (format == 4)\r
237                         AutoNamePath = filePath + destination_filename + ".ogm";\r
238                 }\r
239                 else // Otherwise, use the path that is already there.\r
240                 {\r
241                     string destination = AutoNamePath;\r
242                     string[] destName = dest.Split('\\');\r
243                     string[] extension = dest.Split('.');\r
244                     string ext = extension[extension.Length - 1];\r
245 \r
246                     destName[destName.Length - 1] = destination_filename + "." + ext;\r
247 \r
248                     string fullDest = "";\r
249                     foreach (string part in destName)\r
250                     {\r
251                         if (fullDest != "")\r
252                             fullDest = fullDest + "\\" + part;\r
253                         else\r
254                             fullDest = fullDest + part;\r
255                     }\r
256                     return fullDest;\r
257                 }\r
258             }\r
259 \r
260             return AutoNamePath;\r
261         }\r
262 \r
263         /// <summary>\r
264         /// Checks for updates and returns true if an update is available.\r
265         /// </summary>\r
266         /// <param name="debug">Turns on debug mode. Don't use on program startup</param>\r
267         /// <returns>Boolean True = Update available</returns>\r
268         public Boolean updateCheck(Boolean debug)\r
269         {\r
270             try\r
271             {\r
272                 Functions.AppcastReader rssRead = new Functions.AppcastReader();\r
273                 rssRead.getInfo(); // Initializes the class.\r
274                 string build = rssRead.build();\r
275 \r
276                 int latest = int.Parse(build);\r
277                 int current = Properties.Settings.Default.hb_build;\r
278                 int skip = Properties.Settings.Default.skipversion;\r
279 \r
280                 if (latest == skip)\r
281                     return false;\r
282                 else\r
283                 {\r
284                     Boolean update = (latest > current);\r
285                     return update;\r
286                 }\r
287             }\r
288             catch (Exception exc)\r
289             {\r
290                 if (debug == true)\r
291                     MessageBox.Show("Unable to check for updates, Please try again later. \n" + exc.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
292                 return false;\r
293             }\r
294         }\r
295 \r
296         /// <summary>\r
297         /// Get's HandBrakes version data from the CLI.\r
298         /// </summary>\r
299         /// <returns>Arraylist of Version Data. 0 = hb_version 1 = hb_build</returns>\r
300         public ArrayList getCliVersionData()\r
301         {\r
302             ArrayList cliVersionData = new ArrayList();\r
303             String line;\r
304 \r
305             // 0 = SVN Build / Version\r
306             // 1 = Build Date\r
307             Process cliProcess = new Process();\r
308             ProcessStartInfo handBrakeCLI = new ProcessStartInfo("HandBrakeCLI.exe", " -u");\r
309             handBrakeCLI.UseShellExecute = false;\r
310             handBrakeCLI.RedirectStandardError = true;\r
311             handBrakeCLI.RedirectStandardOutput = true;\r
312             handBrakeCLI.CreateNoWindow = true;\r
313             cliProcess.StartInfo = handBrakeCLI;\r
314 \r
315             try\r
316             {\r
317                 cliProcess.Start();\r
318                 // Retrieve standard output and report back to parent thread until the process is complete\r
319                 TextReader stdOutput = cliProcess.StandardError;\r
320 \r
321                 while (!cliProcess.HasExited)\r
322                 {\r
323                     line = stdOutput.ReadLine();\r
324                     if (line == null) line = "";\r
325                     Match m = Regex.Match(line, @"HandBrake ([0-9\.]*)*(svn[0-9]*[M]*)* \([0-9]*\)");\r
326 \r
327                     if (m.Success != false)\r
328                     {\r
329                         string data = line.Replace("(", "").Replace(")", "").Replace("HandBrake ", "");\r
330                         string[] arr = data.Split(' ');\r
331                         cliVersionData.Add(arr[0]);\r
332                         cliVersionData.Add(arr[1]);\r
333                         return cliVersionData;\r
334                     }\r
335                 }\r
336             }\r
337             catch (Exception e)\r
338             {\r
339                 MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);\r
340             }\r
341 \r
342             cliVersionData.Add(0);\r
343             cliVersionData.Add("0");\r
344             return cliVersionData;\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 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.Count != 0)\r
363                             return true;\r
364                     }\r
365                 }\r
366                 return false;\r
367             }\r
368             catch (Exception)\r
369             {\r
370                 return false; // Keep quiet about the error.\r
371             }\r
372         }\r
373 \r
374     }\r
375 }