/* Main.cs $\r
- \r
- This file is part of the HandBrake source code.\r
- Homepage: <http://handbrake.fr>.\r
- It may be used under the terms of the GNU General Public License. */\r
-\r
-using System;\r
-using System.Windows.Forms;\r
-using System.IO;\r
-using System.Diagnostics;\r
-using System.Text.RegularExpressions;\r
-using System.Collections.Generic;\r
-using System.Xml.Serialization;\r
-using System.Threading;\r
-using Handbrake.EncodeQueue;\r
-using System.Net;\r
+ This file is part of the HandBrake source code.\r
+ Homepage: <http://handbrake.fr>.\r
+ It may be used under the terms of the GNU General Public License. */\r
\r
namespace Handbrake.Functions\r
{\r
- static class Main\r
+ using System;\r
+ using System.Collections.Generic;\r
+ using System.Diagnostics;\r
+ using System.IO;\r
+ using System.Linq;\r
+ using System.Text;\r
+ using System.Text.RegularExpressions;\r
+ using System.Windows.Forms;\r
+ using System.Xml.Serialization;\r
+\r
+ using HandBrake.Framework.Services;\r
+ using HandBrake.Framework.Services.Interfaces;\r
+ using HandBrake.ApplicationServices.Model;\r
+ using HandBrake.ApplicationServices.Parsing;\r
+ using HandBrake.ApplicationServices.Services.Interfaces;\r
+ using Model;\r
+\r
+ /// <summary>\r
+ /// Useful functions which various screens can use.\r
+ /// </summary>\r
+ public static class Main\r
{\r
- // Private Variables\r
- private static readonly XmlSerializer ser = new XmlSerializer(typeof(List<Job>));\r
+ /// <summary>\r
+ /// The Error Service\r
+ /// </summary>\r
+ private static readonly IErrorService errorService = new ErrorService();\r
+\r
+ /// <summary>\r
+ /// The XML Serializer\r
+ /// </summary>\r
+ private static readonly XmlSerializer Ser = new XmlSerializer(typeof(List<Job>));\r
\r
/// <summary>\r
/// Calculate the duration of the selected title and chapters\r
/// </summary>\r
- public static TimeSpan calculateDuration(int chapterStart, int chapterEnd, Parsing.Title selectedTitle)\r
+ /// <param name="chapterStart">\r
+ /// The chapter Start.\r
+ /// </param>\r
+ /// <param name="chapterEnd">\r
+ /// The chapter End.\r
+ /// </param>\r
+ /// <param name="selectedTitle">\r
+ /// The selected Title.\r
+ /// </param>\r
+ /// <returns>\r
+ /// The calculated duration.\r
+ /// </returns>\r
+ public static TimeSpan CalculateDuration(int chapterStart, int chapterEnd, Title selectedTitle)\r
{\r
TimeSpan duration = TimeSpan.FromSeconds(0.0);\r
- chapterStart++; chapterEnd++;\r
+ chapterStart++;\r
+ chapterEnd++;\r
if (chapterStart != 0 && chapterEnd != 0 && chapterEnd <= selectedTitle.Chapters.Count)\r
{\r
for (int i = chapterStart; i <= chapterEnd; i++)\r
}\r
\r
/// <summary>\r
- /// Select the longest title in the DVD title dropdown menu on frmMain\r
- /// </summary>\r
- public static Parsing.Title selectLongestTitle(Parsing.DVD thisDvd)\r
- {\r
- TimeSpan longestDurationFound = TimeSpan.FromSeconds(0.0);\r
- Parsing.Title returnTitle = null;\r
-\r
- foreach (Parsing.Title item in thisDvd.Titles)\r
- {\r
- if (item.Duration > longestDurationFound)\r
- {\r
- returnTitle = item;\r
- longestDurationFound = item.Duration;\r
- }\r
- }\r
- return returnTitle;\r
- }\r
-\r
- /// <summary>\r
/// Set's up the DataGridView on the Chapters tab (frmMain)\r
/// </summary>\r
- public static DataGridView chapterNaming(DataGridView dataChpt, string chapterEnd)\r
+ /// <param name="title">\r
+ /// The currently selected title object.\r
+ /// This will be used to get chapter names if they exist.\r
+ /// </param>\r
+ /// <param name="dataChpt">\r
+ /// The DataGridView Control\r
+ /// </param>\r
+ /// <param name="chapterEnd">\r
+ /// The chapter End.\r
+ /// </param>\r
+ /// <returns>\r
+ /// The chapter naming.\r
+ /// </returns>\r
+ public static DataGridView ChapterNaming(Title title, DataGridView dataChpt, string chapterEnd)\r
{\r
int i = 0, finish = 0;\r
\r
\r
while (i < finish)\r
{\r
+ string chapterName = string.Empty;\r
+ if (title != null)\r
+ {\r
+ if (title.Chapters.Count <= i && title.Chapters[i] != null)\r
+ {\r
+ chapterName = title.Chapters[i].ChapterName;\r
+ }\r
+ }\r
+\r
int n = dataChpt.Rows.Add();\r
- dataChpt.Rows[n].Cells[0].Value = (i + 1);\r
- dataChpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);\r
+ dataChpt.Rows[n].Cells[0].Value = i + 1;\r
+ dataChpt.Rows[n].Cells[1].Value = string.IsNullOrEmpty(chapterName) ? "Chapter " + (i + 1) : chapterName;\r
dataChpt.Rows[n].Cells[0].ValueType = typeof(int);\r
dataChpt.Rows[n].Cells[1].ValueType = typeof(string);\r
i++;\r
/// <summary>\r
/// Import a CSV file which contains Chapter Names\r
/// </summary>\r
- /// <param name="dataChpt"></param>\r
- /// <param name="filename"></param>\r
- /// <returns></returns>\r
- public static DataGridView importChapterNames(DataGridView dataChpt, string filename)\r
+ /// <param name="dataChpt">\r
+ /// The DataGridView Control\r
+ /// </param>\r
+ /// <param name="filename">\r
+ /// The filepath and name\r
+ /// </param>\r
+ /// <returns>A Populated DataGridView</returns>\r
+ public static DataGridView ImportChapterNames(DataGridView dataChpt, string filename)\r
{\r
IDictionary<int, string> chapterMap = new Dictionary<int, string>();\r
try\r
string csv = sr.ReadLine();\r
while (csv != null)\r
{\r
- if (csv.Trim() != "")\r
+ if (csv.Trim() != string.Empty)\r
{\r
+ csv = csv.Replace("\\,", "<!comma!>");\r
string[] contents = csv.Split(',');\r
int chapter;\r
int.TryParse(contents[0], out chapter);\r
- chapterMap.Add(chapter, contents[1]);\r
+ chapterMap.Add(chapter, contents[1].Replace("<!comma!>", ","));\r
}\r
csv = sr.ReadLine();\r
}\r
}\r
\r
/// <summary>\r
+ /// Create a CSV file with the data from the Main Window Chapters tab\r
+ /// </summary>\r
+ /// <param name="mainWindow">Main Window</param>\r
+ /// <param name="filePathName">Path to save the csv file</param>\r
+ /// <returns>True if successful </returns>\r
+ public static bool SaveChapterMarkersToCsv(frmMain mainWindow, string filePathName)\r
+ {\r
+ try\r
+ {\r
+ string csv = string.Empty;\r
+\r
+ foreach (DataGridViewRow row in mainWindow.data_chpt.Rows)\r
+ {\r
+ csv += row.Cells[0].Value.ToString();\r
+ csv += ",";\r
+ csv += row.Cells[1].Value.ToString().Replace(",", "\\,");\r
+ csv += Environment.NewLine;\r
+ }\r
+ StreamWriter file = new StreamWriter(filePathName);\r
+ file.Write(csv);\r
+ file.Close();\r
+ file.Dispose();\r
+ return true;\r
+ }\r
+ catch (Exception exc)\r
+ {\r
+ ShowExceptiowWindow("Unable to save Chapter Makrers file! \nChapter marker names will NOT be saved in your encode", exc.ToString());\r
+ return false;\r
+ }\r
+ }\r
+\r
+ /// <summary>\r
/// Function which generates the filename and path automatically based on \r
/// the Source Name, DVD title and DVD Chapters\r
/// </summary>\r
- public static string autoName(frmMain mainWindow) //ComboBox drpDvdtitle, string chapter_start, string chatper_end, string source, string dest, int format, Boolean chapters)\r
+ /// <param name="mainWindow">\r
+ /// The main Window.\r
+ /// </param>\r
+ /// <returns>\r
+ /// The Generated FileName\r
+ /// </returns>\r
+ public static string AutoName(frmMain mainWindow)\r
{\r
- string AutoNamePath = string.Empty;\r
+ string autoNamePath = string.Empty;\r
if (mainWindow.drp_dvdtitle.Text != "Automatic")\r
{\r
- // Get the Source Name \r
- string sourceName = mainWindow.SourceName;\r
+ // Get the Source Name and remove any invalid characters\r
+\r
+ string sourceName = Path.GetInvalidFileNameChars().Aggregate(Path.GetFileNameWithoutExtension(mainWindow.SourceName), (current, character) => current.Replace(character.ToString(), string.Empty));\r
+\r
+ if (Properties.Settings.Default.AutoNameRemoveUnderscore)\r
+ sourceName = sourceName.Replace("_", " ");\r
+\r
+ if (Properties.Settings.Default.AutoNameTitleCase)\r
+ sourceName = TitleCase(sourceName);\r
\r
// Get the Selected Title Number\r
string[] titlesplit = mainWindow.drp_dvdtitle.Text.Split(' ');\r
- string dvdTitle = titlesplit[0].Replace("Automatic", "");\r
+ string dvdTitle = titlesplit[0].Replace("Automatic", string.Empty);\r
\r
// Get the Chapter Start and Chapter End Numbers\r
- string chapterStart = mainWindow.drop_chapterStart.Text.Replace("Auto", "");\r
- string chapterFinish = mainWindow.drop_chapterFinish.Text.Replace("Auto", "");\r
+ string chapterStart = mainWindow.drop_chapterStart.Text.Replace("Auto", string.Empty);\r
+ string chapterFinish = mainWindow.drop_chapterFinish.Text.Replace("Auto", string.Empty);\r
string combinedChapterTag = chapterStart;\r
- if (chapterFinish != chapterStart && chapterFinish != "")\r
+ if (chapterFinish != chapterStart && chapterFinish != string.Empty)\r
combinedChapterTag = chapterStart + "-" + chapterFinish;\r
\r
// Get the destination filename.\r
string destinationFilename;\r
- if (Properties.Settings.Default.autoNameFormat != "")\r
+ if (Properties.Settings.Default.autoNameFormat != string.Empty)\r
{\r
destinationFilename = Properties.Settings.Default.autoNameFormat;\r
- destinationFilename = destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace("{chapters}", combinedChapterTag);\r
+ destinationFilename = destinationFilename.Replace("{source}", sourceName)\r
+ .Replace("{title}", dvdTitle)\r
+ .Replace("{chapters}", combinedChapterTag);\r
}\r
else\r
destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;\r
// Add the appropriate file extension\r
if (mainWindow.drop_format.SelectedIndex == 0)\r
{\r
- if (Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked || mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V())\r
- destinationFilename += ".m4v";\r
- else\r
- destinationFilename += ".mp4";\r
+ destinationFilename += Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked ||\r
+ mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V()\r
+ ? ".m4v"\r
+ : ".mp4";\r
}\r
else if (mainWindow.drop_format.SelectedIndex == 1)\r
destinationFilename += ".mkv";\r
if (!mainWindow.text_destination.Text.Contains(Path.DirectorySeparatorChar.ToString()))\r
{\r
// If there is an auto name path, use it...\r
- if (Properties.Settings.Default.autoNamePath.Trim() != "" && Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")\r
- AutoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);\r
+ if (Properties.Settings.Default.autoNamePath.Trim() == "{source_path}" && !string.IsNullOrEmpty(mainWindow.sourcePath))\r
+ {\r
+ autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.sourcePath), destinationFilename);\r
+ if (autoNamePath == mainWindow.sourcePath)\r
+ {\r
+ // Append out_ to files that already exist or is the source file\r
+ autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.sourcePath), "output_" + destinationFilename);\r
+ }\r
+ }\r
+ else if (Properties.Settings.Default.autoNamePath.Trim() != string.Empty && Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")\r
+ {\r
+ autoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);\r
+ }\r
else // ...otherwise, output to the source directory\r
- AutoNamePath = null;\r
+ autoNamePath = null;\r
}\r
else // Otherwise, use the path that is already there.\r
{\r
// Use the path and change the file extension to match the previous destination\r
- AutoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), destinationFilename);\r
+ autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), destinationFilename);\r
\r
if (Path.HasExtension(mainWindow.text_destination.Text))\r
- AutoNamePath = Path.ChangeExtension(AutoNamePath, Path.GetExtension(mainWindow.text_destination.Text));\r
+ autoNamePath = Path.ChangeExtension(autoNamePath,\r
+ Path.GetExtension(mainWindow.text_destination.Text));\r
}\r
}\r
\r
- return AutoNamePath;\r
+ return autoNamePath;\r
}\r
\r
/// <summary>\r
/// Get's HandBrakes version data from the CLI.\r
/// </summary>\r
- /// <returns>Arraylist of Version Data. 0 = hb_version 1 = hb_build</returns>\r
- public static void setCliVersionData()\r
+ public static void SetCliVersionData()\r
{\r
- String line;\r
+ string line;\r
\r
// 0 = SVN Build / Version\r
// 1 = Build Date\r
-\r
DateTime lastModified = File.GetLastWriteTime("HandBrakeCLI.exe");\r
\r
-\r
- if (Properties.Settings.Default.cliLastModified == lastModified && Properties.Settings.Default.hb_build != 0)\r
+ if (Properties.Settings.Default.hb_build != 0 && Properties.Settings.Default.cliLastModified == lastModified)\r
+ {\r
return;\r
+ }\r
\r
Properties.Settings.Default.cliLastModified = lastModified;\r
- \r
+\r
Process cliProcess = new Process();\r
- ProcessStartInfo handBrakeCLI = new ProcessStartInfo("HandBrakeCLI.exe", " -u")\r
+ ProcessStartInfo handBrakeCli = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")\r
{\r
UseShellExecute = false,\r
RedirectStandardError = true,\r
RedirectStandardOutput = true,\r
CreateNoWindow = true\r
};\r
- cliProcess.StartInfo = handBrakeCLI;\r
+ cliProcess.StartInfo = handBrakeCli;\r
\r
try\r
{\r
cliProcess.Start();\r
+\r
// Retrieve standard output and report back to parent thread until the process is complete\r
TextReader stdOutput = cliProcess.StandardError;\r
\r
while (!cliProcess.HasExited)\r
{\r
- line = stdOutput.ReadLine() ?? "";\r
- Match m = Regex.Match(line, @"HandBrake ([0-9.]*)(svn[0-9M]*) \([0-9]*\)");\r
+ line = stdOutput.ReadLine() ?? string.Empty;\r
+ Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \(([0-9]*)\)");\r
Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");\r
\r
if (m.Success)\r
{\r
- string data = line.Replace("(", "").Replace(")", "").Replace("HandBrake ", "");\r
- string[] arr = data.Split(' ');\r
+ string version = m.Groups[1].Success ? m.Groups[1].Value : string.Empty;\r
+ string build = m.Groups[2].Success ? m.Groups[2].Value : string.Empty;\r
\r
- Properties.Settings.Default.hb_build = int.Parse(arr[1]);\r
- Properties.Settings.Default.hb_version = arr[0];\r
+ int buildValue;\r
+ int.TryParse(build, out buildValue);\r
+\r
+ Properties.Settings.Default.hb_build = buildValue;\r
+ Properties.Settings.Default.hb_version = version;\r
}\r
+\r
if (platform.Success)\r
- Properties.Settings.Default.hb_platform = platform.Value.Replace("-", "").Trim();\r
+ {\r
+ Properties.Settings.Default.hb_platform = platform.Value.Replace("-", string.Empty).Trim();\r
+ }\r
\r
if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.\r
{\r
Process cli = Process.GetProcessById(cliProcess.Id);\r
if (!cli.HasExited)\r
+ {\r
cli.Kill();\r
+ }\r
}\r
}\r
+\r
Properties.Settings.Default.Save();\r
}\r
catch (Exception e)\r
{\r
- MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);\r
+ Properties.Settings.Default.hb_build = 0;\r
+ Properties.Settings.Default.Save();\r
+\r
+ ShowExceptiowWindow("Unable to retrieve version information from the CLI.", e.ToString());\r
}\r
}\r
\r
/// If it does, it means the last queue did not complete before HandBrake closed.\r
/// So, return a boolean if true. \r
/// </summary>\r
- public static Boolean checkQueueRecovery()\r
+ /// <returns>\r
+ /// True if there is a queue to recover.\r
+ /// </returns>\r
+ public static List<string> CheckQueueRecovery()\r
{\r
try\r
{\r
- string tempPath = Path.Combine(Path.GetTempPath(), "hb_queue_recovery.xml");\r
- if (File.Exists(tempPath))\r
+ string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\");\r
+ List<string> queueFiles = new List<string>();\r
+\r
+ DirectoryInfo info = new DirectoryInfo(tempPath);\r
+ FileInfo[] logFiles = info.GetFiles("*.xml");\r
+ foreach (FileInfo file in logFiles)\r
{\r
- using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))\r
+ if (!file.Name.Contains("hb_queue_recovery"))\r
+ continue;\r
+\r
+ using (FileStream strm = new FileStream(Path.Combine(file.DirectoryName, file.Name), FileMode.Open, FileAccess.Read))\r
{\r
- List<Job> list = ser.Deserialize(strm) as List<Job>;\r
+ List<Job> list = Ser.Deserialize(strm) as List<Job>;\r
if (list != null)\r
+ {\r
if (list.Count != 0)\r
- return true;\r
+ {\r
+ queueFiles.Add(file.Name);\r
+ }\r
+ }\r
}\r
}\r
- return false;\r
+\r
+ return queueFiles;\r
}\r
catch (Exception)\r
{\r
- return false; // Keep quiet about the error.\r
+ return new List<string>(); // Keep quiet about the error.\r
}\r
}\r
\r
/// <summary>\r
- /// Get the Process ID of HandBrakeCLI for the current instance.\r
+ /// Recover a queue from file.\r
/// </summary>\r
- /// <param name="before">List of processes before the new process was started</param>\r
- /// <returns>Int - Process ID</returns>\r
- public static int getCliProcess(Process[] before)\r
+ /// <param name="encodeQueue">\r
+ /// The encode Queue.\r
+ /// </param>\r
+ public static void RecoverQueue(IQueue encodeQueue)\r
{\r
- // This is a bit of a cludge. Maybe someone has a better idea on how to impliment this.\r
- // Since we used CMD to start HandBrakeCLI, we don't get the process ID from hbProc.\r
- // Instead we take the processes before and after, and get the ID of HandBrakeCLI.exe\r
- // avoiding any previous instances of HandBrakeCLI.exe in before.\r
- // Kill the current process.\r
-\r
- DateTime startTime = DateTime.Now;\r
- TimeSpan duration;\r
-\r
- Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");\r
- while (hbProcesses.Length == 0)\r
+ DialogResult result = DialogResult.None;\r
+ List<string> queueFiles = CheckQueueRecovery();\r
+ if (queueFiles.Count == 1)\r
{\r
- hbProcesses = Process.GetProcessesByName("HandBrakeCLI");\r
- duration = DateTime.Now - startTime;\r
- if (duration.Seconds > 5 && hbProcesses.Length == 0) // Make sure we don't wait forever if the process doesn't start\r
- return -1;\r
+ result = MessageBox.Show(\r
+ "HandBrake has detected unfinished items on the queue from the last time the application was launched. Would you like to recover these?",\r
+ "Queue Recovery Possible", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
+ }\r
+ else if (queueFiles.Count > 1)\r
+ {\r
+ result = MessageBox.Show(\r
+ "HandBrake has detected multiple unfinished queue files. These will be from multiple instances of HandBrake running. Would you like to recover all unfinished jobs?",\r
+ "Queue Recovery Possible", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
}\r
\r
- Process hbProcess = null;\r
- foreach (Process process in hbProcesses)\r
+ if (result == DialogResult.Yes)\r
{\r
- Boolean found = false;\r
- // Check if the current CLI instance was running before we started the current one\r
- foreach (Process bprocess in before)\r
+ foreach (string file in queueFiles)\r
{\r
- if (process.Id == bprocess.Id)\r
- found = true;\r
+ encodeQueue.LoadQueueFromFile(file); // Start Recovery\r
}\r
+ }\r
+ else\r
+ {\r
+ if (IsMultiInstance) return; // Don't tamper with the files if we are multi instance\r
\r
- // If it wasn't running before, we found the process we want.\r
- if (!found)\r
+ string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\");\r
+ foreach (string file in queueFiles)\r
{\r
- hbProcess = process;\r
- break;\r
+ if (File.Exists(Path.Combine(tempPath, file)))\r
+ File.Delete(Path.Combine(tempPath, file));\r
}\r
}\r
- if (hbProcess != null)\r
- return hbProcess.Id;\r
+ }\r
\r
- return -1;\r
+ /// <summary>\r
+ /// Gets a value indicating whether HandBrake is running in multi instance mode\r
+ /// </summary>\r
+ /// <returns>True if the UI has another instance running</returns>\r
+ public static bool IsMultiInstance\r
+ {\r
+ get\r
+ {\r
+ return Process.GetProcessesByName("HandBrake").Length > 0 ? true : false;\r
+ }\r
}\r
\r
/// <summary>\r
/// Clear all the encode log files.\r
/// </summary>\r
- public static void clearLogs()\r
+ public static void ClearLogs()\r
{\r
string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
if (Directory.Exists(logDir))\r
FileInfo[] logFiles = info.GetFiles("*.txt");\r
foreach (FileInfo file in logFiles)\r
{\r
- if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt"))\r
+ if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log"))\r
File.Delete(file.FullName);\r
}\r
}\r
}\r
\r
/// <summary>\r
- /// Begins checking for an update to HandBrake.\r
+ /// Clear old log files x days in the past\r
/// </summary>\r
- /// <param name="callback">The method that will be called when the check is finished.</param>\r
- /// <param name="debug">Whether or not to execute this in debug mode.</param>\r
- public static void BeginCheckForUpdates(AsyncCallback callback, bool debug)\r
+ public static void ClearOldLogs()\r
{\r
- ThreadPool.QueueUserWorkItem(new WaitCallback(delegate\r
+ string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
+ if (Directory.Exists(logDir))\r
{\r
- try\r
- {\r
- // Is this a stable or unstable build?\r
- string url = Properties.Settings.Default.hb_build.ToString().EndsWith("1") ? Properties.Settings.Default.appcast_unstable : Properties.Settings.Default.appcast;\r
-\r
- // Initialize variables\r
- WebRequest request = WebRequest.Create(url);\r
- WebResponse response = request.GetResponse();\r
- AppcastReader reader = new AppcastReader();\r
-\r
- // Get the data, convert it to a string, and parse it into the AppcastReader\r
- reader.getInfo(new StreamReader(response.GetResponseStream()).ReadToEnd());\r
-\r
- // Further parse the information\r
- string build = reader.build;\r
-\r
- int latest = int.Parse(build);\r
- int current = Properties.Settings.Default.hb_build;\r
- int skip = Properties.Settings.Default.skipversion;\r
+ DirectoryInfo info = new DirectoryInfo(logDir);\r
+ FileInfo[] logFiles = info.GetFiles("*.txt");\r
\r
- // If the user wanted to skip this version, don't report the update\r
- if (latest == skip)\r
+ foreach (FileInfo file in logFiles)\r
+ {\r
+ if (file.LastWriteTime < DateTime.Now.AddDays(-30))\r
{\r
- UpdateCheckInformation info = new UpdateCheckInformation() { NewVersionAvailable = false, BuildInformation = null };\r
- callback(new UpdateCheckResult(debug, info));\r
- return;\r
+ if (!file.Name.Contains("last_scan_log.txt") && !file.Name.Contains("last_encode_log.txt"))\r
+ File.Delete(file.FullName);\r
}\r
+ }\r
+ }\r
+ }\r
\r
- // Set when the last update was\r
- Properties.Settings.Default.lastUpdateCheckDate = DateTime.Now;\r
- Properties.Settings.Default.Save();\r
+ /// <summary>\r
+ /// Map languages and their iso639_2 value into a IDictionary\r
+ /// </summary>\r
+ /// <returns>A Dictionary containing the language and iso code</returns>\r
+ public static IDictionary<string, string> MapLanguages()\r
+ {\r
+ IDictionary<string, string> languageMap = new Dictionary<string, string>\r
+ {\r
+ {"Any", "und"}, \r
+ {"Afar", "aar"}, \r
+ {"Abkhazian", "abk"}, \r
+ {"Afrikaans", "afr"}, \r
+ {"Akan", "aka"}, \r
+ {"Albanian", "sqi"}, \r
+ {"Amharic", "amh"}, \r
+ {"Arabic", "ara"}, \r
+ {"Aragonese", "arg"}, \r
+ {"Armenian", "hye"}, \r
+ {"Assamese", "asm"}, \r
+ {"Avaric", "ava"}, \r
+ {"Avestan", "ave"}, \r
+ {"Aymara", "aym"}, \r
+ {"Azerbaijani", "aze"}, \r
+ {"Bashkir", "bak"}, \r
+ {"Bambara", "bam"}, \r
+ {"Basque", "eus"}, \r
+ {"Belarusian", "bel"}, \r
+ {"Bengali", "ben"}, \r
+ {"Bihari", "bih"}, \r
+ {"Bislama", "bis"}, \r
+ {"Bosnian", "bos"}, \r
+ {"Breton", "bre"}, \r
+ {"Bulgarian", "bul"}, \r
+ {"Burmese", "mya"}, \r
+ {"Catalan", "cat"}, \r
+ {"Chamorro", "cha"}, \r
+ {"Chechen", "che"}, \r
+ {"Chinese", "zho"}, \r
+ {"Church Slavic", "chu"}, \r
+ {"Chuvash", "chv"}, \r
+ {"Cornish", "cor"}, \r
+ {"Corsican", "cos"}, \r
+ {"Cree", "cre"}, \r
+ {"Czech", "ces"}, \r
+ {"Dansk", "dan"}, \r
+ {"Divehi", "div"}, \r
+ {"Nederlands", "nld"}, \r
+ {"Dzongkha", "dzo"}, \r
+ {"English", "eng"}, \r
+ {"Esperanto", "epo"}, \r
+ {"Estonian", "est"}, \r
+ {"Ewe", "ewe"}, \r
+ {"Faroese", "fao"}, \r
+ {"Fijian", "fij"}, \r
+ {"Suomi", "fin"}, \r
+ {"Francais", "fra"}, \r
+ {"Western Frisian", "fry"}, \r
+ {"Fulah", "ful"}, \r
+ {"Georgian", "kat"}, \r
+ {"Deutsch", "deu"}, \r
+ {"Gaelic (Scots)", "gla"}, \r
+ {"Irish", "gle"}, \r
+ {"Galician", "glg"}, \r
+ {"Manx", "glv"}, \r
+ {"Greek Modern", "ell"}, \r
+ {"Guarani", "grn"}, \r
+ {"Gujarati", "guj"}, \r
+ {"Haitian", "hat"}, \r
+ {"Hausa", "hau"}, \r
+ {"Hebrew", "heb"}, \r
+ {"Herero", "her"}, \r
+ {"Hindi", "hin"}, \r
+ {"Hiri Motu", "hmo"}, \r
+ {"Magyar", "hun"}, \r
+ {"Igbo", "ibo"}, \r
+ {"Islenska", "isl"}, \r
+ {"Ido", "ido"}, \r
+ {"Sichuan Yi", "iii"}, \r
+ {"Inuktitut", "iku"}, \r
+ {"Interlingue", "ile"}, \r
+ {"Interlingua", "ina"}, \r
+ {"Indonesian", "ind"}, \r
+ {"Inupiaq", "ipk"}, \r
+ {"Italiano", "ita"}, \r
+ {"Javanese", "jav"}, \r
+ {"Japanese", "jpn"}, \r
+ {"Kalaallisut", "kal"}, \r
+ {"Kannada", "kan"}, \r
+ {"Kashmiri", "kas"}, \r
+ {"Kanuri", "kau"}, \r
+ {"Kazakh", "kaz"}, \r
+ {"Central Khmer", "khm"}, \r
+ {"Kikuyu", "kik"}, \r
+ {"Kinyarwanda", "kin"}, \r
+ {"Kirghiz", "kir"}, \r
+ {"Komi", "kom"}, \r
+ {"Kongo", "kon"}, \r
+ {"Korean", "kor"}, \r
+ {"Kuanyama", "kua"}, \r
+ {"Kurdish", "kur"}, \r
+ {"Lao", "lao"}, \r
+ {"Latin", "lat"}, \r
+ {"Latvian", "lav"}, \r
+ {"Limburgan", "lim"}, \r
+ {"Lingala", "lin"}, \r
+ {"Lithuanian", "lit"}, \r
+ {"Luxembourgish", "ltz"}, \r
+ {"Luba-Katanga", "lub"}, \r
+ {"Ganda", "lug"}, \r
+ {"Macedonian", "mkd"}, \r
+ {"Marshallese", "mah"}, \r
+ {"Malayalam", "mal"}, \r
+ {"Maori", "mri"}, \r
+ {"Marathi", "mar"}, \r
+ {"Malay", "msa"}, \r
+ {"Malagasy", "mlg"}, \r
+ {"Maltese", "mlt"}, \r
+ {"Moldavian", "mol"}, \r
+ {"Mongolian", "mon"}, \r
+ {"Nauru", "nau"}, \r
+ {"Navajo", "nav"}, \r
+ {"Ndebele, South", "nbl"}, \r
+ {"Ndebele, North", "nde"}, \r
+ {"Ndonga", "ndo"}, \r
+ {"Nepali", "nep"}, \r
+ {"Norwegian Nynorsk", "nno"}, \r
+ {"Norwegian Bokmål", "nob"}, \r
+ {"Norsk", "nor"}, \r
+ {"Chichewa; Nyanja", "nya"}, \r
+ {"Occitan", "oci"}, \r
+ {"Ojibwa", "oji"}, \r
+ {"Oriya", "ori"}, \r
+ {"Oromo", "orm"}, \r
+ {"Ossetian", "oss"}, \r
+ {"Panjabi", "pan"}, \r
+ {"Persian", "fas"}, \r
+ {"Pali", "pli"}, \r
+ {"Polish", "pol"}, \r
+ {"Portugues", "por"}, \r
+ {"Pushto", "pus"}, \r
+ {"Quechua", "que"}, \r
+ {"Romansh", "roh"}, \r
+ {"Romanian", "ron"}, \r
+ {"Rundi", "run"}, \r
+ {"Russian", "rus"}, \r
+ {"Sango", "sag"}, \r
+ {"Sanskrit", "san"}, \r
+ {"Serbian", "srp"}, \r
+ {"Hrvatski", "hrv"}, \r
+ {"Sinhala", "sin"}, \r
+ {"Slovak", "slk"}, \r
+ {"Slovenian", "slv"}, \r
+ {"Northern Sami", "sme"}, \r
+ {"Samoan", "smo"}, \r
+ {"Shona", "sna"}, \r
+ {"Sindhi", "snd"}, \r
+ {"Somali", "som"}, \r
+ {"Sotho Southern", "sot"}, \r
+ {"Espanol", "spa"}, \r
+ {"Sardinian", "srd"}, \r
+ {"Swati", "ssw"}, \r
+ {"Sundanese", "sun"}, \r
+ {"Swahili", "swa"}, \r
+ {"Svenska", "swe"}, \r
+ {"Tahitian", "tah"}, \r
+ {"Tamil", "tam"}, \r
+ {"Tatar", "tat"}, \r
+ {"Telugu", "tel"}, \r
+ {"Tajik", "tgk"}, \r
+ {"Tagalog", "tgl"}, \r
+ {"Thai", "tha"}, \r
+ {"Tibetan", "bod"}, \r
+ {"Tigrinya", "tir"}, \r
+ {"Tonga", "ton"}, \r
+ {"Tswana", "tsn"}, \r
+ {"Tsonga", "tso"}, \r
+ {"Turkmen", "tuk"}, \r
+ {"Turkish", "tur"}, \r
+ {"Twi", "twi"}, \r
+ {"Uighur", "uig"}, \r
+ {"Ukrainian", "ukr"}, \r
+ {"Urdu", "urd"}, \r
+ {"Uzbek", "uzb"}, \r
+ {"Venda", "ven"}, \r
+ {"Vietnamese", "vie"}, \r
+ {"Volapük", "vol"}, \r
+ {"Welsh", "cym"}, \r
+ {"Walloon", "wln"}, \r
+ {"Wolof", "wol"}, \r
+ {"Xhosa", "xho"}, \r
+ {"Yiddish", "yid"}, \r
+ {"Yoruba", "yor"}, \r
+ {"Zhuang", "zha"}, \r
+ {"Zulu", "zul"}\r
+ };\r
+ return languageMap;\r
+ }\r
\r
- UpdateCheckInformation info2 = new UpdateCheckInformation() { NewVersionAvailable = latest > current, BuildInformation = reader };\r
- callback(new UpdateCheckResult(debug, info2));\r
+ /// <summary>\r
+ /// Get a list of available DVD drives which are ready and contain DVD content.\r
+ /// </summary>\r
+ /// <returns>A List of Drives with their details</returns>\r
+ public static List<DriveInformation> GetDrives()\r
+ {\r
+ List<DriveInformation> drives = new List<DriveInformation>();\r
+ DriveInfo[] theCollectionOfDrives = DriveInfo.GetDrives();\r
+ int id = 0;\r
+ foreach (DriveInfo curDrive in theCollectionOfDrives)\r
+ {\r
+ if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady &&\r
+ File.Exists(curDrive.RootDirectory + "VIDEO_TS\\VIDEO_TS.IFO"))\r
+ {\r
+ drives.Add(new DriveInformation\r
+ {\r
+ Id = id,\r
+ VolumeLabel = curDrive.VolumeLabel,\r
+ RootDirectory = curDrive.RootDirectory + "VIDEO_TS"\r
+ });\r
+ id++;\r
}\r
- catch (Exception exc)\r
+ }\r
+ return drives;\r
+ }\r
+\r
+ /// <summary>\r
+ /// Change a string to Title Case/\r
+ /// </summary>\r
+ /// <param name="input">\r
+ /// The input.\r
+ /// </param>\r
+ /// <returns>\r
+ /// A string in title case.\r
+ /// </returns>\r
+ public static string TitleCase(string input)\r
+ {\r
+ string[] tokens = input.Split(' ');\r
+ StringBuilder sb = new StringBuilder(input.Length);\r
+ foreach (string s in tokens)\r
+ {\r
+ if (!string.IsNullOrEmpty(s))\r
{\r
- callback(new UpdateCheckResult(debug, new UpdateCheckInformation() { Error = exc }));\r
+ sb.Append(s[0].ToString().ToUpper());\r
+ sb.Append(s.Substring(1).ToLower());\r
+ sb.Append(" ");\r
}\r
- }));\r
+ }\r
+\r
+ return sb.ToString().Trim();\r
}\r
\r
/// <summary>\r
- /// \r
+ /// Show the Exception Window\r
/// </summary>\r
- /// <param name="result"></param>\r
- /// <returns></returns>\r
- public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)\r
+ /// <param name="shortError">\r
+ /// The short error.\r
+ /// </param>\r
+ /// <param name="longError">\r
+ /// The long error.\r
+ /// </param>\r
+ public static void ShowExceptiowWindow(string shortError, string longError)\r
{\r
- UpdateCheckResult checkResult = (UpdateCheckResult)result;\r
- return checkResult.Result;\r
+ errorService.ShowError(shortError, longError);\r
}\r
\r
/// <summary>\r
- /// Used in EndUpdateCheck() for update checking and the IAsyncResult design pattern.\r
+ /// Get The Source from the CLI Query\r
/// </summary>\r
- private class UpdateCheckResult : IAsyncResult\r
+ /// <param name="query">Full CLI Query</param>\r
+ /// <returns>The Source Path</returns>\r
+ public static string GetSourceFromQuery(string query)\r
{\r
- public UpdateCheckResult(object asyncState, UpdateCheckInformation info)\r
+ int startIndex = query.IndexOf("-i \"");\r
+ if (startIndex != -1)\r
{\r
- AsyncState = asyncState;\r
- Result = info;\r
- }\r
+ string input = query.Substring(startIndex).Replace("-i \"", string.Empty).Trim();\r
\r
- /// <summary>\r
- /// Gets whether the check was executed in debug mode.\r
- /// </summary>\r
- public object AsyncState { get; private set; }\r
+ int closeIndex = input.IndexOf('"');\r
\r
- /// <summary>\r
- /// Gets the result of the update check.\r
- /// </summary>\r
- public UpdateCheckInformation Result { get; private set; }\r
+ return closeIndex == -1 ? "Unknown" : input.Substring(0, closeIndex);\r
+ }\r
\r
- public WaitHandle AsyncWaitHandle { get { throw new NotImplementedException(); } }\r
- public bool CompletedSynchronously { get { throw new NotImplementedException(); } }\r
- public bool IsCompleted { get { throw new NotImplementedException(); } }\r
+ return "Unknown";\r
}\r
\r
/// <summary>\r
- /// Map languages and their iso639_2 value into a IDictionary\r
+ /// Get the Destination from the CLI Query\r
/// </summary>\r
- /// <returns></returns>\r
- public static IDictionary<string, string> mapLanguages()\r
+ /// <param name="query">Full CLI Query</param>\r
+ /// <returns>The Destination path</returns>\r
+ public static string GetDestinationFromQuery(string query)\r
{\r
- IDictionary<string, string> languageMap = new Dictionary<string, string>\r
- {\r
- {"Any", "und"},\r
- {"Afar", "aar"},\r
- {"Abkhazian", "abk"},\r
- {"Afrikaans", "afr"},\r
- {"Akan", "aka"},\r
- {"Albanian", "sqi"},\r
- {"Amharic", "amh"},\r
- {"Arabic", "ara"},\r
- {"Aragonese", "arg"},\r
- {"Armenian", "hye"},\r
- {"Assamese", "asm"},\r
- {"Avaric", "ava"},\r
- {"Avestan", "ave"},\r
- {"Aymara", "aym"},\r
- {"Azerbaijani", "aze"},\r
- {"Bashkir", "bak"},\r
- {"Bambara", "bam"},\r
- {"Basque", "eus"},\r
- {"Belarusian", "bel"},\r
- {"Bengali", "ben"},\r
- {"Bihari", "bih"},\r
- {"Bislama", "bis"},\r
- {"Bosnian", "bos"},\r
- {"Breton", "bre"},\r
- {"Bulgarian", "bul"},\r
- {"Burmese", "mya"},\r
- {"Catalan", "cat"},\r
- {"Chamorro", "cha"},\r
- {"Chechen", "che"},\r
- {"Chinese", "zho"},\r
- {"Church Slavic", "chu"},\r
- {"Chuvash", "chv"},\r
- {"Cornish", "cor"},\r
- {"Corsican", "cos"},\r
- {"Cree", "cre"},\r
- {"Czech", "ces"},\r
- {"Dansk", "dan"},\r
- {"Divehi", "div"},\r
- {"Nederlands", "nld"},\r
- {"Dzongkha", "dzo"},\r
- {"English", "eng"},\r
- {"Esperanto", "epo"},\r
- {"Estonian", "est"},\r
- {"Ewe", "ewe"},\r
- {"Faroese", "fao"},\r
- {"Fijian", "fij"},\r
- {"Suomi", "fin"},\r
- {"Francais", "fra"},\r
- {"Western Frisian", "fry"},\r
- {"Fulah", "ful"},\r
- {"Georgian", "kat"},\r
- {"Deutsch", "deu"},\r
- {"Gaelic (Scots)", "gla"},\r
- {"Irish", "gle"},\r
- {"Galician", "glg"},\r
- {"Manx", "glv"},\r
- {"Greek Modern", "ell"},\r
- {"Guarani", "grn"},\r
- {"Gujarati", "guj"},\r
- {"Haitian", "hat"},\r
- {"Hausa", "hau"},\r
- {"Hebrew", "heb"},\r
- {"Herero", "her"},\r
- {"Hindi", "hin"},\r
- {"Hiri Motu", "hmo"},\r
- {"Magyar", "hun"},\r
- {"Igbo", "ibo"},\r
- {"Islenska", "isl"},\r
- {"Ido", "ido"},\r
- {"Sichuan Yi", "iii"},\r
- {"Inuktitut", "iku"},\r
- {"Interlingue", "ile"},\r
- {"Interlingua", "ina"},\r
- {"Indonesian", "ind"},\r
- {"Inupiaq", "ipk"},\r
- {"Italiano", "ita"},\r
- {"Javanese", "jav"},\r
- {"Japanese", "jpn"},\r
- {"Kalaallisut", "kal"},\r
- {"Kannada", "kan"},\r
- {"Kashmiri", "kas"},\r
- {"Kanuri", "kau"},\r
- {"Kazakh", "kaz"},\r
- {"Central Khmer", "khm"},\r
- {"Kikuyu", "kik"},\r
- {"Kinyarwanda", "kin"},\r
- {"Kirghiz", "kir"},\r
- {"Komi", "kom"},\r
- {"Kongo", "kon"},\r
- {"Korean", "kor"},\r
- {"Kuanyama", "kua"},\r
- {"Kurdish", "kur"},\r
- {"Lao", "lao"},\r
- {"Latin", "lat"},\r
- {"Latvian", "lav"},\r
- {"Limburgan", "lim"},\r
- {"Lingala", "lin"},\r
- {"Lithuanian", "lit"},\r
- {"Luxembourgish", "ltz"},\r
- {"Luba-Katanga", "lub"},\r
- {"Ganda", "lug"},\r
- {"Macedonian", "mkd"},\r
- {"Marshallese", "mah"},\r
- {"Malayalam", "mal"},\r
- {"Maori", "mri"},\r
- {"Marathi", "mar"},\r
- {"Malay", "msa"},\r
- {"Malagasy", "mlg"},\r
- {"Maltese", "mlt"},\r
- {"Moldavian", "mol"},\r
- {"Mongolian", "mon"},\r
- {"Nauru", "nau"},\r
- {"Navajo", "nav"},\r
- {"Ndebele, South", "nbl"},\r
- {"Ndebele, North", "nde"},\r
- {"Ndonga", "ndo"},\r
- {"Nepali", "nep"},\r
- {"Norwegian Nynorsk", "nno"},\r
- {"Norwegian Bokmål", "nob"},\r
- {"Norsk", "nor"},\r
- {"Chichewa; Nyanja", "nya"},\r
- {"Occitan", "oci"},\r
- {"Ojibwa", "oji"},\r
- {"Oriya", "ori"},\r
- {"Oromo", "orm"},\r
- {"Ossetian", "oss"},\r
- {"Panjabi", "pan"},\r
- {"Persian", "fas"},\r
- {"Pali", "pli"},\r
- {"Polish", "pol"},\r
- {"Portugues", "por"},\r
- {"Pushto", "pus"},\r
- {"Quechua", "que"},\r
- {"Romansh", "roh"},\r
- {"Romanian", "ron"},\r
- {"Rundi", "run"},\r
- {"Russian", "rus"},\r
- {"Sango", "sag"},\r
- {"Sanskrit", "san"},\r
- {"Serbian", "srp"},\r
- {"Hrvatski", "hrv"},\r
- {"Sinhala", "sin"},\r
- {"Slovak", "slk"},\r
- {"Slovenian", "slv"},\r
- {"Northern Sami", "sme"},\r
- {"Samoan", "smo"},\r
- {"Shona", "sna"},\r
- {"Sindhi", "snd"},\r
- {"Somali", "som"},\r
- {"Sotho Southern", "sot"},\r
- {"Espanol", "spa"},\r
- {"Sardinian", "srd"},\r
- {"Swati", "ssw"},\r
- {"Sundanese", "sun"},\r
- {"Swahili", "swa"},\r
- {"Svenska", "swe"},\r
- {"Tahitian", "tah"},\r
- {"Tamil", "tam"},\r
- {"Tatar", "tat"},\r
- {"Telugu", "tel"},\r
- {"Tajik", "tgk"},\r
- {"Tagalog", "tgl"},\r
- {"Thai", "tha"},\r
- {"Tibetan", "bod"},\r
- {"Tigrinya", "tir"},\r
- {"Tonga", "ton"},\r
- {"Tswana", "tsn"},\r
- {"Tsonga", "tso"},\r
- {"Turkmen", "tuk"},\r
- {"Turkish", "tur"},\r
- {"Twi", "twi"},\r
- {"Uighur", "uig"},\r
- {"Ukrainian", "ukr"},\r
- {"Urdu", "urd"},\r
- {"Uzbek", "uzb"},\r
- {"Venda", "ven"},\r
- {"Vietnamese", "vie"},\r
- {"Volapük", "vol"},\r
- {"Welsh", "cym"},\r
- {"Walloon", "wln"},\r
- {"Wolof", "wol"},\r
- {"Xhosa", "xho"},\r
- {"Yiddish", "yid"},\r
- {"Yoruba", "yor"},\r
- {"Zhuang", "zha"},\r
- {"Zulu", "zul"}\r
- };\r
- return languageMap;\r
- }\r
+ int startIndex = query.IndexOf("-o \"");\r
+ if (startIndex != -1)\r
+ {\r
+ string output = query.Substring(startIndex).Replace("-o \"", string.Empty).Trim();\r
+\r
+ int closeIndex = output.IndexOf('"');\r
\r
+ return closeIndex == -1 ? "Unknown" : output.Substring(0, closeIndex);\r
+ }\r
+\r
+ return "Unknown";\r
+ }\r
}\r
-}\r
+}
\ No newline at end of file