OSDN Git Service

CLI: update the built in presets
[handbrake-jp/handbrake-jp-git.git] / win / C# / frmActivityWindow.cs
index 9e26170..ee3d3bf 100644 (file)
 /*  frmActivityWindow.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.ComponentModel;\r
-using System.Text;\r
-using System.Windows.Forms;\r
-using System.IO;\r
-using System.Threading;\r
-using Handbrake.EncodeQueue;\r
-using Handbrake.Functions;\r
-using Microsoft.Win32;\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
 namespace Handbrake\r
 {\r
+    using System;\r
+    using System.ComponentModel;\r
+    using System.Diagnostics;\r
+    using System.IO;\r
+    using System.Text;\r
+    using System.Threading;\r
+    using System.Windows.Forms;\r
+\r
+    using HandBrake.Framework.Services;\r
+    using HandBrake.Framework.Services.Interfaces;\r
+    using HandBrake.ApplicationServices.Services.Interfaces;\r
+\r
+    using Model;\r
+    using Timer = System.Threading.Timer;\r
+\r
+    /// <summary>\r
+    /// The Activity Log Window\r
+    /// </summary>\r
     public partial class frmActivityWindow : Form\r
     {\r
-        private delegate void setTextCallback(StringBuilder text);\r
-        private delegate void setTextClearCallback();\r
-        private static int _position;\r
-        private static string _lastMode;\r
-        private static string _currentMode;\r
+        /* Private Variables */\r
+\r
+        /// <summary>\r
+        /// The Encode Object\r
+        /// </summary>\r
+        private readonly IQueue encode;\r
+\r
+        /// <summary>\r
+        /// The Scan Object\r
+        /// </summary>\r
+        private readonly IScan scan;\r
 \r
-        public frmActivityWindow()\r
+        /// <summary>\r
+        /// The Error service\r
+        /// </summary>\r
+        private readonly IErrorService errorService = new ErrorService();\r
+\r
+        /// <summary>\r
+        /// The current position in the log file\r
+        /// </summary>\r
+        private int position;\r
+\r
+        /// <summary>\r
+        /// A Timer for this window\r
+        /// </summary>\r
+        private Timer windowTimer;\r
+\r
+        /// <summary>\r
+        /// The Type of log that the window is currently dealing with\r
+        /// </summary>\r
+        private ActivityLogMode mode;\r
+\r
+        /* Constructor */\r
+\r
+        /// <summary>\r
+        /// Initializes a new instance of the <see cref="frmActivityWindow"/> class.\r
+        /// </summary>\r
+        /// <param name="encode">\r
+        /// The encode.\r
+        /// </param>\r
+        /// <param name="scan">\r
+        /// The scan.\r
+        /// </param>\r
+        public frmActivityWindow(IQueue encode, IScan scan)\r
         {\r
             InitializeComponent();\r
+\r
+            this.encode = encode;\r
+            this.scan = scan;\r
+            this.position = 0;\r
+\r
+            // Listen for Scan and Encode Starting Events\r
+            scan.ScanStared += scan_ScanStared;\r
+            encode.EncodeStarted += encode_EncodeStarted;\r
         }\r
