using System.Collections.Generic;\r
using System.Diagnostics;\r
using System.IO;\r
- using System.Net;\r
+ using System.Linq;\r
+ using System.Security.Cryptography;\r
using System.Text;\r
using System.Text.RegularExpressions;\r
- using System.Threading;\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
-\r
using Model;\r
\r
/// <summary>\r
public static class Main\r
{\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
+ private static readonly XmlSerializer Ser = new XmlSerializer(typeof(List<QueueTask>));\r
\r
/// <summary>\r
/// Calculate the duration of the selected title and chapters\r
/// <summary>\r
/// Set's up the DataGridView on the Chapters tab (frmMain)\r
/// </summary>\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
/// <returns>\r
/// The chapter naming.\r
/// </returns>\r
- public static DataGridView ChapterNaming(DataGridView dataChpt, string chapterEnd)\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[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
}\r
catch (Exception exc)\r
{\r
- frmExceptionWindow exceptionWindow = new frmExceptionWindow();\r
- exceptionWindow.Setup("Unable to save Chapter Makrers file! \nChapter marker names will NOT be saved in your encode", exc.ToString());\r
- exceptionWindow.ShowDialog();\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
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
- // Remove any illeagal characters from the source name\r
- foreach (char character in Path.GetInvalidFileNameChars())\r
- {\r
- if (autoNamePath != null)\r
- {\r
- sourceName = sourceName.Replace(character.ToString(), string.Empty);\r
- }\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
if (Properties.Settings.Default.autoNameFormat != string.Empty)\r
{\r
destinationFilename = Properties.Settings.Default.autoNameFormat;\r
- destinationFilename =\r
- destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace(\r
- "{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 ||\r
- mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V())\r
- destinationFilename += ".m4v";\r
- else\r
- destinationFilename += ".mp4";\r
+ destinationFilename += Properties.Settings.Default.useM4v == 0 || Properties.Settings.Default.useM4v == 2 || 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() != string.Empty &&\r
- Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")\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
}\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),\r
- 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,\r
\r
// 0 = SVN Build / Version\r
// 1 = Build Date\r
- DateTime lastModified = File.GetLastWriteTime("HandBrakeCLI.exe");\r
\r
- if (Properties.Settings.Default.cliLastModified == lastModified && Properties.Settings.Default.hb_build != 0)\r
+ // Get the SHA1 Hash of HandBrakeCLI\r
+ byte[] hash;\r
+ using (Stream stream = File.OpenRead(Path.Combine(Application.StartupPath, "HandBrakeCLI.exe")))\r
+ {\r
+ hash = SHA1.Create().ComputeHash(stream);\r
+ }\r
+ string base64Hash = Convert.ToBase64String(hash);\r
+ \r
+ // Compare the hash with the last known hash. If it's the same, return.\r
+ if (Properties.Settings.Default.CliExeHash == base64Hash)\r
+ {\r
return;\r
+ }\r
\r
- Properties.Settings.Default.cliLastModified = lastModified;\r
-\r
+ // It's not the same, so start the CLI to get it's version data.\r
Process cliProcess = new Process();\r
ProcessStartInfo handBrakeCli = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")\r
{\r
while (!cliProcess.HasExited)\r
{\r
line = stdOutput.ReadLine() ?? string.Empty;\r
- Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \([0-9]*\)");\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("(", string.Empty).Replace(")", string.Empty).Replace("HandBrake ", string.Empty);\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
}\r
}\r
\r
+ Properties.Settings.Default.CliExeHash = base64Hash;\r
+\r
Properties.Settings.Default.Save();\r
}\r
catch (Exception e)\r
{\r
- frmExceptionWindow exceptionWindow = new frmExceptionWindow();\r
- exceptionWindow.Setup("Unable to retrieve version information from the CLI.", e.ToString());\r
- exceptionWindow.ShowDialog();\r
- }\r
- }\r
+ Properties.Settings.Default.hb_build = 0;\r
+ Properties.Settings.Default.CliExeHash = null;\r
+ Properties.Settings.Default.Save();\r
\r
- /// <summary>\r
- /// Check to make sure that the user has an up to date version of the CLI installed.\r
- /// </summary>\r
- public static void CheckForValidCliVersion()\r
- {\r
- // Make sure we have a recent version for svn builds\r
- string version = Properties.Settings.Default.hb_version;\r
- if (version.Contains("svn"))\r
- {\r
- version = version.Replace("svn", string.Empty).Trim();\r
- int build;\r
- int.TryParse(version, out build);\r
- if (build < Properties.Settings.Default.hb_min_cli)\r
- {\r
- MessageBox.Show(\r
- "It appears you are trying to use a CLI executable that is too old for this version of the HandBrake GUI.\n" +\r
- "Please update the HandBrakeCLI.exe to a newer build.\n\n" +\r
- "HandBrake build Detected: " + Properties.Settings.Default.hb_version,\r
- "Error",\r
- MessageBoxButtons.OK,\r
- MessageBoxIcon.Error);\r
- return;\r
- }\r
+ ShowExceptiowWindow("Unable to retrieve version information from the CLI.", e.ToString());\r
}\r
}\r
\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<QueueTask> list = Ser.Deserialize(strm) as List<QueueTask>;\r
if (list != null)\r
{\r
if (list.Count != 0)\r
/// <summary>\r
/// Recover a queue from file.\r
/// </summary>\r
- public static void RecoverQueue(IQueue encodeQueue)\r
+ /// <param name="encodeQueue">\r
+ /// The encode Queue.\r
+ /// </param>\r
+ public static void RecoverQueue(IQueueProcessor encodeQueue)\r
{\r
+ string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\");\r
+\r
DialogResult result = DialogResult.None;\r
List<string> queueFiles = CheckQueueRecovery();\r
if (queueFiles.Count == 1)\r
{\r
foreach (string file in queueFiles)\r
{\r
- encodeQueue.LoadQueueFromFile(file); // Start Recovery\r
+ encodeQueue.QueueManager.RestoreQueue(appDataPath + 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
- string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\");\r
foreach (string file in queueFiles)\r
{\r
- if (File.Exists(Path.Combine(tempPath, file)))\r
- File.Delete(Path.Combine(tempPath, file));\r
+ if (File.Exists(Path.Combine(appDataPath, file)))\r
+ File.Delete(Path.Combine(appDataPath, file));\r
}\r
}\r
}\r
\r
/// <summary>\r
- /// Checks if this HandBrake is running multiple instances\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
\r
/// <summary>\r
- /// Clear all the encode log files.\r
- /// </summary>\r
- public static void ClearLogs()\r
- {\r
- string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
- if (Directory.Exists(logDir))\r
- {\r
- DirectoryInfo info = new DirectoryInfo(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"))\r
- File.Delete(file.FullName);\r
- }\r
- }\r
- }\r
-\r
- /// <summary>\r
- /// Clear old log files x days in the past\r
- /// </summary>\r
- public static void ClearOldLogs()\r
- {\r
- string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
- if (Directory.Exists(logDir))\r
- {\r
- DirectoryInfo info = new DirectoryInfo(logDir);\r
- FileInfo[] logFiles = info.GetFiles("*.txt");\r
-\r
- foreach (FileInfo file in logFiles)\r
- {\r
- if (file.LastWriteTime < DateTime.Now.AddDays(-30))\r
- {\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
- /// <summary>\r
- /// Begins checking for an update to HandBrake.\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
- {\r
- ThreadPool.QueueUserWorkItem(new WaitCallback(delegate\r
- {\r
- try\r
- {\r
- // Is this a stable or unstable build?\r
- string url =\r
- Properties.Settings.Default.hb_build.ToString()\r
- .EndsWith("1")\r
- ? Properties.Settings.Default.\r
- appcast_unstable\r
- : 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(\r
- new StreamReader(response.GetResponseStream())\r
- .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
-\r
- // If the user wanted to skip this version, don't report the update\r
- if (latest == skip)\r
- {\r
- UpdateCheckInformation info =\r
- new UpdateCheckInformation\r
- {\r
- NewVersionAvailable = false,\r
- BuildInformation = null\r
- };\r
- callback(new UpdateCheckResult(debug, info));\r
- return;\r
- }\r
-\r
- // Set when the last update was\r
- Properties.Settings.Default.lastUpdateCheckDate =\r
- DateTime.Now;\r
- Properties.Settings.Default.Save();\r
-\r
- UpdateCheckInformation info2 =\r
- new UpdateCheckInformation\r
- {\r
- NewVersionAvailable = latest > current,\r
- BuildInformation = reader\r
- };\r
- callback(new UpdateCheckResult(debug, info2));\r
- }\r
- catch (Exception exc)\r
- {\r
- callback(new UpdateCheckResult(debug, new UpdateCheckInformation { Error = exc }));\r
- }\r
- }));\r
- }\r
-\r
- /// <summary>\r
- /// End Check for Updates\r
- /// </summary>\r
- /// <param name="result">\r
- /// The result.\r
- /// </param>\r
- /// <returns>\r
- /// Update Check information\r
- /// </returns>\r
- public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)\r
- {\r
- UpdateCheckResult checkResult = (UpdateCheckResult)result;\r
- return checkResult.Result;\r
- }\r
-\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
}\r
\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
- }\r
- return drives;\r
- }\r
-\r
- /// <summary>\r
/// Change a string to Title Case/\r
/// </summary>\r
/// <param name="input">\r
StringBuilder sb = new StringBuilder(input.Length);\r
foreach (string s in tokens)\r
{\r
- sb.Append(s[0].ToString().ToUpper());\r
- sb.Append(s.Substring(1).ToLower());\r
- sb.Append(" ");\r
+ if (!string.IsNullOrEmpty(s))\r
+ {\r
+ sb.Append(s[0].ToString().ToUpper());\r
+ sb.Append(s.Substring(1).ToLower());\r
+ sb.Append(" ");\r
+ }\r
}\r
\r
return sb.ToString().Trim();\r
/// </param>\r
public static void ShowExceptiowWindow(string shortError, string longError)\r
{\r
- frmExceptionWindow exceptionWindow = new frmExceptionWindow();\r
- exceptionWindow.Setup(shortError, longError);\r
- exceptionWindow.Show();\r
+ errorService.ShowError(shortError, longError);\r
}\r
\r
/// <summary>\r