Remove polling from JobManagerView and use signals instead (fixes #137).
[dcpomatic.git] / src / lib / job.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file src/job.cc
21  *  @brief A parent class to represent long-running tasks which are run in their own thread.
22  */
23
24 #include <boost/thread.hpp>
25 #include <boost/filesystem.hpp>
26 #include <libdcp/exceptions.h>
27 #include "job.h"
28 #include "util.h"
29 #include "cross.h"
30 #include "ui_signaller.h"
31 #include "exceptions.h"
32
33 #include "i18n.h"
34
35 using std::string;
36 using std::list;
37 using std::stringstream;
38 using boost::shared_ptr;
39
40 Job::Job (shared_ptr<const Film> f)
41         : _film (f)
42         , _thread (0)
43         , _state (NEW)
44         , _start_time (0)
45         , _progress_unknown (false)
46         , _ran_for (0)
47 {
48         descend (1);
49 }
50
51 /** Start the job in a separate thread, returning immediately */
52 void
53 Job::start ()
54 {
55         set_state (RUNNING);
56         _start_time = time (0);
57         _thread = new boost::thread (boost::bind (&Job::run_wrapper, this));
58 }
59
60 /** A wrapper for the ::run() method to catch exceptions */
61 void
62 Job::run_wrapper ()
63 {
64         try {
65
66                 run ();
67
68         } catch (libdcp::FileError& e) {
69                 
70                 set_progress (1);
71                 set_state (FINISHED_ERROR);
72                 
73                 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
74
75                 try {
76                         boost::filesystem::space_info const s = boost::filesystem::space (e.filename());
77                         if (s.available < pow (1024, 3)) {
78                                 m += N_("\n\n");
79                                 m += _("The drive that the film is stored on is low in disc space.  Free some more space and try again.");
80                         }
81                 } catch (...) {
82
83                 }
84
85                 set_error (e.what(), m);
86
87         } catch (OpenFileError& e) {
88
89                 set_progress (1);
90                 set_state (FINISHED_ERROR);
91
92                 set_error (
93                         String::compose (_("Could not open %1"), e.file().string()),
94                         String::compose (_("DCP-o-matic could not open the file %1.  Perhaps it does not exist or is in an unexpected format."), e.file().string())
95                         );
96
97         } catch (boost::thread_interrupted &) {
98
99                 set_state (FINISHED_CANCELLED);
100                 
101         } catch (std::exception& e) {
102
103                 set_progress (1);
104                 set_state (FINISHED_ERROR);
105                 set_error (
106                         e.what (),
107                         _("It is not known what caused this error.  The best idea is to report the problem to the DCP-o-matic mailing list (dcpomatic@carlh.net)")
108                         );
109
110         } catch (...) {
111
112                 set_progress (1);
113                 set_state (FINISHED_ERROR);
114                 set_error (
115                         _("Unknown error"),
116                         _("It is not known what caused this error.  The best idea is to report the problem to the DCP-o-matic mailing list (dcpomatic@carlh.net)")
117                         );
118
119         }
120 }
121
122 /** @return true if this job is new (ie has not started running) */
123 bool
124 Job::is_new () const
125 {
126         boost::mutex::scoped_lock lm (_state_mutex);
127         return _state == NEW;
128 }
129
130 /** @return true if the job is running */
131 bool
132 Job::running () const
133 {
134         boost::mutex::scoped_lock lm (_state_mutex);
135         return _state == RUNNING;
136 }
137
138 /** @return true if the job has finished (either successfully or unsuccessfully) */
139 bool
140 Job::finished () const
141 {
142         boost::mutex::scoped_lock lm (_state_mutex);
143         return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
144 }
145
146 /** @return true if the job has finished successfully */
147 bool
148 Job::finished_ok () const
149 {
150         boost::mutex::scoped_lock lm (_state_mutex);
151         return _state == FINISHED_OK;
152 }
153
154 /** @return true if the job has finished unsuccessfully */
155 bool
156 Job::finished_in_error () const
157 {
158         boost::mutex::scoped_lock lm (_state_mutex);
159         return _state == FINISHED_ERROR;
160 }
161
162 bool
163 Job::finished_cancelled () const
164 {
165         boost::mutex::scoped_lock lm (_state_mutex);
166         return _state == FINISHED_CANCELLED;
167 }
168
169 bool
170 Job::paused () const
171 {
172         boost::mutex::scoped_lock lm (_state_mutex);
173         return _state == PAUSED;
174 }
175         
176 /** Set the state of this job.
177  *  @param s New state.
178  */
179 void
180 Job::set_state (State s)
181 {
182         boost::mutex::scoped_lock lm (_state_mutex);
183         _state = s;
184
185         if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
186                 _ran_for = elapsed_time ();
187                 if (ui_signaller) {
188                         ui_signaller->emit (boost::bind (boost::ref (Finished)));
189                 }
190         }
191 }
192
193 /** @return Time (in seconds) that this job has been running */
194 int
195 Job::elapsed_time () const
196 {
197         if (_start_time == 0) {
198                 return 0;
199         }
200         
201         return time (0) - _start_time;
202 }
203
204 /** Set the progress of the current part of the job.
205  *  @param p Progress (from 0 to 1)
206  */
207 void
208 Job::set_progress (float p)
209 {
210         boost::mutex::scoped_lock lm (_progress_mutex);
211         _progress_unknown = false;
212         _stack.back().normalised = p;
213         boost::this_thread::interruption_point ();
214
215         if (paused ()) {
216                 dcpomatic_sleep (1);
217         }
218
219         if (ui_signaller) {
220                 ui_signaller->emit (boost::bind (boost::ref (Progress)));
221         }
222 }
223
224 /** @return fractional overall progress, or -1 if not known */
225 float
226 Job::overall_progress () const
227 {
228         boost::mutex::scoped_lock lm (_progress_mutex);
229         if (_progress_unknown) {
230                 return -1;
231         }
232
233         float overall = 0;
234         float factor = 1;
235         for (list<Level>::const_iterator i = _stack.begin(); i != _stack.end(); ++i) {
236                 factor *= i->allocation;
237                 overall += i->normalised * factor;
238         }
239
240         if (overall > 1) {
241                 overall = 1;
242         }
243         
244         return overall;
245 }
246
247 /** Ascend up one level in terms of progress reporting; see descend() */
248 void
249 Job::ascend ()
250 {
251         boost::mutex::scoped_lock lm (_progress_mutex);
252         
253         assert (!_stack.empty ());
254         float const a = _stack.back().allocation;
255         _stack.pop_back ();
256         _stack.back().normalised += a;
257 }
258
259 /** Descend down one level in terms of progress reporting; e.g. if
260  *  there is a task which is split up into N subtasks, each of which
261  *  report their progress from 0 to 100%, call descend() before executing
262  *  each subtask, and ascend() afterwards to ensure that overall progress
263  *  is reported correctly.
264  *
265  *  @param a Fraction (from 0 to 1) of the current task to allocate to the subtask.
266  */
267 void
268 Job::descend (float a)
269 {
270         boost::mutex::scoped_lock lm (_progress_mutex);
271         _stack.push_back (Level (a));
272 }
273
274 string
275 Job::error_details () const
276 {
277         boost::mutex::scoped_lock lm (_state_mutex);
278         return _error_details;
279 }
280
281 /** @return A summary of any error that the job has generated */
282 string
283 Job::error_summary () const
284 {
285         boost::mutex::scoped_lock lm (_state_mutex);
286         return _error_summary;
287 }
288
289 /** Set the current error string.
290  *  @param e New error string.
291  */
292 void
293 Job::set_error (string s, string d)
294 {
295         boost::mutex::scoped_lock lm (_state_mutex);
296         _error_summary = s;
297         _error_details = d;
298 }
299
300 /** Say that this job's progress will be unknown until further notice */
301 void
302 Job::set_progress_unknown ()
303 {
304         boost::mutex::scoped_lock lm (_progress_mutex);
305         _progress_unknown = true;
306 }
307
308 /** @return Human-readable status of this job */
309 string
310 Job::status () const
311 {
312         float const p = overall_progress ();
313         int const t = elapsed_time ();
314         int const r = remaining_time ();
315
316         int pc = rint (p * 100);
317         if (pc == 100) {
318                 /* 100% makes it sound like we've finished when we haven't */
319                 pc = 99;
320         }
321
322         stringstream s;
323         if (!finished ()) {
324                 s << pc << N_("%");
325                 if (p >= 0 && t > 10 && r > 0) {
326                         /// TRANSLATORS: remaining here follows an amount of time that is remaining
327                         /// on an operation.
328                         s << "; " << seconds_to_approximate_hms (r) << " " << _("remaining");
329                 }
330         } else if (finished_ok ()) {
331                 s << String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
332         } else if (finished_in_error ()) {
333                 s << String::compose (_("Error (%1)"), error_summary());
334         } else if (finished_cancelled ()) {
335                 s << _("Cancelled");
336         }
337
338         return s.str ();
339 }
340
341 /** @return An estimate of the remaining time for this job, in seconds */
342 int
343 Job::remaining_time () const
344 {
345         return elapsed_time() / overall_progress() - elapsed_time();
346 }
347
348 void
349 Job::cancel ()
350 {
351         if (!_thread) {
352                 return;
353         }
354
355         _thread->interrupt ();
356         _thread->join ();
357 }
358
359 void
360 Job::pause ()
361 {
362         if (running ()) {
363                 set_state (PAUSED);
364         }
365 }
366
367 void
368 Job::resume ()
369 {
370         if (paused ()) {
371                 set_state (RUNNING);
372         }
373 }