OSDN Git Service

merge 0.9.4 to jp
[handbrake-jp/handbrake-jp.git] / win / C# / frmActivityWindow.cs
index 5bd5c59..b2655f9 100644 (file)
           It may be used under the terms of the GNU General Public License. */\r
 \r
 using System;\r
-using System.Collections;\r
-using System.Collections.Generic;\r
 using System.ComponentModel;\r
-using System.Data;\r
-using System.Drawing;\r
-using System.Text;\r
 using System.Windows.Forms;\r
 using System.IO;\r
 using System.Threading;\r
-using System.Diagnostics;\r
-using System.Runtime.InteropServices;\r
+using Handbrake.EncodeQueue;\r
+using Handbrake.Functions;\r
+using Microsoft.Win32;\r
 \r
 \r
 namespace Handbrake\r
 {\r
     public partial class frmActivityWindow : Form\r
     {\r
-        delegate void SetTextCallback(string text);\r
-        String read_file;\r
-        Thread monitor;\r
-        frmMain mainWindow;\r
-        frmQueue queueWindow;\r
-        int position = 0;  // Position in the arraylist reached by the current log output in the rtf box.\r
-\r
-        /// <summary>\r
-        /// This window should be used to display the RAW output of the handbrake CLI which is produced during an encode.\r
-        /// </summary>\r
-        public frmActivityWindow(string file, frmMain fm, frmQueue fq)\r
+        private delegate void setTextCallback(string text);\r
+        private String _readFile;\r
+        private readonly EncodeAndQueueHandler _encodeQueue;\r
+        private int _position;  // Position in the arraylist reached by the current log output in the rtf box.\r
+        private readonly frmMain _mainWin;\r
+        private Boolean _lastUpdate;\r
+        private Boolean fileNotFoundQuickFix;\r
+\r
+        public frmActivityWindow(string file, EncodeAndQueueHandler eh, frmMain mw)\r
         {\r
             InitializeComponent();\r
-            this.rtf_actLog.Text = string.Empty;\r
 \r
-            // When the window closes, we want to abort the monitor thread.\r
-            this.Disposed += new EventHandler(forceQuit);\r
+            _encodeQueue = eh;\r
+            _mainWin = mw;\r
 \r
-            mainWindow = fm;\r
-            queueWindow = fq;\r
-            read_file = file;\r
-            position = 0;\r
-\r
-            // Print the Log header in the Rich text box.\r
-            displayLogHeader();\r
+            fileNotFoundQuickFix = false;\r
 \r
+/*\r
             if (file == "dvdinfo.dat")\r
                 txt_log.Text = "\83X\83L\83\83\83\93\83\8d\83O";\r
             else if (file == "hb_encode_log.dat")\r
                 txt_log.Text = "\83G\83\93\83R\81[\83h\83\8d\83O";\r
+*/\r
+            if (file == "last_scan_log.txt")\r
+                SetLogView(true);\r
+            else\r
+                SetLogView(false);\r
 \r
             // Start a new thread which will montior and keep the log window up to date if required/\r
-            startLogThread(read_file);            \r
+            try\r
+            {\r
+                Thread monitor = new Thread(AutoUpdate) { IsBackground = true };\r
+                monitor.Start();\r
+            }\r
+            catch (Exception exc)\r
+            {\r
+                MessageBox.Show("startLogThread(): Exception: \n" + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
+            }\r
         }\r
 \r
         /// <summary>\r
-        /// Displays the Log header\r
+        /// Set the view which the Log window displays.\r
+        /// Scan = true;\r
+        /// Encode = false;\r
         /// </summary>\r
-        private void displayLogHeader()\r
+        /// <param name="scan">Boolean. Scan = true</param>\r
+        public void SetLogView(Boolean scan)\r
         {\r
-            // System Information\r
-            Functions.SystemInfo info = new Functions.SystemInfo();\r
+            // Reset\r
+            _position = 0;\r
+            rtf_actLog.Text = String.Empty;\r
 \r
-            // Add a header to the log file indicating that it's from the Windows GUI and display the windows version\r
+            // Print the log header\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.ToString()));\r
-            rtf_actLog.AppendText(String.Format("### CPU: {0} \n", info.getCpuCount()));\r
-            rtf_actLog.AppendText(String.Format("### Ram: {0} MB \n", info.TotalPhysicalMemory()));\r
-            rtf_actLog.AppendText(String.Format("### Screen: {0}x{1} \n", info.screenBounds().Bounds.Width, info.screenBounds().Bounds.Height));\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
-        }\r
 \r
-        /// <summary>\r
-        /// Starts a new thread which runs the autoUpdate function.\r
-        /// </summary>\r
-        /// <param name="file"> File which will be used to populate the Rich text box.</param>\r
-        private void startLogThread(string file)\r
-        {\r
-            try\r
+            // Seutp the log file\r
+            if (scan)\r
             {\r
-                string logFile = Path.Combine(Path.GetTempPath(), file);\r
-                if (File.Exists(logFile))\r
-                {\r
-                    // Start a new thread to run the autoUpdate process\r
-                    monitor = new Thread(autoUpdate);\r
-                    monitor.IsBackground = true;\r
-                    monitor.Start();\r
-                }\r
-                else\r
-                    rtf_actLog.AppendText("\n\n\nERROR: The log file could not be found. \nMaybe you cleared your system's tempory folder or maybe you just havn't run an encode yet. \nTried to find the log file in: " + logFile);\r
-\r
+                txt_log.Text = "Scan Log";\r
+                _readFile = "last_scan_log.txt";\r
             }\r
-            catch (Exception exc)\r
+            else\r
             {\r
-                MessageBox.Show("startLogThread(): Exception: \n" + exc);\r
+                _readFile = "last_encode_log.txt";\r
+                txt_log.Text = "Encode Log";\r
+                if (_encodeQueue.isEncoding)\r
+                    if ((!_encodeQueue.LastEncode.IsEmpty) && _encodeQueue.LastEncode.Query != String.Empty)\r
+                    {\r
+                        rtf_actLog.AppendText("### CLI Query: " + _encodeQueue.LastEncode.Query + "\n");\r
+                        rtf_actLog.AppendText("### Custom Query: " + _encodeQueue.LastEncode.CustomQuery + "\n\n");\r
+                        rtf_actLog.AppendText("#########################################\n\n");\r
+                    }\r
             }\r
+            _lastUpdate = false;\r
         }\r
 \r
+/*\r
         /// <summary>\r
         /// Change the log file to be displayed to hb_encode_log.dat\r
         /// </summary>\r
@@ -157,85 +157,65 @@ namespace Handbrake
         /// </summary>\r
         /// <param name="state"></param>\r
         private void autoUpdate(object state)\r
+*/\r
+        private void AutoUpdate(object state)\r
         {\r
             try\r
             {\r
-                Boolean lastUpdate = false;\r
-                updateTextFromThread();\r
+                _lastUpdate = false;\r
+                UpdateTextFromThread();\r
                 while (true)\r
                 {\r
-                    if ((mainWindow.isEncoding() == true) || (queueWindow.isEncoding() == true))\r
-                        updateTextFromThread();\r
-                    else\r
+                    if (IsHandleCreated)\r
                     {\r
-                        // The encode may just have stoped, so, refresh the log one more time before restarting it.\r
-                        if (lastUpdate == false)\r
-                            updateTextFromThread();\r
-\r
-                        lastUpdate = true; // Prevents the log window from being updated when there is no encode going.\r
-                        position = 0; // There is no encoding, so reset the log position counter to 0 so it can be reused\r
+                        if (_encodeQueue.isEncoding || _mainWin.isScanning)\r
+                            UpdateTextFromThread();\r
+                        else\r
+                        {\r
+                            // The encode may just have stoped, so, refresh the log one more time before restarting it.\r
+                            if (_lastUpdate == false)\r
+                                UpdateTextFromThread();\r
+\r
+                            _lastUpdate = true; // Prevents the log window from being updated when there is no encode going.\r
+                            _position = 0; // There is no encoding, so reset the log position counter to 0 so it can be reused\r
+                        }\r
                     }\r
-                    Thread.Sleep(5000);\r
+                    Thread.Sleep(1000);\r
                 }\r
             }\r
-            catch (ThreadAbortException)\r
-            {\r
-                // Do Nothing. This is needed since we run thread.abort(). \r
-                // Should probably find a better way of making this work at some point.\r
-            }\r
             catch (Exception exc)\r
             {\r
-                MessageBox.Show("autoUpdate(): Exception: \n" + exc);\r
+                MessageBox.Show("AutoUpdate(): Exception: \n" + exc);\r
             }\r
         }\r
-\r
-        /// <summary>\r
-        /// Finds any new text in the log file and calls a funciton to display this new text.\r
-        /// </summary>\r
-        private void updateTextFromThread()\r
+        private void UpdateTextFromThread()\r
         {\r
             try\r
             {\r
-                string text = "";\r
-                List<string> data = readFile();\r
-                int count = data.Count;\r
-\r
-                while (position < count)\r
-                {\r
-                    text = data[position].ToString();\r
-                    if (data[position].ToString().Contains("has exited"))\r
-                        text = "\n ############ End of Log ############## \n";\r
-                    position++;\r
+                String info = ReadFile();\r
+                if (info.Contains("has exited"))\r
+                    info += "\n ############ End of Log ############## \n";\r
 \r
-                    SetText(text);\r
-                }\r
+                SetText(info);\r
             }\r
             catch (Exception exc)\r
             {\r
-                MessageBox.Show("updateTextFromThread(): Exception: \n" + exc);\r
+                MessageBox.Show("UpdateTextFromThread(): Exception: \n" + exc);\r
             }\r
         }\r
-\r
-        /// <summary>\r
-        /// Updates the rich text box with anything in the string text.\r
-        /// </summary>\r
-        /// <param name="text"></param>\r
         private void SetText(string text)\r
         {\r
             try\r
             {\r
-                // InvokeRequired required compares the thread ID of the\r
-                // calling thread to the thread ID of the creating thread.\r
-                // If these threads are different, it returns true.\r
-                if (this.IsHandleCreated) // Make sure the windows has a handle before doing anything\r
+                if (IsHandleCreated)\r
                 {\r
-                    if (this.rtf_actLog.InvokeRequired)\r
+                    if (rtf_actLog.InvokeRequired)\r
                     {\r
-                        SetTextCallback d = new SetTextCallback(SetText);\r
-                        this.Invoke(d, new object[] { text });\r
+                        IAsyncResult invoked = BeginInvoke(new setTextCallback(SetText), new object[] { text });\r
+                        EndInvoke(invoked);\r
                     }\r
                     else\r
-                        this.rtf_actLog.AppendText(text);\r
+                        rtf_actLog.AppendText(text);\r
                 }\r
             }\r
             catch (Exception exc)\r
@@ -243,75 +223,132 @@ namespace Handbrake
                 MessageBox.Show("SetText(): Exception: \n" + exc);\r
             }\r
         }\r
-\r
-        /// <summary>\r
-        /// Read the log file, and store the data in a List.\r
-        /// </summary>\r
-        /// <returns></returns>\r
-        private List<string> readFile()\r
+        private String ReadFile()\r
         {\r
-            // Ok, the task here is to, Get an arraylist of log data.\r
-            // And update some global varibles which are pointers to the last displayed log line.\r
-            List<string> logData = new List<string>();\r
-\r
+            String appendText = String.Empty;\r
             try\r
             {\r
-                // 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),\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 logFile = Path.Combine(Path.GetTempPath(), read_file);\r
-                string logFile2 = Path.Combine(Path.GetTempPath(), "hb_encode_log_AppReadable.dat");\r
+                string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
+                string logFile = Path.Combine(logDir, _readFile);\r
+                string logFile2 = Path.Combine(logDir, "tmp_appReadable_log.txt");\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
 \r
                 // Copy the log file.\r
-                File.Copy(logFile, logFile2);\r
+                if (File.Exists(logFile))\r
+                    File.Copy(logFile, logFile2, true);\r
+                else\r
+                {\r
+                    if (fileNotFoundQuickFix)\r
+                        return "";\r
+                    fileNotFoundQuickFix = true;\r
+                    return "\n\n\nERROR: The log file could not be found. \nMaybe you cleared your system's tempory folder or maybe you just havn't run an encode yet. \nTried to find the log file in: " + logFile;\r
+                }\r
 \r
-                // Open the copied log file for reading\r
                 StreamReader sr = new StreamReader(logFile2);\r
-                string line = sr.ReadLine();\r
-                while (line != null)\r
+                string line;\r
+                int i = 1;\r
+                while ((line = sr.ReadLine()) != null)\r
                 {\r
-                    if (line.Trim() != "")\r
-                        logData.Add(line + System.Environment.NewLine);\r
-\r
-                    line = sr.ReadLine();\r
+                    if (i > _position)\r
+                    {\r
+                        appendText += line + Environment.NewLine;\r
+                        _position++;\r
+                    }\r
+                    i++;\r
                 }\r
                 sr.Close();\r
                 sr.Dispose();\r
 \r
-                return logData;\r
+                return appendText;\r
             }\r
             catch (Exception exc)\r
             {\r
-                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);\r
+                return "Error in ReadFile() \n Unable to read the log file.\n You may have to restart HandBrake. Will try reading the file again in a few seconds... \n  Error Information: \n\n" + exc;\r
             }\r
-            return null;\r
         }\r
 \r
-        /// <summary>\r
-        /// Kills the montior thead when the window is disposed of.\r
-        /// </summary>\r
-        /// <param name="sender"></param>\r
-        /// <param name="e"></param>\r
-        private void forceQuit(object sender, EventArgs e)\r
+        protected override void OnClosing(CancelEventArgs e)\r
         {\r
-            if (monitor != null)\r
-            {\r
-                while (monitor.IsAlive)\r
-                    monitor.Abort();\r
-            }\r
-\r
-            this.Close();\r
+            e.Cancel = true;\r
+            this.Hide();\r
+            base.OnClosing(e);\r
         }\r
 \r
-        private void copyToolStripMenuItem_Click(object sender, EventArgs e)\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
+        {\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
+            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
+            SetLogView(true);\r
+        }\r
+        private void btn_encode_log_Click(object sender, EventArgs e)\r
+        {\r
+            SetLogView(false);\r
+        }\r
+        #endregion\r
+\r
+        #region System Information\r
+        /// <summary>\r
+        /// Returns the total physical ram in a system\r
+        /// </summary>\r
+        /// <returns></returns>\r
+        public uint TotalPhysicalMemory()\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
+        }\r
+\r
+        /// <summary>\r
+        /// Get the number of CPU Cores\r
+        /// </summary>\r
+        /// <returns>Object</returns>\r
+        public Object getCpuCount()\r
+        {\r
+            RegistryKey RegKey = Registry.LocalMachine;\r
+            RegKey = RegKey.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0");\r
+            return RegKey.GetValue("ProcessorNameString");\r
+        }\r
+\r
+        /// <summary>\r
+        /// Get the System screen size information.\r
+        /// </summary>\r
+        /// <returns>System.Windows.Forms.Scree</returns>\r
+        public Screen screenBounds()\r
+        {\r
+            return Screen.PrimaryScreen;\r
+        }\r
+        #endregion\r
+\r
     }\r
 }
\ No newline at end of file