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