-        private void NewActivityWindow_Load(object sender, EventArgs e)\r
+\r
+        /* Delegates */\r
+\r
+        /// <summary>\r
+        /// A callback function for updating the ui\r
+        /// </summary>\r
+        /// <param name="text">\r
+        /// The text.\r
+        /// </param>\r
+        private delegate void SetTextCallback(StringBuilder text);\r
+\r
+        /// <summary>\r
+        /// Clear text callback\r
+        /// </summary>\r
+        private delegate void SetTextClearCallback();\r
+\r
+        /// <summary>\r
+        /// Set mode callback\r
+        /// </summary>\r
+        /// <param name="setMode">\r
+        /// The set mode.\r
+        /// </param>\r
+        private delegate void SetModeCallback(ActivityLogMode setMode);\r
+\r
+        /* Private Methods */\r
+\r
+        /// <summary>\r
+        /// Set the window to scan mode\r
+        /// </summary>\r
+        /// <param name="setMode">\r
+        /// The set Mode.\r
+        /// </param>\r
+        private void SetMode(ActivityLogMode setMode)\r
         {\r
-            SetScanMode();\r
-            Thread monitor = new Thread(LogMonitor);\r
+            if (IsHandleCreated)\r
+            {\r
+                if (rtf_actLog.InvokeRequired)\r
+                {\r
+                    IAsyncResult invoked = BeginInvoke(new SetModeCallback(SetMode), new object[] { setMode });\r
+                    EndInvoke(invoked);\r
+                }\r
+                else\r
+                {\r
+                    Reset();\r
+                    this.mode = setMode;\r
+\r
+                    Array values = Enum.GetValues(typeof(ActivityLogMode));\r
+                    Properties.Settings.Default.ActivityWindowLastMode = (int)values.GetValue(Convert.ToInt32(setMode));\r
+                    Properties.Settings.Default.Save();\r
+\r
+                    this.Text = mode == ActivityLogMode.Scan\r
+                                    ? "Activity Window (Scan Log)"\r
+                                    : "Activity Window (Encode Log)";\r
+\r
+                    if (mode == ActivityLogMode.Scan)\r
+                    {\r
+                        scan.ScanCompleted += stopWindowRefresh;\r
+                        encode.EncodeEnded -= stopWindowRefresh;\r
+                    }\r
+                    else\r
+                    {\r
+                        scan.ScanCompleted -= stopWindowRefresh;\r
+                        encode.EncodeEnded += stopWindowRefresh;\r
+                    }\r
+\r
+                    // Start a fresh window timer\r
+                    windowTimer = new Timer(new TimerCallback(LogMonitor), null, 1000, 1000);\r
+                }\r
+            }\r
+        }\r
 \r
+        /// <summary>\r
+        /// On Window load, start a new timer\r
+        /// </summary>\r
+        /// <param name="sender">\r
+        /// The sender.\r
+        /// </param>\r
+        /// <param name="e">\r
+        /// The EventArgs.\r
+        /// </param>\r
+        private void ActivityWindowLoad(object sender, EventArgs e)\r
+        {\r
             try\r
             {\r
-                monitor.Start();\r
+                // Set the inital log file.\r
+                if (encode.IsEncoding)\r
+                {\r
+                    this.logSelector.SelectedIndex = 1;\r
+                }\r
+                else if (scan.IsScanning)\r
+                {\r
+                    this.logSelector.SelectedIndex = 0;\r
+                }\r
+                else\r
+                {\r
+                    // Otherwise, use the last mode the window was in.\r
+                    ActivityLogMode activitLogMode = (ActivityLogMode)Enum.ToObject(typeof(ActivityLogMode), Properties.Settings.Default.ActivityWindowLastMode);\r
+                    this.logSelector.SelectedIndex = activitLogMode == ActivityLogMode.Scan ? 0 : 1;\r
+                }\r
             }\r
             catch (Exception exc)\r
             {\r
-                MessageBox.Show(exc.ToString());\r
+                errorService.ShowError("Error during load.", exc.ToString());\r
             }\r
         }\r
 \r
