X-Git-Url: http://git.osdn.jp/view?a=blobdiff_plain;f=win%2FC%23%2FfrmActivityWindow.cs;h=613a1a4c2c31a912d16abb5fa1f0940996703642;hb=4f0019f03c2e85e8634150ff0c9a31bee6d35ce5;hp=63157909c9b38c8d6ba8ac13c9c2e841adee25f4;hpb=83f94313f43f1e3c02159cbc86d3721c7c2da288;p=handbrake-jp%2Fhandbrake-jp-git.git diff --git a/win/C#/frmActivityWindow.cs b/win/C#/frmActivityWindow.cs index 63157909..613a1a4c 100644 --- a/win/C#/frmActivityWindow.cs +++ b/win/C#/frmActivityWindow.cs @@ -1,206 +1,502 @@ /* 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 Functions; + using Model; + using Services; + using Timer = System.Threading.Timer; + + /// + /// The Activity Log Window + /// public partial class frmActivityWindow : Form { + /* Private Variables */ + + /// + /// The current position in the log file + /// + private int position; + + /// + /// A Timer for this window + /// + private Timer windowTimer; + + /// + /// The Encode Object + /// + private Encode encode; - 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 Scan Object + /// + private ScanService scan; + + /// + /// The Type of log that the window is currently dealing with + /// + private ActivityLogMode mode; + + /* Constructor */ /// - /// This window should be used to display the RAW output of the handbrake CLI which is produced during an encode. + /// Initializes a new instance of the class. /// - /// - public frmActivityWindow(string file, frmMain fm, frmQueue fq) + /// + /// The encode. + /// + /// + /// The scan. + /// + public frmActivityWindow(Encode encode, ScanService scan) { InitializeComponent(); - mainWindow = fm; - queueWindow = fq; - read_file = file; + this.encode = encode; + this.scan = scan; + this.position = 0; - // Reset some varibles - this.rtf_actLog.Text = string.Empty; - position = 0; + // Listen for Scan and Encode Starting Events + scan.ScanStared += scan_ScanStared; + encode.EncodeStarted += encode_EncodeStarted; + } - string logFile = Path.Combine(Path.GetTempPath(), read_file); - if (File.Exists(logFile)) + /* 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) + { + if (IsHandleCreated) { + if (rtf_actLog.InvokeRequired) + { + IAsyncResult invoked = BeginInvoke(new SetModeCallback(SetMode), new object[] {setMode}); + EndInvoke(invoked); + } + else + { + Reset(); + this.mode = setMode; + + Array values = Enum.GetValues(typeof(ActivityLogMode)); + Properties.Settings.Default.ActivityWindowLastMode = (int) values.GetValue(Convert.ToInt32(setMode)); + Properties.Settings.Default.Save(); + + 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; + } - // Get the CPU Processor Name - RegistryKey RegKey = Registry.LocalMachine; - RegKey = RegKey.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"); - Object cpuType = RegKey.GetValue("ProcessorNameString"); - - // Get the screen resolution - System.Windows.Forms.Screen scr = System.Windows.Forms.Screen.PrimaryScreen; - - // Physical Ram - Functions.SystemInfo info = new Functions.SystemInfo(); - uint memory = info.TotalPhysicalMemory(); - - // 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("### Ram: {0} MB \n", memory)); - rtf_actLog.AppendText(String.Format("### Screen: {0}x{1} \n", scr.Bounds.Width, scr.Bounds.Height)); - 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(); + // Start a fresh window timer + windowTimer = new Timer(new TimerCallback(LogMonitor), null, 1000, 1000); + } } - 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); + } - // Handle the event of the window being disposed. This is needed to make sure HandBrake exit's cleanly. - this.Disposed += new EventHandler(forceQuit); + /// + /// On Window load, start a new timer + /// + /// + /// The sender. + /// + /// + /// The e. + /// + private void NewActivityWindow_Load(object sender, EventArgs e) + { + ActivityLogMode activitLogMode = (ActivityLogMode) Enum.ToObject(typeof(ActivityLogMode), Properties.Settings.Default.ActivityWindowLastMode); + SetMode(activitLogMode); } - // 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) + /// + /// Set the Log window to encode mode when an encode starts. + /// + /// + /// The sender. + /// + /// + /// The e. + /// + private void encode_EncodeStarted(object sender, EventArgs e) { - if (monitorFile != null) - monitorFile.Abort(); + SetMode(ActivityLogMode.Encode); + } - this.Close(); + /// + /// 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); } - // Update the Activity window every 5 seconds with the latest log data. - private void autoUpdate(object state) + /// + /// Stop refreshing the window when no scanning or encoding is happening. + /// + /// + /// The sender. + /// + /// + /// The e. + /// + private void stopWindowRefresh(object sender, EventArgs e) { - Boolean lastUpdate = false; - updateTextFromThread(); - while (true) - { - if ((mainWindow.isEncoding() == true) || (queueWindow.isEncoding() == true)) - updateTextFromThread(); - else + windowTimer.Dispose(); + 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(); + + if (this.mode == ActivityLogMode.Scan) + { + if (scan == null || scan.ActivityLog == string.Empty) { - // The encode may just have stoped, so, refresh the log one more time before restarting it. - if (lastUpdate == false) - updateTextFromThread(); + appendText.AppendFormat("Waiting for the log to be generated ...\n"); + position = 0; + ClearWindowText(); + PrintLogHeader(); + return appendText; + } - lastUpdate = true; + using (StringReader reader = new StringReader(scan.ActivityLog)) + { + LogReader(reader, appendText); + } + } + else + { + if (encode == null || encode.ActivityLog == string.Empty) + { + appendText.AppendFormat("Waiting for the log to be generated ...\n"); position = 0; + ClearWindowText(); + PrintLogHeader(); + return appendText; + } + + using (StringReader reader = new StringReader(encode.ActivityLog)) + { + LogReader(reader, appendText); } - Thread.Sleep(5000); } + return appendText; } - private delegate void UpdateUIHandler(); - private void updateTextFromThread() + /// + /// Reads the log data from a Scan or Encode object + /// + /// + /// The reader. + /// + /// + /// The append text. + /// + private void LogReader(StringReader reader, StringBuilder appendText) { - try + string line; + int i = 1; + while ((line = reader.ReadLine()) != null) { - if (this.InvokeRequired) + if (i > position) { - this.BeginInvoke(new UpdateUIHandler(updateTextFromThread)); - return; + appendText.AppendLine(line); + position++; } - // Initialize a pointer and get the log data arraylist - ArrayList data = readFile(); + i++; + } + } - while (position < data.Count) + /// + /// Append text to the RTF box + /// + /// + /// The text. + /// + private void AppendWindowText(StringBuilder text) + { + try + { + if (IsHandleCreated) { - rtf_actLog.AppendText(data[position].ToString()); - if (data[position].ToString().Contains("has exited")) + if (rtf_actLog.InvokeRequired) { - rtf_actLog.AppendText("\n ############ End of Encode ############## \n"); + IAsyncResult invoked = BeginInvoke(new SetTextCallback(AppendWindowText), new object[] { text }); + EndInvoke(invoked); } - position++; - } + else + lock (rtf_actLog) + rtf_actLog.AppendText(text.ToString()); - // this.rtf_actLog.SelectionStart = this.rtf_actLog.Text.Length - 1; - // this.rtf_actLog.ScrollToCaret(); + // Stop the refresh process if log has finished. + if (text.ToString().Contains("HandBrake has Exited")) + { + windowTimer.Dispose(); + } + } } - catch (Exception exc) + catch (Exception) { - 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); + return; } } - private ArrayList readFile() + /// + /// Clear the contents of the log window + /// + private void ClearWindowText() { - // 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(); + try + { + if (IsHandleCreated) + { + if (rtf_actLog.InvokeRequired) + { + IAsyncResult invoked = BeginInvoke(new SetTextClearCallback(ClearWindowText)); + EndInvoke(invoked); + } + else + lock (rtf_actLog) + rtf_actLog.Clear(); + } + } + catch (Exception) + { + return; + } + } + /// + /// Display the log header + /// + private void PrintLogHeader() + { 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 SetTextClearCallback(PrintLogHeader)); + EndInvoke(invoked); + } + else + { + lock (rtf_actLog) + { + // Print the log header. This function will be re-implimented later. Do not delete. + StringBuilder header = new StringBuilder(); - line = sr.ReadLine(); - } - sr.Close(); - sr.Dispose(); + header.Append(String.Format("### Windows GUI {1} {0} \n", Properties.Settings.Default.hb_build, Properties.Settings.Default.hb_version)); + header.Append(String.Format("### Running: {0} \n###\n", Environment.OSVersion)); + header.Append(String.Format("### CPU: {0} \n", SystemInfo.GetCpuCount)); + header.Append(String.Format("### Ram: {0} MB \n", SystemInfo.TotalPhysicalMemory)); + header.Append(String.Format("### Screen: {0}x{1} \n", SystemInfo.ScreenBounds.Bounds.Width, SystemInfo.ScreenBounds.Bounds.Height)); + header.Append(String.Format("### Temp Dir: {0} \n", Path.GetTempPath())); + header.Append(String.Format("### Install Dir: {0} \n", Application.StartupPath)); + header.Append(String.Format("### Data Dir: {0} \n", Application.UserAppDataPath)); + header.Append("#########################################\n\n"); - return logData; + rtf_actLog.AppendText(header.ToString()); + } + } + } } - 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(); + PrintLogHeader(); + 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); + } + + /// + /// 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); + } + + /// + /// Set scan mode + /// + /// + /// The sender. + /// + /// + /// The e. + /// + private void BtnScanLogClick(object sender, EventArgs e) + { + SetMode(ActivityLogMode.Scan); + } - // Ok, We need to make sure the monitor thread is dead when we close the window. + /// + /// Set the encode mode + /// + /// + /// The sender. + /// + /// + /// The e. + /// + private void BtnEncodeLogClick(object sender, EventArgs e) + { + SetMode(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