Fix non-translated days of the week (#1455).
[dcpomatic.git] / src / lib / job.cc
1 /*
2     Copyright (C) 2012-2019 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 /** @file  src/job.cc
22  *  @brief A parent class to represent long-running tasks which are run in their own thread.
23  */
24
25 #include "job.h"
26 #include "util.h"
27 #include "cross.h"
28 #include "exceptions.h"
29 #include "film.h"
30 #include "log.h"
31 #include "dcpomatic_log.h"
32 #include "compose.hpp"
33 #include <dcp/exceptions.h>
34 #include <sub/exceptions.h>
35 #include <boost/thread.hpp>
36 #include <boost/filesystem.hpp>
37 #include <boost/foreach.hpp>
38 #include <boost/date_time/posix_time/posix_time.hpp>
39 #include <iostream>
40
41 #include "i18n.h"
42
43 using std::string;
44 using std::list;
45 using std::cout;
46 using boost::shared_ptr;
47 using boost::optional;
48 using boost::function;
49
50 /** @param film Associated film, or 0 */
51 Job::Job (shared_ptr<const Film> film)
52         : _film (film)
53         , _thread (0)
54         , _state (NEW)
55         , _start_time (0)
56         , _sub_start_time (0)
57         , _progress (0)
58         , _ran_for (0)
59 {
60
61 }
62
63 Job::~Job ()
64 {
65         if (_thread) {
66                 _thread->interrupt ();
67                 /* We can't use DCPOMATIC_ASSERT here as it may throw an exception */
68                 if (_thread->joinable ()) {
69                         try {
70                                 _thread->join ();
71                         } catch (...) {
72                                 /* Too late to do anything about this */
73                         }
74                 }
75         }
76
77         delete _thread;
78 }
79
80 /** Start the job in a separate thread, returning immediately */
81 void
82 Job::start ()
83 {
84         set_state (RUNNING);
85         _start_time = time (0);
86         _sub_start_time = time (0);
87         _thread = new boost::thread (boost::bind (&Job::run_wrapper, this));
88 #ifdef DCPOMATIC_LINUX
89         pthread_setname_np (_thread->native_handle(), "job-wrapper");
90 #endif
91 }
92
93 /** A wrapper for the ::run() method to catch exceptions */
94 void
95 Job::run_wrapper ()
96 {
97         try {
98
99                 run ();
100
101         } catch (dcp::FileError& e) {
102
103                 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
104
105                 try {
106                         boost::filesystem::space_info const s = boost::filesystem::space (e.filename());
107                         if (s.available < pow (1024, 3)) {
108                                 m += N_("\n\n");
109                                 m += _("The drive that the film is stored on is low in disc space.  Free some more space and try again.");
110                         }
111                 } catch (...) {
112
113                 }
114
115                 set_error (e.what(), m);
116                 set_progress (1);
117                 set_state (FINISHED_ERROR);
118
119         } catch (OpenFileError& e) {
120
121                 set_error (
122                         String::compose (_("Could not open %1"), e.file().string()),
123                         String::compose (
124                                 _("DCP-o-matic could not open the file %1 (%2).  Perhaps it does not exist or is in an unexpected format."),
125                                 boost::filesystem::absolute (e.file()).string(),
126                                 e.what()
127                                 )
128                         );
129
130                 set_progress (1);
131                 set_state (FINISHED_ERROR);
132
133         } catch (boost::filesystem::filesystem_error& e) {
134
135                 if (e.code() == boost::system::errc::no_such_file_or_directory) {
136                         set_error (
137                                 String::compose (_("Could not open %1"), e.path1().string ()),
138                                 String::compose (
139                                         _("DCP-o-matic could not open the file %1 (%2).  Perhaps it does not exist or is in an unexpected format."),
140                                         boost::filesystem::absolute (e.path1()).string(),
141                                         e.what()
142                                         )
143                                 );
144                 } else {
145                         set_error (
146                                 e.what (),
147                                 string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
148                                 );
149                 }
150
151                 set_progress (1);
152                 set_state (FINISHED_ERROR);
153
154         } catch (boost::thread_interrupted &) {
155
156                 set_state (FINISHED_CANCELLED);
157
158         } catch (sub::SubripError& e) {
159
160                 string extra = "Error is near:\n";
161                 BOOST_FOREACH (string i, e.context()) {
162                         extra += i + "\n";
163                 }
164
165                 set_error (e.what (), extra);
166                 set_progress (1);
167                 set_state (FINISHED_ERROR);
168
169         } catch (std::bad_alloc& e) {
170
171                 set_error (_("Out of memory"), _("There was not enough memory to do this.  If you are running a 32-bit operating system try reducing the number of encoding threads in the General tab of Preferences."));
172                 set_progress (1);
173                 set_state (FINISHED_ERROR);
174
175         } catch (dcp::MissingAssetError& e) {
176
177                 set_error (e.message(), e.path().string());
178                 set_progress (1);
179                 set_state (FINISHED_ERROR);
180
181         } catch (dcp::DCPReadError& e) {
182
183                 set_error (e.message(), e.detail().get_value_or(""));
184                 set_progress (1);
185                 set_state (FINISHED_ERROR);
186
187         } catch (KDMError& e) {
188
189                 set_error (e.summary(), e.detail());
190                 set_progress (1);
191                 set_state (FINISHED_ERROR);
192
193         } catch (std::exception& e) {
194
195                 set_error (
196                         e.what (),
197                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
198                         );
199
200                 set_progress (1);
201                 set_state (FINISHED_ERROR);
202
203         } catch (...) {
204
205                 set_error (
206                         _("Unknown error"),
207                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
208                         );
209
210                 set_progress (1);
211                 set_state (FINISHED_ERROR);
212         }
213 }
214
215 /** @return true if this job is new (ie has not started running) */
216 bool
217 Job::is_new () const
218 {
219         boost::mutex::scoped_lock lm (_state_mutex);
220         return _state == NEW;
221 }
222
223 /** @return true if the job is running */
224 bool
225 Job::running () const
226 {
227         boost::mutex::scoped_lock lm (_state_mutex);
228         return _state == RUNNING;
229 }
230
231 /** @return true if the job has finished (either successfully or unsuccessfully) */
232 bool
233 Job::finished () const
234 {
235         boost::mutex::scoped_lock lm (_state_mutex);
236         return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
237 }
238
239 /** @return true if the job has finished successfully */
240 bool
241 Job::finished_ok () const
242 {
243         boost::mutex::scoped_lock lm (_state_mutex);
244         return _state == FINISHED_OK;
245 }
246
247 /** @return true if the job has finished unsuccessfully */
248 bool
249 Job::finished_in_error () const
250 {
251         boost::mutex::scoped_lock lm (_state_mutex);
252         return _state == FINISHED_ERROR;
253 }
254
255 bool
256 Job::finished_cancelled () const
257 {
258         boost::mutex::scoped_lock lm (_state_mutex);
259         return _state == FINISHED_CANCELLED;
260 }
261
262 bool
263 Job::paused_by_user () const
264 {
265         boost::mutex::scoped_lock lm (_state_mutex);
266         return _state == PAUSED_BY_USER;
267 }
268
269 bool
270 Job::paused_by_priority () const
271 {
272         boost::mutex::scoped_lock lm (_state_mutex);
273         return _state == PAUSED_BY_PRIORITY;
274 }
275
276 /** Set the state of this job.
277  *  @param s New state.
278  */
279 void
280 Job::set_state (State s)
281 {
282         bool finished = false;
283
284         {
285                 boost::mutex::scoped_lock lm (_state_mutex);
286                 _state = s;
287
288                 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
289                         _ran_for = time(0) - _start_time;
290                         finished = true;
291                         _sub_name.clear ();
292                 }
293         }
294
295         if (finished) {
296                 emit (boost::bind (boost::ref (Finished)));
297                 FinishedImmediate ();
298         }
299 }
300
301 /** @return DCPTime (in seconds) that this sub-job has been running */
302 int
303 Job::elapsed_sub_time () const
304 {
305         if (_sub_start_time == 0) {
306                 return 0;
307         }
308
309         return time (0) - _sub_start_time;
310 }
311
312 /** Check to see if this job has been interrupted or paused */
313 void
314 Job::check_for_interruption_or_pause ()
315 {
316         boost::this_thread::interruption_point ();
317
318         boost::mutex::scoped_lock lm (_state_mutex);
319         while (_state == PAUSED_BY_USER || _state == PAUSED_BY_PRIORITY) {
320                 emit (boost::bind (boost::ref (Progress)));
321                 _pause_changed.wait (lm);
322         }
323 }
324
325 /** Set the progress of the current part of the job.
326  *  @param p Progress (from 0 to 1)
327  *  @param force Do not ignore this update, even if it hasn't been long since the last one.
328  */
329 void
330 Job::set_progress (float p, bool force)
331 {
332         check_for_interruption_or_pause ();
333
334         if (!force) {
335                 /* Check for excessively frequent progress reporting */
336                 boost::mutex::scoped_lock lm (_progress_mutex);
337                 struct timeval now;
338                 gettimeofday (&now, 0);
339                 if (_last_progress_update && _last_progress_update->tv_sec > 0) {
340                         double const elapsed = (now.tv_sec + now.tv_usec / 1000000.0)
341                                 - (_last_progress_update->tv_sec + _last_progress_update->tv_usec / 1000000.0);
342                         if (elapsed < 0.5) {
343                                 return;
344                         }
345                 }
346                 _last_progress_update = now;
347         }
348
349         set_progress_common (p);
350 }
351
352 void
353 Job::set_progress_common (optional<float> p)
354 {
355         {
356                 boost::mutex::scoped_lock lm (_progress_mutex);
357                 _progress = p;
358         }
359
360         emit (boost::bind (boost::ref (Progress)));
361 }
362
363 /** @return fractional progress of the current sub-job, if known */
364 optional<float>
365 Job::progress () const
366 {
367         boost::mutex::scoped_lock lm (_progress_mutex);
368         return _progress;
369 }
370
371 void
372 Job::sub (string n)
373 {
374         {
375                 boost::mutex::scoped_lock lm (_progress_mutex);
376                 LOG_GENERAL ("Sub-job %1 starting", n);
377                 _sub_name = n;
378         }
379
380         set_progress (0, true);
381         _sub_start_time = time (0);
382 }
383
384 string
385 Job::error_details () const
386 {
387         boost::mutex::scoped_lock lm (_state_mutex);
388         return _error_details;
389 }
390
391 /** @return A summary of any error that the job has generated */
392 string
393 Job::error_summary () const
394 {
395         boost::mutex::scoped_lock lm (_state_mutex);
396         return _error_summary;
397 }
398
399 /** Set the current error string.
400  *  @param s New error string.
401  *  @param d New error detail string.
402  */
403 void
404 Job::set_error (string s, string d)
405 {
406         if (_film) {
407                 _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d), LogEntry::TYPE_ERROR);
408         }
409
410         boost::mutex::scoped_lock lm (_state_mutex);
411         _error_summary = s;
412         _error_details = d;
413 }
414
415 /** Say that this job's progress will be unknown until further notice */
416 void
417 Job::set_progress_unknown ()
418 {
419         check_for_interruption_or_pause ();
420         set_progress_common (optional<float> ());
421 }
422
423 /** @return Human-readable status of this job */
424 string
425 Job::status () const
426 {
427         optional<float> p = progress ();
428         int const t = elapsed_sub_time ();
429         int const r = remaining_time ();
430
431         string s;
432         if (!finished () && p) {
433                 int pc = lrintf (p.get() * 100);
434                 if (pc == 100) {
435                         /* 100% makes it sound like we've finished when we haven't */
436                         pc = 99;
437                 }
438
439                 char buffer[64];
440                 snprintf (buffer, sizeof(buffer), "%d%%", pc);
441                 s += buffer;
442
443                 if (t > 10 && r > 0) {
444                         boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
445                         boost::posix_time::ptime finish = now + boost::posix_time::seconds(r);
446                         char finish_string[16];
447                         snprintf (finish_string, sizeof(finish_string), "%02d:%02d", int(finish.time_of_day().hours()), int(finish.time_of_day().minutes()));
448                         string day;
449                         if (now.date() != finish.date()) {
450                                 /// TRANSLATORS: the %1 in this string will be filled in with a day of the week
451                                 /// to say what day a job will finish.
452                                 day = String::compose (_(" on %1"), day_of_week_to_string(finish.date().day_of_week()));
453                         }
454                         /// TRANSLATORS: "remaining; finishing at" here follows an amount of time that is remaining
455                         /// on an operation; after it is an estimated wall-clock completion time.
456                         s += String::compose(
457                                 _("; %1 remaining; finishing at %2%3"),
458                                 seconds_to_approximate_hms(r), finish_string, day
459                                 );
460                 }
461         } else if (finished_ok ()) {
462                 s = String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
463         } else if (finished_in_error ()) {
464                 s = String::compose (_("Error: %1"), error_summary ());
465         } else if (finished_cancelled ()) {
466                 s = _("Cancelled");
467         }
468
469         return s;
470 }
471
472 string
473 Job::json_status () const
474 {
475         boost::mutex::scoped_lock lm (_state_mutex);
476
477         switch (_state) {
478         case NEW:
479                 return N_("new");
480         case RUNNING:
481                 return N_("running");
482         case PAUSED_BY_USER:
483         case PAUSED_BY_PRIORITY:
484                 return N_("paused");
485         case FINISHED_OK:
486                 return N_("finished_ok");
487         case FINISHED_ERROR:
488                 return N_("finished_error");
489         case FINISHED_CANCELLED:
490                 return N_("finished_cancelled");
491         }
492
493         return "";
494 }
495
496 /** @return An estimate of the remaining time for this sub-job, in seconds */
497 int
498 Job::remaining_time () const
499 {
500         if (progress().get_value_or(0) == 0) {
501                 return elapsed_sub_time ();
502         }
503
504         return elapsed_sub_time() / progress().get() - elapsed_sub_time();
505 }
506
507 void
508 Job::cancel ()
509 {
510         if (!_thread) {
511                 return;
512         }
513
514         if (paused_by_user() || paused_by_priority()) {
515                 resume ();
516         }
517
518         _thread->interrupt ();
519         DCPOMATIC_ASSERT (_thread->joinable ());
520         _thread->join ();
521         delete _thread;
522         _thread = 0;
523 }
524
525 /** @return true if the job was paused, false if it was not running */
526 bool
527 Job::pause_by_user ()
528 {
529         bool paused = false;
530         {
531                 boost::mutex::scoped_lock lm (_state_mutex);
532                 /* We can set _state here directly because we have a lock and we aren't
533                    setting the job to FINISHED_*
534                 */
535                 if (_state == RUNNING) {
536                         paused = true;
537                         _state = PAUSED_BY_USER;
538                 }
539         }
540
541         if (paused) {
542                 _pause_changed.notify_all ();
543         }
544
545         return paused;
546 }
547
548 void
549 Job::pause_by_priority ()
550 {
551         if (running ()) {
552                 set_state (PAUSED_BY_PRIORITY);
553                 _pause_changed.notify_all ();
554         }
555 }
556
557 void
558 Job::resume ()
559 {
560         if (paused_by_user() || paused_by_priority()) {
561                 set_state (RUNNING);
562                 _pause_changed.notify_all ();
563         }
564 }
565
566 void
567 Job::when_finished (boost::signals2::connection& connection, function<void()> finished)
568 {
569         boost::mutex::scoped_lock lm (_state_mutex);
570         if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
571                 finished ();
572         } else {
573                 connection = Finished.connect (finished);
574         }
575 }
576
577 optional<string>
578 Job::message () const
579 {
580         boost::mutex::scoped_lock lm (_state_mutex);
581         return _message;
582 }
583
584 void
585 Job::set_message (string m)
586 {
587         boost::mutex::scoped_lock lm (_state_mutex);
588         _message = m;
589 }