-        private void LogMonitor()\r
+        /// <summary>\r
+        /// Set the Log window to encode mode when an encode starts.\r
+        /// </summary>\r
+        /// <param name="sender">\r
+        /// The sender.\r
+        /// </param>\r
+        /// <param name="e">\r
+        /// The e.\r
+        /// </param>\r
+        private void encode_EncodeStarted(object sender, EventArgs e)\r
         {\r
-            while (true)\r
-            {\r
-                // Perform a reset if require.\r
-                // If we have switched to a different log file, we want to start from the beginning.\r
-                if (SetLogFile != _lastMode)\r
-                {\r
-                    _position = 0;\r
-                    ClearWindowText();\r
-                }\r
+            SetMode(ActivityLogMode.Encode);\r
+        }\r
 \r
-                // Perform the window update\r
-                switch (SetLogFile)\r
-                {\r
-                    case "last_scan_log.txt":\r
-                        AppendWindowText(ReadFile("last_scan_log.txt"));\r
-                        _lastMode = "last_scan_log.txt";\r
-                        break;\r
-                    case "last_encode_log.txt":\r
-                        AppendWindowText(ReadFile("last_encode_log.txt"));\r
-                        _lastMode = "last_encode_log.txt";\r
-                        break;\r
-                }\r
+        /// <summary>\r
+        /// Set the log widow to scan mode when a scan starts\r
+        /// </summary>\r
+        /// <param name="sender">\r
+        /// The sender.\r
+        /// </param>\r
+        /// <param name="e">\r
+        /// The e.\r
+        /// </param>\r
+        private void scan_ScanStared(object sender, EventArgs e)\r
+        {\r
+            SetMode(ActivityLogMode.Scan);\r
+        }\r
 \r
-                Thread.Sleep(1000);\r
-            }\r
+        /// <summary>\r
+        /// Stop refreshing the window when no scanning or encoding is happening.\r
+        /// </summary>\r
+        /// <param name="sender">\r
+        /// The sender.\r
+        /// </param>\r
+        /// <param name="e">\r
+        /// The e.\r
+        /// </param>\r
+        private void stopWindowRefresh(object sender, EventArgs e)\r
+        {\r
+            windowTimer.Dispose();\r
+            Reset();\r
+            LogMonitor(null);\r
         }\r
-        private StringBuilder ReadFile(string file)\r
+\r
+        /// <summary>\r
+        /// Append new text to the window\r
+        /// </summary>\r
+        /// <param name="n">\r
+        /// The n.\r
+        /// </param>\r
+        private void LogMonitor(object n)\r
         {\r
-            StringBuilder appendText = new StringBuilder();\r
+            AppendWindowText(GetLog());\r
+        }\r
 \r
-            // last_encode_log.txt 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),\r
-            // we'll need to make a copy of it.\r
-            string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
-            string logFile = Path.Combine(logDir, file);\r
-            string logFile2 = Path.Combine(logDir, "tmp_appReadable_log.txt");\r
+        /// <summary>\r
+        /// New Code for getting the Activity log from the Services rather than reading a file.\r
+        /// </summary>\r
+        /// <returns>\r
+        /// The StringBuilder containing a log\r
+        /// </returns>\r
+        private StringBuilder GetLog()\r
+        {\r
+            StringBuilder appendText = new StringBuilder();\r
 \r
             try\r
             {\r
-                // Make sure the application readable log file does not already exist. FileCopy fill fail if it does.\r
-                if (File.Exists(logFile2))\r
-                    File.Delete(logFile2);\r
+                if (this.mode == ActivityLogMode.Scan)\r
+                {\r
+                    if (scan == null || scan.ActivityLog == string.Empty)\r
+                    {\r
+                        appendText.AppendFormat("Waiting for the log to be generated ...\n");\r
+                        position = 0;\r
+                        ClearWindowText();\r
+                        return appendText;\r
+                    }\r
 \r
-                // Copy the log file.\r
-                if (File.Exists(logFile))\r
-                    File.Copy(logFile, logFile2, true);\r
+                    using (StringReader reader = new StringReader(scan.ActivityLog))\r
+                    {\r
+                        LogReader(reader, appendText);\r
+                    }\r
+                }\r
                 else\r
                 {\r
-                    appendText.AppendFormat("Waiting for the log file to be generated ...\n");\r
-                    _position = 0;\r
-                    ClearWindowText();\r
-                    return appendText;\r
-                }\r
+                    if (encode == null || encode.ActivityLog == string.Empty)\r
+                    {\r
+                        appendText.AppendFormat("Waiting for the log to be generated ...\n");\r
+                        position = 0;\r
+                        ClearWindowText();\r
+                        return appendText;\r
+                    }\r
 \r
-                // Start the Reader\r
-                // Only use text which continues on from the last read line\r
-                StreamReader sr = new StreamReader(logFile2);\r
-                string line;\r
-                int i = 1;\r
-                while ((line = sr.ReadLine()) != null)\r
-                {\r
-                    if (i > _position)\r
+                    using (StringReader reader = new StringReader(encode.ActivityLog))\r
                     {\r
-                        appendText.AppendLine(line);\r
-                        _position++;\r
+                        LogReader(reader, appendText);\r
                     }\r
-                    i++;\r
                 }\r
-                sr.Close();\r
-                sr.Dispose();\r
-\r
             }\r
             catch (Exception exc)\r
             {\r
-                appendText.AppendFormat("\nERROR: The Log file could not be read. You may need to restart HandBrake! " + exc);\r
-                _position = 0;\r
-                ClearWindowText();\r
+                windowTimer.Dispose();\r
+                errorService.ShowError("GetLog() Error", exc.ToString());\r
             }\r
+\r
             return appendText;\r
         }\r
