OSDN Git Service

f34de0190049f151c8fe90488d3a0e1cec0069e4
[handbrake-jp/handbrake-jp-git.git] / win / C# / EncodeQueue / QueueHandler.cs
1 /*  QueueHandler.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.Collections.Generic;\r
9 using System.IO;\r
10 using System.Windows.Forms;\r
11 using System.Xml.Serialization;\r
12 using System.Threading;\r
13 using System.Diagnostics;\r
14 \r
15 namespace Handbrake.EncodeQueue\r
16 {\r
17     public class QueueHandler\r
18     {\r
19         Encode encodeHandler = new Encode();\r
20         private static XmlSerializer ser = new XmlSerializer(typeof(List<QueueItem>));\r
21         List<QueueItem> queue = new List<QueueItem>();\r
22         int id; // Unique identifer number for each job\r
23 \r
24         #region Queue Handling\r
25         public List<QueueItem> getQueue()\r
26         {\r
27             return queue;\r
28         }\r
29 \r
30         /// <summary>\r
31         /// Get's the next CLI query for encoding\r
32         /// </summary>\r
33         /// <returns>String</returns>\r
34         private string getNextItemForEncoding()\r
35         {\r
36             QueueItem job = queue[0];\r
37             String query = job.Query;\r
38             lastQueueItem = job;\r
39             remove(0);    // Remove the item which we are about to pass out.\r
40             return query;\r
41         }\r
42 \r
43         /// <summary>\r
44         /// Get the last query that was returned by getNextItemForEncoding()\r
45         /// </summary>\r
46         /// <returns></returns>\r
47         public QueueItem lastQueueItem { get; set; }\r
48 \r
49         /// <summary>\r
50         /// Add's a new item to the queue\r
51         /// </summary>\r
52         /// <param name="query">String</param>\r
53         /// <param name="source"></param>\r
54         /// <param name="destination"></param>\r
55         public void add(string query, string source, string destination)\r
56         {\r
57             QueueItem newJob = new QueueItem { Id = id, Query = query, Source = source, Destination = destination };\r
58             id++;\r
59 \r
60             queue.Add(newJob);\r
61         }\r
62 \r
63         /// <summary>\r
64         /// Check to see if a destination path is already on the queue\r
65         /// </summary>\r
66         /// <param name="destination">Destination path</param>\r
67         /// <returns>Boolean True/False. True = Path Exists</returns>\r
68         public Boolean checkDestinationPath(string destination)\r
69         {\r
70             foreach (QueueItem checkItem in queue)\r
71             {\r
72                 if (checkItem.Destination.Contains(destination.Replace("\\\\", "\\")))\r
73                     return true;\r
74             }\r
75             return false;\r
76         }\r
77 \r
78         /// <summary>\r
79         /// Removes an item from the queue.\r
80         /// </summary>\r
81         /// <param name="index">Index</param>\r
82         /// <returns>Bolean true if successful</returns>\r
83         public void remove(int index)\r
84         {\r
85             queue.RemoveAt(index);\r
86         }\r
87 \r
88         /// <summary>\r
89         /// Returns how many items are in the queue\r
90         /// </summary>\r
91         /// <returns>Int</returns>\r
92         public int count()\r
93         {\r
94             return queue.Count;\r
95         }\r
96 \r
97         /// <summary>\r
98         /// Move an item with an index x, up in the queue\r
99         /// </summary>\r
100         /// <param name="index">Int</param>\r
101         public void moveUp(int index)\r
102         {\r
103             if (index > 0)\r
104             {\r
105                 QueueItem item = queue[index];\r
106 \r
107                 queue.RemoveAt(index);\r
108                 queue.Insert((index - 1), item);\r
109             }\r
110         }\r
111 \r
112         /// <summary>\r
113         /// Move an item with an index x, down in the queue\r
114         /// </summary>\r
115         /// <param name="index">Int</param>\r
116         public void moveDown(int index)\r
117         {\r
118             if (index < queue.Count - 1)\r
119             {\r
120                 QueueItem item = queue[index];\r
121 \r
122                 queue.RemoveAt(index);\r
123                 queue.Insert((index + 1), item);\r
124             }\r
125         }\r
126 \r
127         /// <summary>\r
128         /// Writes the current queue to disk. hb_queue_recovery.xml\r
129         /// This function is called after getNextItemForEncoding()\r
130         /// </summary>\r
131         public void write2disk(string file)\r
132         {\r
133             string tempPath = file == "hb_queue_recovery.xml" ? Path.Combine(Path.GetTempPath(), "hb_queue_recovery.xml") : file;\r
134 \r
135             try\r
136             {\r
137                 using (FileStream strm = new FileStream(tempPath, FileMode.Create, FileAccess.Write))\r
138                 {\r
139                     ser.Serialize(strm, queue);\r
140                     strm.Close();\r
141                     strm.Dispose();\r
142                 }\r
143             }\r
144             catch (Exception)\r
145             {\r
146                 // Any Errors will be out of diskspace/permissions problems. \r
147                 // Don't report them as they'll annoy the user.\r
148             }\r
149         }\r
150 \r
151         /// <summary>\r
152         /// Writes the current queue to disk to the location specified in file\r
153         /// </summary>\r
154         /// <param name="file"></param>\r
155         public void writeBatchScript(string file)\r
156         {\r
157             string queries = "";\r
158             foreach (QueueItem queue_item in queue)\r
159             {\r
160                 string q_item = queue_item.Query;\r
161                 string fullQuery = '"' + Application.StartupPath + "\\HandBrakeCLI.exe" + '"' + q_item;\r
162 \r
163                 if (queries == string.Empty)\r
164                     queries = queries + fullQuery;\r
165                 else\r
166                     queries = queries + " && " + fullQuery;\r
167             }\r
168             string strCmdLine = queries;\r
169 \r
170             if (file != "")\r
171             {\r
172                 try\r
173                 {\r
174                     // Create a StreamWriter and open the file, Write the batch file query to the file and \r
175                     // Close the stream\r
176                     StreamWriter line = new StreamWriter(file);\r
177                     line.WriteLine(strCmdLine);\r
178                     line.Close();\r
179 \r
180                     MessageBox.Show("Your batch script has been sucessfully saved.", "Status", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);\r
181                 }\r
182                 catch (Exception)\r
183                 {\r
184                     MessageBox.Show("Unable to write to the file. Please make sure that the location has the correct permissions for file writing.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);\r
185                 }\r
186 \r
187             }\r
188         }\r
189 \r
190         /// <summary>\r
191         /// Recover the queue from hb_queue_recovery.xml\r
192         /// </summary>\r
193         public void recoverQueue(string file)\r
194         {\r
195             string tempPath;\r
196             if (file == "hb_queue_recovery.xml")\r
197                 tempPath = Path.Combine(Path.GetTempPath(), "hb_queue_recovery.xml");\r
198             else\r
199                 tempPath = file;\r
200 \r
201             if (File.Exists(tempPath))\r
202             {\r
203                 using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))\r
204                 {\r
205                     if (strm.Length != 0)\r
206                     {\r
207                         List<QueueItem> list = ser.Deserialize(strm) as List<QueueItem>;\r
208 \r
209                         if (list != null)\r
210                             foreach (QueueItem item in list)\r
211                                 queue.Add(item);\r
212 \r
213                         if (file != "hb_queue_recovery.xml")\r
214                             write2disk("hb_queue_recovery.xml");\r
215                     }\r
216                 }\r
217             }\r
218         }\r
219         #endregion\r
220 \r
221         #region Encoding\r
222 \r
223         public Boolean isEncodeStarted { get; private set; }\r
224         public Boolean isPaused { get; private set; }\r
225         public Boolean isEncoding { get; private set; }\r
226         public EncodeProcess encodeProcess { get; set; }\r
227 \r
228         public void startEncode()\r
229         { \r
230             Thread theQueue;\r
231             if (this.count() != 0)\r
232             {\r
233                 if (isPaused)\r
234                     isPaused = false;\r
235                 else\r
236                 {\r
237                     isPaused = false;\r
238                     try\r
239                     {\r
240                         theQueue = new Thread(startProc) { IsBackground = true };\r
241                         theQueue.Start();\r
242                     }\r
243                     catch (Exception exc)\r
244                     {\r
245                         MessageBox.Show(exc.ToString());\r
246                     }\r
247                 }\r
248             }\r
249         }\r
250         public void pauseEncodeQueue()\r
251         {\r
252             isPaused = true;\r
253             EncodePaused(null);\r
254         }\r
255         public void endEncode()\r
256         {\r
257             encodeHandler.closeCLI(encodeProcess);\r
258         }\r
259 \r
260         private void startProc(object state)\r
261         {\r
262             try\r
263             {\r
264                 // Run through each item on the queue\r
265                 while (this.count() != 0)\r
266                 {\r
267                     string query = getNextItemForEncoding();\r
268                     write2disk("hb_queue_recovery.xml"); // Update the queue recovery file\r
269 \r
270                     encodeProcess = encodeHandler.runCli(query);\r
271                     EncodeStarted(null);\r
272                     encodeProcess.hbProcProcess.WaitForExit();\r
273 \r
274                     encodeHandler.addCLIQueryToLog(query);\r
275                     encodeHandler.copyLog(lastQueueItem.Destination);\r
276 \r
277                     encodeProcess.hbProcProcess.Close();\r
278                     encodeProcess.hbProcProcess.Dispose();\r
279                     EncodeFinished(null);\r
280 \r
281                     while (isPaused) // Need to find a better way of doing this.\r
282                     {\r
283                         Thread.Sleep(10000);\r
284                     }\r
285                 }\r
286                 EncodeQueueFinished(null);\r
287 \r
288                 // After the encode is done, we may want to shutdown, suspend etc.\r
289                 encodeHandler.afterEncodeAction(encodeProcess);\r
290             }\r
291             catch (Exception exc)\r
292             {\r
293                 throw new Exception(exc.ToString());\r
294             }\r
295         }\r
296         #endregion\r
297 \r
298         #region Events\r
299         public event EventHandler OnEncodeStart;\r
300         public event EventHandler OnPaused;\r
301         public event EventHandler OnEncodeEnded;\r
302         public event EventHandler OnQueueFinished;\r
303 \r
304         // Invoke the Changed event; called whenever encodestatus changes:\r
305         protected virtual void EncodeStarted(EventArgs e)\r
306         {\r
307             if (OnEncodeStart != null)\r
308                 OnEncodeStart(this, e);\r
309 \r
310             isEncoding = true;\r
311         }\r
312         protected virtual void EncodePaused(EventArgs e)\r
313         {\r
314             if (OnPaused != null)\r
315                 OnPaused(this, e);\r
316         }\r
317         protected virtual void EncodeFinished(EventArgs e)\r
318         {\r
319             if (OnEncodeEnded != null)\r
320                 OnEncodeEnded(this, e);\r
321 \r
322             isEncoding = false;\r
323         }\r
324         protected virtual void EncodeQueueFinished(EventArgs e)\r
325         {\r
326             if (OnQueueFinished != null)\r
327                 OnQueueFinished(this, e);\r
328         }\r
329         #endregion\r
330 \r
331     }\r
332 }