X-Git-Url: http://git.osdn.jp/view?a=blobdiff_plain;f=win%2FC%23%2FfrmActivityWindow.cs;h=ee3d3bf750d20980f044f3efd290bbfaad629469;hb=4560ade3c833f282f02d15a9473e233488617df9;hp=36e405b383fc318d1812f3944dd8b9d64284e66b;hpb=4e3111f326a09f5fab0602b974636668dd6c6006;p=handbrake-jp%2Fhandbrake-jp-git.git diff --git a/win/C#/frmActivityWindow.cs b/win/C#/frmActivityWindow.cs index 36e405b3..ee3d3bf7 100644 --- a/win/C#/frmActivityWindow.cs +++ b/win/C#/frmActivityWindow.cs @@ -1,197 +1,477 @@ /* frmActivityWindow.cs $ - - This file is part of the HandBrake source code. - Homepage: . - It may be used under the terms of the GNU General Public License. */ - -using System; -using System.Collections; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.IO; -using System.Threading; -using System.Diagnostics; -using System.Runtime.InteropServices; -using Microsoft.Win32; + This file is part of the HandBrake source code. + Homepage: . + It may be used under the terms of the GNU General Public License. */ namespace Handbrake { + using System; + using System.ComponentModel; + using System.Diagnostics; + using System.IO; + using System.Text; + using System.Threading; + using System.Windows.Forms; + + using HandBrake.Framework.Services; + using HandBrake.Framework.Services.Interfaces; + using HandBrake.ApplicationServices.Services.Interfaces; + + using Model; + using Timer = System.Threading.Timer; + + /// + /// The Activity Log Window + /// public partial class frmActivityWindow : Form { + /* Private Variables */ - Thread monitorFile; - String read_file; - frmMain mainWindow; - frmQueue queueWindow; - int position = 0; // Position in the arraylist reached by the current log output in the rtf box. - + /// + /// The Encode Object + /// + private readonly IQueue encode; /// - /// This window should be used to display the RAW output of the handbrake CLI which is produced during an encode. + /// The Scan Object /// - /// - public frmActivityWindow(string file, frmMain fm, frmQueue fq) - { - InitializeComponent(); + private readonly IScan scan; - mainWindow = fm; - queueWindow = fq; - read_file = file; + /// + /// The Error service + /// + private readonly IErrorService errorService = new ErrorService(); - // Reset some varibles - this.rtf_actLog.Text = string.Empty; - position = 0; + /// + /// The current position in the log file + /// + private int position; - string logFile = Path.Combine(Path.GetTempPath(), read_file); - if (File.Exists(logFile)) - { + /// + /// A Timer for this window + /// + private Timer windowTimer; - // Get the CPU Processor Name - RegistryKey RegKey = Registry.LocalMachine; - RegKey = RegKey.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"); - Object cpuType = RegKey.GetValue("ProcessorNameString"); - - // Add a header to the log file indicating that it's from the Windows GUI and display the windows version - rtf_actLog.AppendText("### Windows GUI \n"); - rtf_actLog.AppendText(String.Format("### Running: {0} \n###\n", Environment.OSVersion.ToString())); - rtf_actLog.AppendText(String.Format("### CPU: {0} \n", cpuType)); - rtf_actLog.AppendText(String.Format("### Temp Dir: {0} \n", Path.GetTempPath())); - rtf_actLog.AppendText(String.Format("### Install Dir: {0} \n", Application.StartupPath)); - rtf_actLog.AppendText(String.Format("### Data Dir: {0} \n###\n", Application.UserAppDataPath)); - - // Start a new thread to run the autoUpdate process - monitorFile = new Thread(autoUpdate); - monitorFile.Start(); - } - else - MessageBox.Show("The log file could not be found. Maybe you cleared your system's tempory folder or maybe you just havn't run an encode yet.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Warning); + /// + /// The Type of log that the window is currently dealing with + /// + private ActivityLogMode mode; - // Handle the event of the window being disposed. This is needed to make sure HandBrake exit's cleanly. - this.Disposed += new EventHandler(forceQuit); - } + /* Constructor */ - // Ok, so, this function is called when someone closes frmMain but didn't close frmActivitWindow first. - // When you close frmMain, the activity window gets closed (disposed of) but, this doens't kill the threads that it started. - // When that thread tries to access the disposed rich text box, it causes an exception. - // Basically, this function is called when the window is disposed of, to kill the thread and close the window properly. - // This allows HandBrake to close cleanly. - private void forceQuit(object sender, EventArgs e) + /// + /// Initializes a new instance of the class. + /// + /// + /// The encode. + /// + /// + /// The scan. + /// + public frmActivityWindow(IQueue encode, IScan scan) { - if (monitorFile != null) - monitorFile.Abort(); + InitializeComponent(); + + this.encode = encode; + this.scan = scan; + this.position = 0; - this.Close(); + // Listen for Scan and Encode Starting Events + scan.ScanStared += scan_ScanStared; + encode.EncodeStarted += encode_EncodeStarted; } - // Update the Activity window every 5 seconds with the latest log data. - private void autoUpdate(object state) + /* Delegates */ + + /// + /// A callback function for updating the ui + /// + /// + /// The text. + /// + private delegate void SetTextCallback(StringBuilder text); + + /// + /// Clear text callback + /// + private delegate void SetTextClearCallback(); + + /// + /// Set mode callback + /// + /// + /// The set mode. + /// + private delegate void SetModeCallback(ActivityLogMode setMode); + + /* Private Methods */ + + /// + /// Set the window to scan mode + /// + /// + /// The set Mode. + /// + private void SetMode(ActivityLogMode setMode) { - Boolean lastUpdate = false; - updateTextFromThread(); - while (true) - { - if ((mainWindow.isEncoding() == true) || (queueWindow.isEncoding() == true)) - updateTextFromThread(); + if (IsHandleCreated) + { + if (rtf_actLog.InvokeRequired) + { + IAsyncResult invoked = BeginInvoke(new SetModeCallback(SetMode), new object[] { setMode }); + EndInvoke(invoked); + } else { - // The encode may just have stoped, so, refresh the log one more time before restarting it. - if (lastUpdate == false) - updateTextFromThread(); + Reset(); + this.mode = setMode; + + Array values = Enum.GetValues(typeof(ActivityLogMode)); + Properties.Settings.Default.ActivityWindowLastMode = (int)values.GetValue(Convert.ToInt32(setMode)); + Properties.Settings.Default.Save(); - lastUpdate = true; - position = 0; + this.Text = mode == ActivityLogMode.Scan + ? "Activity Window (Scan Log)" + : "Activity Window (Encode Log)"; + + if (mode == ActivityLogMode.Scan) + { + scan.ScanCompleted += stopWindowRefresh; + encode.EncodeEnded -= stopWindowRefresh; + } + else + { + scan.ScanCompleted -= stopWindowRefresh; + encode.EncodeEnded += stopWindowRefresh; + } + + // Start a fresh window timer + windowTimer = new Timer(new TimerCallback(LogMonitor), null, 1000, 1000); } - Thread.Sleep(5000); } } - private delegate void UpdateUIHandler(); - private void updateTextFromThread() + /// + /// On Window load, start a new timer + /// + /// + /// The sender. + /// + /// + /// The EventArgs. + /// + private void ActivityWindowLoad(object sender, EventArgs e) { try { - if (this.InvokeRequired) + // Set the inital log file. + if (encode.IsEncoding) + { + this.logSelector.SelectedIndex = 1; + } + else if (scan.IsScanning) { - this.BeginInvoke(new UpdateUIHandler(updateTextFromThread)); - return; + this.logSelector.SelectedIndex = 0; } - // Initialize a pointer and get the log data arraylist - ArrayList data = readFile(); + else + { + // Otherwise, use the last mode the window was in. + ActivityLogMode activitLogMode = (ActivityLogMode)Enum.ToObject(typeof(ActivityLogMode), Properties.Settings.Default.ActivityWindowLastMode); + this.logSelector.SelectedIndex = activitLogMode == ActivityLogMode.Scan ? 0 : 1; + } + } + catch (Exception exc) + { + errorService.ShowError("Error during load.", exc.ToString()); + } + } - while (position < data.Count) + /// + /// Set the Log window to encode mode when an encode starts. + /// + /// + /// The sender. + /// + /// + /// The e. + /// + private void encode_EncodeStarted(object sender, EventArgs e) + { + SetMode(ActivityLogMode.Encode); + } + + /// + /// Set the log widow to scan mode when a scan starts + /// + /// + /// The sender. + /// + /// + /// The e. + /// + private void scan_ScanStared(object sender, EventArgs e) + { + SetMode(ActivityLogMode.Scan); + } + + /// + /// Stop refreshing the window when no scanning or encoding is happening. + /// + /// + /// The sender. + /// + /// + /// The e. + /// + private void stopWindowRefresh(object sender, EventArgs e) + { + windowTimer.Dispose(); + Reset(); + LogMonitor(null); + } + + /// + /// Append new text to the window + /// + /// + /// The n. + /// + private void LogMonitor(object n) + { + AppendWindowText(GetLog()); + } + + /// + /// New Code for getting the Activity log from the Services rather than reading a file. + /// + /// + /// The StringBuilder containing a log + /// + private StringBuilder GetLog() + { + StringBuilder appendText = new StringBuilder(); + + try + { + if (this.mode == ActivityLogMode.Scan) { - rtf_actLog.AppendText(data[position].ToString()); - if (data[position].ToString().Contains("has exited")) + if (scan == null || scan.ActivityLog == string.Empty) { - rtf_actLog.AppendText("\n ############ End of Encode ############## \n"); + appendText.AppendFormat("Waiting for the log to be generated ...\n"); + position = 0; + ClearWindowText(); + return appendText; + } + + using (StringReader reader = new StringReader(scan.ActivityLog)) + { + LogReader(reader, appendText); } - position++; } + else + { + if (encode == null || encode.ActivityLog == string.Empty) + { + appendText.AppendFormat("Waiting for the log to be generated ...\n"); + position = 0; + ClearWindowText(); + return appendText; + } - // this.rtf_actLog.SelectionStart = this.rtf_actLog.Text.Length - 1; - // this.rtf_actLog.ScrollToCaret(); + using (StringReader reader = new StringReader(encode.ActivityLog)) + { + LogReader(reader, appendText); + } + } } catch (Exception exc) { - MessageBox.Show("An error has occured in: updateTextFromThread(). \n You may have to restart HandBrake. \n Error Information: \n\n" + exc.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + windowTimer.Dispose(); + errorService.ShowError("GetLog() Error", exc.ToString()); } + + return appendText; } - private ArrayList readFile() + /// + /// Reads the log data from a Scan or Encode object + /// + /// + /// The reader. + /// + /// + /// The append text. + /// + private void LogReader(StringReader reader, StringBuilder appendText) { - // Ok, the task here is to, Get an arraylist of log data. - // And update some global varibles which are pointers to the last displayed log line. - ArrayList logData = new ArrayList(); + string line; + int i = 1; + while ((line = reader.ReadLine()) != null) + { + if (i > position) + { + appendText.AppendLine(line); + position++; + } + i++; + } + } + /// + /// Append text to the RTF box + /// + /// + /// The text. + /// + private void AppendWindowText(StringBuilder text) + { try { - // hb_encode_log.dat is the primary log file. Since .NET can't read this file whilst the CLI is outputing to it (Not even in read only mode), - // we'll need to make a copy of it. - string logFile = Path.Combine(Path.GetTempPath(), read_file); - string logFile2 = Path.Combine(Path.GetTempPath(), "hb_encode_log_AppReadable.dat"); - - // Make sure the application readable log file does not already exist. FileCopy fill fail if it does. - if (File.Exists(logFile2)) - File.Delete(logFile2); - - // Copy the log file. - File.Copy(logFile, logFile2); - - // Open the copied log file for reading - StreamReader sr = new StreamReader(logFile2); - string line = sr.ReadLine(); - while (line != null) + if (IsHandleCreated) { - if (line.Trim() != "") - logData.Add(line + System.Environment.NewLine); + if (rtf_actLog.InvokeRequired) + { + IAsyncResult invoked = BeginInvoke(new SetTextCallback(AppendWindowText), new object[] { text }); + EndInvoke(invoked); + } + else + lock (rtf_actLog) + rtf_actLog.AppendText(text.ToString()); - line = sr.ReadLine(); + // Stop the refresh process if log has finished. + if (text.ToString().Contains("HandBrake has Exited")) + { + windowTimer.Dispose(); + } } - sr.Close(); - sr.Dispose(); + } + catch (Exception) + { + return; + } + } - return logData; + /// + /// Clear the contents of the log window + /// + private void ClearWindowText() + { + try + { + if (IsHandleCreated) + { + if (rtf_actLog.InvokeRequired) + { + IAsyncResult invoked = BeginInvoke(new SetTextClearCallback(ClearWindowText)); + EndInvoke(invoked); + } + else + lock (rtf_actLog) + rtf_actLog.Clear(); + } } - catch (Exception exc) + catch (Exception) { - MessageBox.Show("Error in readFile() \n Unable to read the log file.\n You may have to restart HandBrake.\n Error Information: \n\n" + exc.ToString(), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; } - return null; } + /// + /// Reset Everything + /// + private void Reset() + { + if (windowTimer != null) + windowTimer.Dispose(); + position = 0; + ClearWindowText(); + windowTimer = new Timer(new TimerCallback(LogMonitor), null, 1000, 1000); + } + + /* Menus and Buttons */ + + /// + /// Copy log to clipboard + /// + /// + /// The sender. + /// + /// + /// The e. + /// + private void MnuCopyLogClick(object sender, EventArgs e) + { + Clipboard.SetDataObject(rtf_actLog.SelectedText != string.Empty ? rtf_actLog.SelectedText : rtf_actLog.Text, true); + } - // Ok, We need to make sure the monitor thread is dead when we close the window. + /// + /// Open the log folder + /// + /// + /// The sender. + /// + /// + /// The e. + /// + private void MnuOpenLogFolderClick(object sender, EventArgs e) + { + string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs"; + string windir = Environment.GetEnvironmentVariable("WINDIR"); + Process prc = new Process + { + StartInfo = + { + FileName = windir + @"\explorer.exe", + Arguments = logDir + } + }; + prc.Start(); + } + + /// + /// Copy the log + /// + /// + /// The sender. + /// + /// + /// The e. + /// + private void BtnCopyClick(object sender, EventArgs e) + { + Clipboard.SetDataObject(rtf_actLog.SelectedText != string.Empty ? rtf_actLog.SelectedText : rtf_actLog.Text, true); + } + + /// + /// Change the Log file in the viewer + /// + /// The Sender + /// The EventArgs + private void LogSelectorClick(object sender, EventArgs e) + { + this.SetMode((string)this.logSelector.SelectedItem == "Scan Log" ? ActivityLogMode.Scan : ActivityLogMode.Encode); + } + + /* Overrides */ + + /// + /// override onclosing + /// + /// + /// The e. + /// protected override void OnClosing(CancelEventArgs e) { - if (monitorFile != null) - monitorFile.Abort(); + scan.ScanStared -= scan_ScanStared; + encode.EncodeStarted -= encode_EncodeStarted; + + scan.ScanCompleted -= stopWindowRefresh; + encode.EncodeEnded -= stopWindowRefresh; + + windowTimer.Dispose(); e.Cancel = true; - this.Hide(); + this.Dispose(); base.OnClosing(e); } - } } \ No newline at end of file