+\r
+        /// <summary>\r
+        /// Reads the log data from a Scan or Encode object\r
+        /// </summary>\r
+        /// <param name="reader">\r
+        /// The reader.\r
+        /// </param>\r
+        /// <param name="appendText">\r
+        /// The append text.\r
+        /// </param>\r
+        private void LogReader(StringReader reader, StringBuilder appendText)\r
+        {\r
+            string line;\r
+            int i = 1;\r
+            while ((line = reader.ReadLine()) != null)\r
+            {\r
+                if (i > position)\r
+                {\r
+                    appendText.AppendLine(line);\r
+                    position++;\r
+                }\r
+                i++;\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Append text to the RTF box\r
+        /// </summary>\r
+        /// <param name="text">\r
+        /// The text.\r
+        /// </param>\r
         private void AppendWindowText(StringBuilder text)\r
         {\r
             try\r
@@ -133,18 +331,29 @@ namespace Handbrake
                 {\r
                     if (rtf_actLog.InvokeRequired)\r
                     {\r
-                        IAsyncResult invoked = BeginInvoke(new setTextCallback(AppendWindowText), new object[] { text });\r
+                        IAsyncResult invoked = BeginInvoke(new SetTextCallback(AppendWindowText), new object[] { text });\r
                         EndInvoke(invoked);\r
                     }\r
                     else\r
-                        rtf_actLog.AppendText(text.ToString());\r
+                        lock (rtf_actLog)\r
+                            rtf_actLog.AppendText(text.ToString());\r
+\r
+                    // Stop the refresh process if log has finished.\r
+                    if (text.ToString().Contains("HandBrake has Exited"))\r
+                    {\r
+                        windowTimer.Dispose();\r
+                    }\r
                 }\r
             }\r
-            catch (Exception exc)\r
+            catch (Exception)\r
             {\r
-                MessageBox.Show("SetWindowText(): Exception: \n" + exc);\r
+                return;\r
             }\r
         }\r
+\r
+        /// <summary>\r
+        /// Clear the contents of the log window\r
+        /// </summary>\r
         private void ClearWindowText()\r
         {\r
             try\r
@@ -153,128 +362,115 @@ namespace Handbrake
                 {\r
                     if (rtf_actLog.InvokeRequired)\r
                     {\r
-                        IAsyncResult invoked = BeginInvoke(new setTextClearCallback(ClearWindowText));\r
+                        IAsyncResult invoked = BeginInvoke(new SetTextClearCallback(ClearWindowText));\r
                         EndInvoke(invoked);\r
                     }\r
                     else\r
-                        rtf_actLog.Clear();\r
+                        lock (rtf_actLog)\r
+                            rtf_actLog.Clear();\r
                 }\r
             }\r
-            catch (Exception exc)\r
+            catch (Exception)\r
             {\r
-                MessageBox.Show("ClearWindowText(): Exception: \n" + exc);\r
+                return;\r
             }\r
         }\r
 \r
