OSDN Git Service

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