OSDN Git Service

WinGui:
[handbrake-jp/handbrake-jp-git.git] / win / C# / EncodeQueue / Encode.cs
1 /*  Encode.cs $\r
2         \r
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
6 \r
7 using System;\r
8 using System.Diagnostics;\r
9 using System.IO;\r
10 using System.Windows.Forms;\r
11 using Handbrake.Functions;\r
12 \r
13 namespace Handbrake.EncodeQueue\r
14 {\r
15     public class Encode\r
16     {\r
17         public Process HbProcess { get; set; }\r
18         public int ProcessID { get; set; }\r
19         public IntPtr ProcessHandle { get; set; }\r
20         public String CurrentQuery { get; set; }\r
21         public Boolean IsEncoding { get; set; }\r
22 \r
23         public event EventHandler EncodeStarted;\r
24         public event EventHandler EncodeEnded;\r
25 \r
26         /// <summary>\r
27         /// Create a preview sample video\r
28         /// </summary>\r
29         /// <param name="query"></param>\r
30         public void CreatePreviewSampe(string query)\r
31         {\r
32             Run(query);\r
33         }\r
34 \r
35         /// <summary>\r
36         /// Execute a HandBrakeCLI process.\r
37         /// </summary>\r
38         /// <param name="query">The CLI Query</param>\r
39         protected void Run(string query)\r
40         {\r
41             try\r
42             {\r
43                 if (EncodeStarted != null)\r
44                     EncodeStarted(this, new EventArgs());\r
45 \r
46                 IsEncoding = true;\r
47 \r
48                 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");\r
49                 string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs", "last_encode_log.txt");\r
50                 string strCmdLine = String.Format(@" /C """"{0}"" {1} 2>""{2}"" """, handbrakeCLIPath, query, logPath);\r
51                 ProcessStartInfo cliStart = new ProcessStartInfo("CMD.exe", strCmdLine);\r
52 \r
53                 if (Properties.Settings.Default.enocdeStatusInGui)\r
54                 {\r
55                     cliStart.RedirectStandardOutput = true;\r
56                     cliStart.UseShellExecute = false;\r
57                     if (!Properties.Settings.Default.showCliForInGuiEncodeStatus)\r
58                         cliStart.CreateNoWindow = true;\r
59                 }\r
60                 if (Properties.Settings.Default.cli_minimized)\r
61                     cliStart.WindowStyle = ProcessWindowStyle.Minimized;\r
62 \r
63                 Process[] before = Process.GetProcesses(); // Get a list of running processes before starting.\r
64                 HbProcess = Process.Start(cliStart);\r
65                 ProcessID = Main.GetCliProcess(before);\r
66                 CurrentQuery = query;\r
67                 if (HbProcess != null)\r
68                     ProcessHandle = HbProcess.MainWindowHandle; // Set the process Handle\r
69 \r
70                 // Set the process Priority\r
71                 Process hbCliProcess = null;\r
72                 if (ProcessID != -1)\r
73                     hbCliProcess = Process.GetProcessById(ProcessID);\r
74 \r
75                 if (hbCliProcess != null)\r
76                     switch (Properties.Settings.Default.processPriority)\r
77                     {\r
78                         case "Realtime":\r
79                             hbCliProcess.PriorityClass = ProcessPriorityClass.RealTime;\r
80                             break;\r
81                         case "High":\r
82                             hbCliProcess.PriorityClass = ProcessPriorityClass.High;\r
83                             break;\r
84                         case "Above Normal":\r
85                             hbCliProcess.PriorityClass = ProcessPriorityClass.AboveNormal;\r
86                             break;\r
87                         case "Normal":\r
88                             hbCliProcess.PriorityClass = ProcessPriorityClass.Normal;\r
89                             break;\r
90                         case "Low":\r
91                             hbCliProcess.PriorityClass = ProcessPriorityClass.Idle;\r
92                             break;\r
93                         default:\r
94                             hbCliProcess.PriorityClass = ProcessPriorityClass.BelowNormal;\r
95                             break;\r
96                     }\r
97             }\r
98             catch (Exception exc)\r
99             {\r
100                 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
101             }\r
102         }\r
103 \r
104         /// <summary>\r
105         /// Kill the CLI process\r
106         /// </summary>\r
107         public void Stop()\r
108         {\r
109             if (HbProcess != null)\r
110                 HbProcess.Kill();\r
111 \r
112             Process[] list = Process.GetProcessesByName("HandBrakeCLI");\r
113             foreach (Process process in list)\r
114                     process.Kill();\r
115 \r
116             IsEncoding = false;\r
117 \r
118             if (EncodeEnded != null)\r
119                 EncodeEnded(this, new EventArgs());\r
120         }\r
121 \r
122         /// <summary>\r
123         /// Perform an action after an encode. e.g a shutdown, standby, restart etc.\r
124         /// </summary>\r
125         protected void Finish()\r
126         {\r
127             IsEncoding = false;\r
128             CurrentQuery = String.Empty;\r
129 \r
130             //Growl\r
131             if (Properties.Settings.Default.growlQueue)\r
132                 GrowlCommunicator.Notify("Queue Completed", "Put down that cocktail...\nyour Handbrake queue is done.");\r
133 \r
134             // Do something whent he encode ends.\r
135             switch (Properties.Settings.Default.CompletionOption)\r
136             {\r
137                 case "Shutdown":\r
138                     Process.Start("Shutdown", "-s -t 60");\r
139                     break;\r
140                 case "Log Off":\r
141                     Win32.ExitWindowsEx(0, 0);\r
142                     break;\r
143                 case "Suspend":\r
144                     Application.SetSuspendState(PowerState.Suspend, true, true);\r
145                     break;\r
146                 case "Hibernate":\r
147                     Application.SetSuspendState(PowerState.Hibernate, true, true);\r
148                     break;\r
149                 case "Lock System":\r
150                     Win32.LockWorkStation();\r
151                     break;\r
152                 case "Quit HandBrake":\r
153                     Application.Exit();\r
154                     break;\r
155                 default:\r
156                     break;\r
157             }\r
158         }\r
159 \r
160         /// <summary>\r
161         /// Add the CLI Query to the Log File.\r
162         /// </summary>\r
163         /// <param name="encJob"></param>\r
164         protected void AddCLIQueryToLog(Job encJob)\r
165         {\r
166             try\r
167             {\r
168                 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +\r
169                                 "\\HandBrake\\logs";\r
170                 string logPath = Path.Combine(logDir, "last_encode_log.txt");\r
171 \r
172                 StreamReader reader =\r
173                     new StreamReader(File.Open(logPath, FileMode.Open, FileAccess.Read, FileShare.Read));\r
174                 String log = reader.ReadToEnd();\r
175                 reader.Close();\r
176 \r
177                 StreamWriter writer = new StreamWriter(File.Create(logPath));\r
178 \r
179                 writer.Write("### CLI Query: " + encJob.Query + "\n\n");\r
180                 writer.Write("### User Query: " + encJob.CustomQuery + "\n\n");\r
181                 writer.Write("#########################################\n\n");\r
182                 writer.WriteLine(log);\r
183                 writer.Flush();\r
184                 writer.Close();\r
185             } catch (Exception exc)\r
186             {\r
187              \r
188             }\r
189         }\r
190 \r
191         /// <summary>\r
192         /// Save a copy of the log to the users desired location or a default location\r
193         /// if this feature is enabled in options.\r
194         /// </summary>\r
195         /// <param name="destination"></param>\r
196         protected void CopyLog(string destination)\r
197         {\r
198             try\r
199             {\r
200                 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
201                 string tempLogFile = Path.Combine(logDir, "last_encode_log.txt");\r
202 \r
203                 string encodeDestinationPath = Path.GetDirectoryName(destination);\r
204                 String destinationFile = Path.GetFileName(destination);\r
205                 string encodeLogFile = destinationFile + " " + DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";\r
206 \r
207                 // Make sure the log directory exists.\r
208                 if (!Directory.Exists(logDir))\r
209                     Directory.CreateDirectory(logDir);\r
210 \r
211                 // Copy the Log to HandBrakes log folder in the users applciation data folder.\r
212                 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));\r
213 \r
214                 // Save a copy of the log file in the same location as the enocde.\r
215                 if (Properties.Settings.Default.saveLogWithVideo)\r
216                     File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));\r
217 \r
218                 // Save a copy of the log file to a user specified location\r
219                 if (Directory.Exists(Properties.Settings.Default.saveLogPath))\r
220                     if (Properties.Settings.Default.saveLogPath != String.Empty && Properties.Settings.Default.saveLogToSpecifiedPath)\r
221                         File.Copy(tempLogFile, Path.Combine(Properties.Settings.Default.saveLogPath, encodeLogFile));\r
222             }\r
223             catch (Exception exc)\r
224             {\r
225                 MessageBox.Show("Something went a bit wrong trying to copy your log file.\nError Information:\n\n" + exc, "Error",\r
226                                 MessageBoxButtons.OK, MessageBoxIcon.Error);\r
227             }\r
228         }\r
229     }\r
230 }