-        public void PrintLogHeader()\r
+        /// <summary>\r
+        /// Reset Everything\r
+        /// </summary>\r
+        private void Reset()\r
         {\r
-            // Print the log header. This function will be re-implimented later. Do not delete.\r
-            rtf_actLog.AppendText(String.Format("### Windows GUI {1} {0} \n", Properties.Settings.Default.hb_build, Properties.Settings.Default.hb_version));\r
-            rtf_actLog.AppendText(String.Format("### Running: {0} \n###\n", Environment.OSVersion));\r
-            rtf_actLog.AppendText(String.Format("### CPU: {0} \n", getCpuCount()));\r
-            rtf_actLog.AppendText(String.Format("### Ram: {0} MB \n", TotalPhysicalMemory()));\r
-            rtf_actLog.AppendText(String.Format("### Screen: {0}x{1} \n", screenBounds().Bounds.Width, screenBounds().Bounds.Height));\r
-            rtf_actLog.AppendText(String.Format("### Temp Dir: {0} \n", Path.GetTempPath()));\r
-            rtf_actLog.AppendText(String.Format("### Install Dir: {0} \n", Application.StartupPath));\r
-            rtf_actLog.AppendText(String.Format("### Data Dir: {0} \n", Application.UserAppDataPath));\r
-            rtf_actLog.AppendText("#########################################\n\n");\r
+            if (windowTimer != null)\r
+                windowTimer.Dispose();\r
+            position = 0;\r
+            ClearWindowText();\r
+            windowTimer = new Timer(new TimerCallback(LogMonitor), null, 1000, 1000);\r
         }\r
 \r
-        #region Public\r
+        /* Menus and Buttons */\r
 \r
-        public string SetLogFile\r
-        {\r
-            get { return string.IsNullOrEmpty(_currentMode) ? "" : _currentMode; }\r
-            set { _currentMode = value; }\r
-        }\r
-        public void SetScanMode()\r
-        {\r
-            SetLogFile = "last_scan_log.txt";\r
-            this.Text = "Activity Window (Scan Log)";\r
-        }\r
-        public void SetEncodeMode()\r
+        /// <summary>\r
+        /// Copy log to clipboard\r
+        /// </summary>\r
+        /// <param name="sender">\r
+        /// The sender.\r
+        /// </param>\r
+        /// <param name="e">\r
+        /// The e.\r
+        /// </param>\r
+        private void MnuCopyLogClick(object sender, EventArgs e)\r
         {\r
-            SetLogFile = "last_encode_log.txt";\r
-            this.Text = "Activity Window (Enocde Log)";\r
+            Clipboard.SetDataObject(rtf_actLog.SelectedText != string.Empty ? rtf_actLog.SelectedText : rtf_actLog.Text, true);\r
         }\r
 \r
-        #endregion\r
-\r
-        #region User Interface\r
-        private void mnu_copy_log_Click(object sender, EventArgs e)\r
-        {\r
-            if (rtf_actLog.SelectedText != "")\r
-                Clipboard.SetDataObject(rtf_actLog.SelectedText, true);\r
-            else\r
-                Clipboard.SetDataObject(rtf_actLog.Text, true);\r
-        }\r
-        private void mnu_openLogFolder_Click(object sender, EventArgs e)\r
+        /// <summary>\r
+        /// Open the log folder\r
+        /// </summary>\r
+        /// <param name="sender">\r
+        /// The sender.\r
+        /// </param>\r
+        /// <param name="e">\r
+        /// The e.\r
+        /// </param>\r
+        private void MnuOpenLogFolderClick(object sender, EventArgs e)\r
         {\r
             string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
             string windir = Environment.GetEnvironmentVariable("WINDIR");\r
-            System.Diagnostics.Process prc = new System.Diagnostics.Process();\r
-            prc.StartInfo.FileName = windir + @"\explorer.exe";\r
-            prc.StartInfo.Arguments = logDir;\r
+            Process prc = new Process\r
+                              {\r
+                                  StartInfo =\r
+                                      {\r
+                                          FileName = windir + @"\explorer.exe",\r
+                                          Arguments = logDir\r
+                                      }\r
+                              };\r
             prc.Start();\r
         }\r
