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