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
8 using System.Diagnostics;
\r
10 using System.Windows.Forms;
\r
11 using Handbrake.Functions;
\r
13 namespace Handbrake.EncodeQueue
\r
16 /// Class which handles the CLI
\r
23 private int ProcessID { get; set; }
\r
28 public Process HbProcess { get; set; }
\r
31 /// The Process Handle
\r
33 public IntPtr ProcessHandle { get; set; }
\r
36 /// Returns true of HandBrakeCLI.exe is running
\r
38 public Boolean IsEncoding { get; set; }
\r
41 /// Fires when a new CLI Job starts
\r
43 public event EventHandler EncodeStarted;
\r
46 /// Fires when a CLI job finishes.
\r
48 public event EventHandler EncodeEnded;
\r
51 /// Create a preview sample video
\r
53 /// <param name="query"></param>
\r
54 public void CreatePreviewSample(string query)
\r
60 /// Execute a HandBrakeCLI process.
\r
62 /// <param name="query">The CLI Query</param>
\r
63 protected void Run(string query)
\r
67 if (EncodeStarted != null)
\r
68 EncodeStarted(this, new EventArgs());
\r
72 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
73 string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs", "last_encode_log.txt");
\r
74 string strCmdLine = String.Format(@" /C """"{0}"" {1} 2>""{2}"" """, handbrakeCLIPath, query, logPath);
\r
75 ProcessStartInfo cliStart = new ProcessStartInfo("CMD.exe", strCmdLine);
\r
77 if (Properties.Settings.Default.enocdeStatusInGui)
\r
79 cliStart.RedirectStandardOutput = true;
\r
80 cliStart.UseShellExecute = false;
\r
81 if (!Properties.Settings.Default.showCliForInGuiEncodeStatus)
\r
82 cliStart.CreateNoWindow = true;
\r
84 if (Properties.Settings.Default.cli_minimized)
\r
85 cliStart.WindowStyle = ProcessWindowStyle.Minimized;
\r
87 Process[] before = Process.GetProcesses(); // Get a list of running processes before starting.
\r
88 HbProcess = Process.Start(cliStart);
\r
89 ProcessID = Main.GetCliProcess(before);
\r
91 if (HbProcess != null)
\r
92 ProcessHandle = HbProcess.MainWindowHandle; // Set the process Handle
\r
94 // Set the process Priority
\r
95 Process hbCliProcess = null;
\r
96 if (ProcessID != -1)
\r
97 hbCliProcess = Process.GetProcessById(ProcessID);
\r
99 if (hbCliProcess != null)
\r
100 switch (Properties.Settings.Default.processPriority)
\r
103 hbCliProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
106 hbCliProcess.PriorityClass = ProcessPriorityClass.High;
\r
108 case "Above Normal":
\r
109 hbCliProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
112 hbCliProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
115 hbCliProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
118 hbCliProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
122 catch (Exception exc)
\r
124 MessageBox.Show("It would appear that HandBrakeCLI has not started correctly. You should take a look at the Activity log as it may indicate the reason why.\n\n Detailed Error Information: error occured in runCli()\n\n" + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
\r
129 /// Function to run the CLI directly rather than via CMD
\r
130 /// TODO: Code to handle the Log data has yet to be written.
\r
131 /// TODO: Code to handle the % / ETA info has to be written.
\r
133 protected void DirectRun(string query)
\r
137 if (EncodeStarted != null)
\r
138 EncodeStarted(this, new EventArgs());
\r
143 string handbrakeCLIPath = Path.Combine(Environment.CurrentDirectory, "HandBrakeCLI.exe");
\r
144 Process hbProc = new Process
\r
148 FileName = handbrakeCLIPath,
\r
150 UseShellExecute = false,
\r
151 RedirectStandardOutput = true,
\r
152 RedirectStandardError = true,
\r
153 RedirectStandardInput = true,
\r
154 CreateNoWindow = false,
\r
155 WindowStyle = ProcessWindowStyle.Minimized
\r
159 // Setup the redirects
\r
160 hbProc.ErrorDataReceived += new DataReceivedEventHandler(HbProcErrorDataReceived);
\r
161 hbProc.OutputDataReceived += new DataReceivedEventHandler(HbProcOutputDataReceived);
\r
163 // Start the process
\r
166 // Set the Process Priority
\r
167 switch (Properties.Settings.Default.processPriority)
\r
170 hbProc.PriorityClass = ProcessPriorityClass.RealTime;
\r
173 hbProc.PriorityClass = ProcessPriorityClass.High;
\r
175 case "Above Normal":
\r
176 hbProc.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
179 hbProc.PriorityClass = ProcessPriorityClass.Normal;
\r
182 hbProc.PriorityClass = ProcessPriorityClass.Idle;
\r
185 hbProc.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
189 // Set the class items
\r
190 HbProcess = hbProc;
\r
191 ProcessID = hbProc.Id;
\r
192 ProcessHandle = hbProc.Handle;
\r
195 catch (Exception exc)
\r
197 Console.WriteLine(exc);
\r
202 /// Kill the CLI process
\r
206 if (HbProcess != null)
\r
209 Process[] list = Process.GetProcessesByName("HandBrakeCLI");
\r
210 foreach (Process process in list)
\r
213 IsEncoding = false;
\r
215 if (EncodeEnded != null)
\r
216 EncodeEnded(this, new EventArgs());
\r
220 /// Attempt to Safely kill a DirectRun() CLI
\r
221 /// NOTE: This will not work with a MinGW CLI
\r
222 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
224 public void SafelyClose()
\r
226 if ((int)ProcessHandle == 0)
\r
229 // Allow the CLI to exit cleanly
\r
230 Win32.SetForegroundWindow((int)ProcessHandle);
\r
231 SendKeys.Send("^C");
\r
233 // HbProcess.StandardInput.AutoFlush = true;
\r
234 // HbProcess.StandardInput.WriteLine("^C");
\r
238 /// Recieve the Standard Error information and process it
\r
240 /// <param name="sender"></param>
\r
241 /// <param name="e"></param>
\r
242 private static void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
244 // TODO: Recieve the Log data and process it
\r
245 throw new NotImplementedException();
\r
249 /// Standard Input Data Recieved from the CLI
\r
251 /// <param name="sender"></param>
\r
252 /// <param name="e"></param>
\r
253 private static void HbProcOutputDataReceived(object sender, DataReceivedEventArgs e)
\r
255 // TODO: Recieve the %, ETA, FPS etc and process it
\r
256 throw new NotImplementedException();
\r
260 /// Perform an action after an encode. e.g a shutdown, standby, restart etc.
\r
262 protected void Finish()
\r
264 if (EncodeEnded != null)
\r
265 EncodeEnded(this, new EventArgs());
\r
267 IsEncoding = false;
\r
270 if (Properties.Settings.Default.growlQueue)
\r
271 GrowlCommunicator.Notify("Queue Completed", "Put down that cocktail...\nyour Handbrake queue is done.");
\r
273 // Do something whent he encode ends.
\r
274 switch (Properties.Settings.Default.CompletionOption)
\r
277 Process.Start("Shutdown", "-s -t 60");
\r
280 Win32.ExitWindowsEx(0, 0);
\r
283 Application.SetSuspendState(PowerState.Suspend, true, true);
\r
286 Application.SetSuspendState(PowerState.Hibernate, true, true);
\r
288 case "Lock System":
\r
289 Win32.LockWorkStation();
\r
291 case "Quit HandBrake":
\r
292 Application.Exit();
\r
300 /// Add the CLI Query to the Log File.
\r
302 /// <param name="encJob"></param>
\r
303 protected void AddCLIQueryToLog(Job encJob)
\r
307 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
308 "\\HandBrake\\logs";
\r
309 string logPath = Path.Combine(logDir, "last_encode_log.txt");
\r
311 StreamReader reader =
\r
312 new StreamReader(File.Open(logPath, FileMode.Open, FileAccess.Read, FileShare.Read));
\r
313 String log = reader.ReadToEnd();
\r
316 StreamWriter writer = new StreamWriter(File.Create(logPath));
\r
318 writer.Write("### CLI Query: " + encJob.Query + "\n\n");
\r
319 writer.Write("### User Query: " + encJob.CustomQuery + "\n\n");
\r
320 writer.Write("#########################################\n\n");
\r
321 writer.WriteLine(log);
\r
324 } catch (Exception)
\r
331 /// Save a copy of the log to the users desired location or a default location
\r
332 /// if this feature is enabled in options.
\r
334 /// <param name="destination"></param>
\r
335 protected void CopyLog(string destination)
\r
339 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
340 string tempLogFile = Path.Combine(logDir, "last_encode_log.txt");
\r
342 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
343 String destinationFile = Path.GetFileName(destination);
\r
344 string encodeLogFile = destinationFile + " " + DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
346 // Make sure the log directory exists.
\r
347 if (!Directory.Exists(logDir))
\r
348 Directory.CreateDirectory(logDir);
\r
350 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
351 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
353 // Save a copy of the log file in the same location as the enocde.
\r
354 if (Properties.Settings.Default.saveLogWithVideo)
\r
355 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
357 // Save a copy of the log file to a user specified location
\r
358 if (Directory.Exists(Properties.Settings.Default.saveLogPath))
\r
359 if (Properties.Settings.Default.saveLogPath != String.Empty && Properties.Settings.Default.saveLogToSpecifiedPath)
\r
360 File.Copy(tempLogFile, Path.Combine(Properties.Settings.Default.saveLogPath, encodeLogFile));
\r
362 catch (Exception exc)
\r
364 MessageBox.Show("Something went a bit wrong trying to copy your log file.\nError Information:\n\n" + exc, "Error",
\r
365 MessageBoxButtons.OK, MessageBoxIcon.Error);
\r