-        private void btn_copy_Click(object sender, EventArgs e)\r
-        {\r
-            if (rtf_actLog.SelectedText != "")\r
-                Clipboard.SetDataObject(rtf_actLog.SelectedText, true);\r
-            else\r
-                Clipboard.SetDataObject(rtf_actLog.Text, true);\r
-        }\r
-        private void btn_scan_log_Click(object sender, EventArgs e)\r
-        {\r
-            SetScanMode();\r
-        }\r
-        private void btn_encode_log_Click(object sender, EventArgs e)\r
-        {\r
-            SetEncodeMode();\r
-        }\r
-        #endregion\r
 \r
-        #region System Information\r
         /// <summary>\r
-        /// Returns the total physical ram in a system\r
+        /// Copy the log\r
         /// </summary>\r
-        /// <returns></returns>\r
-        public uint TotalPhysicalMemory()\r
+        /// <param name="sender">\r
+        /// The sender.\r
+        /// </param>\r
+        /// <param name="e">\r
+        /// The e.\r
+        /// </param>\r
+        private void BtnCopyClick(object sender, EventArgs e)\r
         {\r
-            Win32.MEMORYSTATUS memStatus = new Win32.MEMORYSTATUS();\r
-            Win32.GlobalMemoryStatus(ref memStatus);\r
-\r
-            uint MemoryInfo = memStatus.dwTotalPhys;\r
-            MemoryInfo = MemoryInfo / 1024 / 1024;\r
-\r
-            return MemoryInfo;\r
+            Clipboard.SetDataObject(rtf_actLog.SelectedText != string.Empty ? rtf_actLog.SelectedText : rtf_actLog.Text, true);\r
         }\r
 \r
         /// <summary>\r
-        /// Get the number of CPU Cores\r
+        /// Change the Log file in the viewer\r
         /// </summary>\r
-        /// <returns>Object</returns>\r
-        public Object getCpuCount()\r
+        /// <param name="sender">The Sender </param>\r
+        /// <param name="e">The EventArgs</param>\r
+        private void LogSelectorClick(object sender, EventArgs e)\r
         {\r
-            RegistryKey RegKey = Registry.LocalMachine;\r
-            RegKey = RegKey.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0");\r
-            return RegKey.GetValue("ProcessorNameString");\r
+            this.SetMode((string)this.logSelector.SelectedItem == "Scan Log" ? ActivityLogMode.Scan : ActivityLogMode.Encode);\r
         }\r
 \r
+        /* Overrides */\r
+\r
         /// <summary>\r
-        /// Get the System screen size information.\r
+        /// override onclosing\r
         /// </summary>\r
-        /// <returns>System.Windows.Forms.Scree</returns>\r
-        public Screen screenBounds()\r
-        {\r
-            return Screen.PrimaryScreen;\r
-        }\r
-        #endregion\r
-\r
+        /// <param name="e">\r
+        /// The e.\r
+        /// </param>\r
         protected override void OnClosing(CancelEventArgs e)\r
         {\r
+            scan.ScanStared -= scan_ScanStared;\r
+            encode.EncodeStarted -= encode_EncodeStarted;\r
+\r
+            scan.ScanCompleted -= stopWindowRefresh;\r
+            encode.EncodeEnded -= stopWindowRefresh;\r
+\r
+            windowTimer.Dispose();\r
             e.Cancel = true;\r
-            this.Hide();\r
+            this.Dispose();\r
             base.OnClosing(e);\r
         }\r
     }\r