Merge master.
[dcpomatic.git] / src / lib / job.cc
1 /*
2     Copyright (C) 2012-2014 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 <dcp/exceptions.h>
27 #include "job.h"
28 #include "util.h"
29 #include "cross.h"
30 #include "ui_signaller.h"
31 #include "exceptions.h"
32 #include "film.h"
33 #include "log.h"
34
35 #include "i18n.h"
36
37 using std::string;
38 using std::list;
39 using std::cout;
40 using std::stringstream;
41 using boost::shared_ptr;
42
43 Job::Job (shared_ptr<const Film> f)
44         : _film (f)
45         , _thread (0)
46         , _state (NEW)
47         , _start_time (0)
48         , _progress (0)
49         , _ran_for (0)
50 {
51
52 }
53
54 /** Start the job in a separate thread, returning immediately */
55 void
56 Job::start ()
57 {
58         set_state (RUNNING);
59         _start_time = time (0);
60         _thread = new boost::thread (boost::bind (&Job::run_wrapper, this));
61 }
62
63 /** A wrapper for the ::run() method to catch exceptions */
64 void
65 Job::run_wrapper ()
66 {
67         try {
68
69                 run ();
70
71         } catch (dcp::FileError& e) {
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                 set_progress (1);
87                 set_state (FINISHED_ERROR);
88                 
89         } catch (OpenFileError& e) {
90
91                 set_error (
92                         String::compose (_("Could not open %1"), e.file().string()),
93                         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())
94                         );
95
96                 set_progress (1);
97                 set_state (FINISHED_ERROR);
98
99         } catch (boost::thread_interrupted &) {
100
101                 set_state (FINISHED_CANCELLED);
102
103         } catch (std::bad_alloc& e) {
104
105                 set_error (_("Out of memory"), _("There was not enough memory to do this."));
106                 set_progress (1);
107                 set_state (FINISHED_ERROR);
108                 
109         } catch (std::exception& e) {
110
111                 set_error (
112                         e.what (),
113                         _("It is not known what caused this error.  Please report the problem to the DCP-o-matic author (carl@dcpomatic.com).")
114                         );
115
116                 set_progress (1);
117                 set_state (FINISHED_ERROR);
118                 
119         } catch (...) {
120
121                 set_error (
122                         _("Unknown error"),
123                         _("It is not known what caused this error.  Please report the problem to the DCP-o-matic author (carl@dcpomatic.com).")
124                         );
125
126                 set_progress (1);
127                 set_state (FINISHED_ERROR);
128         }
129 }
130
131 /** @return true if this job is new (ie has not started running) */
132 bool
133 Job::is_new () const
134 {
135         boost::mutex::scoped_lock lm (_state_mutex);
136         return _state == NEW;
137 }
138
139 /** @return true if the job is running */
140 bool
141 Job::running () const
142 {
143         boost::mutex::scoped_lock lm (_state_mutex);
144         return _state == RUNNING;
145 }
146
147 /** @return true if the job has finished (either successfully or unsuccessfully) */
148 bool
149 Job::finished () const
150 {
151         boost::mutex::scoped_lock lm (_state_mutex);
152         return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
153 }
154
155 /** @return true if the job has finished successfully */
156 bool
157 Job::finished_ok () const
158 {
159         boost::mutex::scoped_lock lm (_state_mutex);
160         return _state == FINISHED_OK;
161 }
162
163 /** @return true if the job has finished unsuccessfully */
164 bool
165 Job::finished_in_error () const
166 {
167         boost::mutex::scoped_lock lm (_state_mutex);
168         return _state == FINISHED_ERROR;
169 }
170
171 bool
172 Job::finished_cancelled () const
173 {
174         boost::mutex::scoped_lock lm (_state_mutex);
175         return _state == FINISHED_CANCELLED;
176 }
177
178 bool
179 Job::paused () const
180 {
181         boost::mutex::scoped_lock lm (_state_mutex);
182         return _state == PAUSED;
183 }
184         
185 /** Set the state of this job.
186  *  @param s New state.
187  */
188 void
189 Job::set_state (State s)
190 {
191         bool finished = false;
192
193         {
194                 boost::mutex::scoped_lock lm (_state_mutex);
195                 _state = s;
196
197                 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
198                         _ran_for = elapsed_time ();
199                         finished = true;
200                         _sub_name.clear ();
201                 }
202         }
203
204         if (finished && ui_signaller) {
205                 ui_signaller->emit (boost::bind (boost::ref (Finished)));
206         }       
207 }
208
209 /** @return DCPTime (in seconds) that this sub-job has been running */
210 int
211 Job::elapsed_time () const
212 {
213         if (_start_time == 0) {
214                 return 0;
215         }
216         
217         return time (0) - _start_time;
218 }
219
220 /** Set the progress of the current part of the job.
221  *  @param p Progress (from 0 to 1)
222  */
223 void
224 Job::set_progress (float p, bool force)
225 {
226         if (!force && fabs (p - progress()) < 0.01) {
227                 /* Calm excessive progress reporting */
228                 return;
229         }
230
231         boost::mutex::scoped_lock lm (_progress_mutex);
232         _progress = p;
233         boost::this_thread::interruption_point ();
234
235         if (paused ()) {
236                 dcpomatic_sleep (1);
237         }
238
239         if (ui_signaller) {
240                 ui_signaller->emit (boost::bind (boost::ref (Progress)));
241         }
242 }
243
244 /** @return fractional progress of the current sub-job, or -1 if not known */
245 float
246 Job::progress () const
247 {
248         boost::mutex::scoped_lock lm (_progress_mutex);
249         return _progress.get_value_or (-1);
250 }
251
252 void
253 Job::sub (string n)
254 {
255         {
256                 boost::mutex::scoped_lock lm (_progress_mutex);
257                 _sub_name = n;
258         }
259         
260         set_progress (0, true);
261 }
262
263 string
264 Job::error_details () const
265 {
266         boost::mutex::scoped_lock lm (_state_mutex);
267         return _error_details;
268 }
269
270 /** @return A summary of any error that the job has generated */
271 string
272 Job::error_summary () const
273 {
274         boost::mutex::scoped_lock lm (_state_mutex);
275         return _error_summary;
276 }
277
278 /** Set the current error string.
279  *  @param e New error string.
280  */
281 void
282 Job::set_error (string s, string d)
283 {
284         _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d));
285         boost::mutex::scoped_lock lm (_state_mutex);
286         _error_summary = s;
287         _error_details = d;
288 }
289
290 /** Say that this job's progress will be unknown until further notice */
291 void
292 Job::set_progress_unknown ()
293 {
294         boost::mutex::scoped_lock lm (_progress_mutex);
295         _progress.reset ();
296 }
297
298 /** @return Human-readable status of this job */
299 string
300 Job::status () const
301 {
302         float const p = progress ();
303         int const t = elapsed_time ();
304         int const r = remaining_time ();
305
306         int pc = rint (p * 100);
307         if (pc == 100) {
308                 /* 100% makes it sound like we've finished when we haven't */
309                 pc = 99;
310         }
311
312         stringstream s;
313         if (!finished ()) {
314                 s << pc << N_("%");
315                 if (p >= 0 && t > 10 && r > 0) {
316                         /// TRANSLATORS: remaining here follows an amount of time that is remaining
317                         /// on an operation.
318                         s << "; " << seconds_to_approximate_hms (r) << " " << _("remaining");
319                 }
320         } else if (finished_ok ()) {
321                 s << String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
322         } else if (finished_in_error ()) {
323                 s << String::compose (_("Error (%1)"), error_summary());
324         } else if (finished_cancelled ()) {
325                 s << _("Cancelled");
326         }
327
328         return s.str ();
329 }
330
331 string
332 Job::json_status () const
333 {
334         boost::mutex::scoped_lock lm (_state_mutex);
335
336         switch (_state) {
337         case NEW:
338                 return N_("new");
339         case RUNNING:
340                 return N_("running");
341         case PAUSED:
342                 return N_("paused");
343         case FINISHED_OK:
344                 return N_("finished_ok");
345         case FINISHED_ERROR:
346                 return N_("finished_error");
347         case FINISHED_CANCELLED:
348                 return N_("finished_cancelled");
349         }
350
351         return "";
352 }
353
354 /** @return An estimate of the remaining time for this sub-job, in seconds */
355 int
356 Job::remaining_time () const
357 {
358         return elapsed_time() / progress() - elapsed_time();
359 }
360
361 void
362 Job::cancel ()
363 {
364         if (!_thread) {
365                 return;
366         }
367
368         _thread->interrupt ();
369         _thread->join ();
370 }
371
372 void
373 Job::pause ()
374 {
375         if (running ()) {
376                 set_state (PAUSED);
377         }
378 }
379
380 void
381 Job::resume ()
382 {
383         if (paused ()) {
384                 set_state (RUNNING);
385         }
386 }