Fix response of the disk writer when polkit authorization fails on
[dcpomatic.git] / src / tools / dcpomatic_player.cc
1 /*
2     Copyright (C) 2017-2021 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 #include "wx/wx_signal_manager.h"
22 #include "wx/wx_util.h"
23 #include "wx/about_dialog.h"
24 #include "wx/report_problem_dialog.h"
25 #include "wx/film_viewer.h"
26 #include "wx/player_information.h"
27 #include "wx/update_dialog.h"
28 #include "wx/player_config_dialog.h"
29 #include "wx/verify_dcp_dialog.h"
30 #include "wx/standard_controls.h"
31 #include "wx/playlist_controls.h"
32 #include "wx/timer_display.h"
33 #include "wx/system_information_dialog.h"
34 #include "wx/player_stress_tester.h"
35 #include "wx/verify_dcp_progress_dialog.h"
36 #include "lib/cross.h"
37 #include "lib/config.h"
38 #include "lib/util.h"
39 #include "lib/internet.h"
40 #include "lib/update_checker.h"
41 #include "lib/compose.hpp"
42 #include "lib/dcp_content.h"
43 #include "lib/job_manager.h"
44 #include "lib/job.h"
45 #include "lib/film.h"
46 #include "lib/null_log.h"
47 #include "lib/video_content.h"
48 #include "lib/text_content.h"
49 #include "lib/ratio.h"
50 #include "lib/verify_dcp_job.h"
51 #include "lib/dcp_examiner.h"
52 #include "lib/examine_content_job.h"
53 #include "lib/server.h"
54 #include "lib/dcpomatic_socket.h"
55 #include "lib/scoped_temporary.h"
56 #include "lib/ffmpeg_content.h"
57 #include "lib/dcpomatic_log.h"
58 #include "lib/file_log.h"
59 #include <dcp/cpl.h>
60 #include <dcp/dcp.h>
61 #include <dcp/raw_convert.h>
62 #include <dcp/exceptions.h>
63 #include <wx/wx.h>
64 #include <wx/stdpaths.h>
65 #include <wx/splash.h>
66 #include <wx/cmdline.h>
67 #include <wx/preferences.h>
68 #include <wx/progdlg.h>
69 #include <wx/display.h>
70 #ifdef __WXGTK__
71 #include <X11/Xlib.h>
72 #endif
73 #include <boost/bind/bind.hpp>
74 #include <boost/algorithm/string.hpp>
75 #include <iostream>
76
77 #ifdef check
78 #undef check
79 #endif
80
81 #define MAX_CPLS 32
82
83 using std::cout;
84 using std::dynamic_pointer_cast;
85 using std::exception;
86 using std::list;
87 using std::make_shared;
88 using std::shared_ptr;
89 using std::string;
90 using std::vector;
91 using std::weak_ptr;
92 using boost::scoped_array;
93 using boost::optional;
94 using boost::thread;
95 using boost::bind;
96 #if BOOST_VERSION >= 106100
97 using namespace boost::placeholders;
98 #endif
99 using dcp::raw_convert;
100 using namespace dcpomatic;
101
102 enum {
103         ID_file_open = 1,
104         ID_file_add_ov,
105         ID_file_add_kdm,
106         ID_file_history,
107         /* Allow spare IDs after _history for the recent files list */
108         ID_file_close = 100,
109         ID_view_cpl,
110         /* Allow spare IDs for CPLs */
111         ID_view_full_screen = 200,
112         ID_view_dual_screen,
113         ID_view_closed_captions,
114         ID_view_scale_appropriate,
115         ID_view_scale_full,
116         ID_view_scale_half,
117         ID_view_scale_quarter,
118         ID_help_report_a_problem,
119         ID_tools_verify,
120         ID_tools_check_for_updates,
121         ID_tools_timing,
122         ID_tools_system_information,
123         /* IDs for shortcuts (with no associated menu item) */
124         ID_start_stop,
125         ID_go_back_frame,
126         ID_go_forward_frame,
127         ID_go_back_small_amount,
128         ID_go_forward_small_amount,
129         ID_go_back_medium_amount,
130         ID_go_forward_medium_amount,
131         ID_go_back_large_amount,
132         ID_go_forward_large_amount,
133         ID_go_to_start,
134         ID_go_to_end
135 };
136
137 class DOMFrame : public wxFrame
138 {
139 public:
140         DOMFrame ()
141                 : wxFrame (0, -1, _("DCP-o-matic Player"))
142                 , _dual_screen (0)
143                 , _update_news_requested (false)
144                 , _info (0)
145                 , _mode (Config::instance()->player_mode())
146                 , _config_dialog (0)
147                 , _file_menu (0)
148                 , _history_items (0)
149                 , _history_position (0)
150                 , _history_separator (0)
151                 , _system_information_dialog (0)
152                 , _view_full_screen (0)
153                 , _view_dual_screen (0)
154                 , _main_sizer (new wxBoxSizer (wxVERTICAL))
155         {
156                 dcpomatic_log = make_shared<NullLog>();
157
158 #if defined(DCPOMATIC_WINDOWS)
159                 maybe_open_console ();
160                 cout << "DCP-o-matic Player is starting." << "\n";
161 #endif
162
163                 auto bar = new wxMenuBar;
164                 setup_menu (bar);
165                 set_menu_sensitivity ();
166                 SetMenuBar (bar);
167
168 #ifdef DCPOMATIC_WINDOWS
169                 SetIcon (wxIcon (std_to_wx ("id")));
170 #endif
171
172                 _config_changed_connection = Config::instance()->Changed.connect (boost::bind (&DOMFrame::config_changed, this, _1));
173                 update_from_config (Config::PLAYER_DEBUG_LOG);
174
175                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_open, this), ID_file_open);
176                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_ov, this), ID_file_add_ov);
177                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_kdm, this), ID_file_add_kdm);
178                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_history, this, _1), ID_file_history, ID_file_history + HISTORY_SIZE);
179                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_close, this), ID_file_close);
180                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this), wxID_EXIT);
181                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this), wxID_PREFERENCES);
182                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_full_screen, this), ID_view_full_screen);
183                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_dual_screen, this), ID_view_dual_screen);
184                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_closed_captions, this), ID_view_closed_captions);
185                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_cpl, this, _1), ID_view_cpl, ID_view_cpl + MAX_CPLS);
186                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(0)), ID_view_scale_full);
187                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(1)), ID_view_scale_half);
188                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(2)), ID_view_scale_quarter);
189                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this), wxID_ABOUT);
190                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
191                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_verify, this), ID_tools_verify);
192                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_check_for_updates, this), ID_tools_check_for_updates);
193                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_timing, this), ID_tools_timing);
194                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_system_information, this), ID_tools_system_information);
195
196                 /* Use a panel as the only child of the Frame so that we avoid
197                    the dark-grey background on Windows.
198                 */
199                 _overall_panel = new wxPanel (this, wxID_ANY);
200
201                 _viewer.reset (new FilmViewer (_overall_panel));
202                 if (Config::instance()->player_mode() == Config::PLAYER_MODE_DUAL) {
203                         auto pc = new PlaylistControls (_overall_panel, _viewer);
204                         _controls = pc;
205                         pc->ResetFilm.connect (bind(&DOMFrame::reset_film_weak, this, _1));
206                 } else {
207                         _controls = new StandardControls (_overall_panel, _viewer, false);
208                 }
209                 _viewer->set_dcp_decode_reduction (Config::instance()->decode_reduction ());
210                 _viewer->PlaybackPermitted.connect (bind(&DOMFrame::playback_permitted, this));
211                 _viewer->Started.connect (bind(&DOMFrame::playback_started, this, _1));
212                 _viewer->Stopped.connect (bind(&DOMFrame::playback_stopped, this, _1));
213                 _info = new PlayerInformation (_overall_panel, _viewer);
214                 setup_main_sizer (Config::instance()->player_mode());
215 #ifdef __WXOSX__
216                 int accelerators = 12;
217 #else
218                 int accelerators = 11;
219 #endif
220
221                 _stress.setup (this, _controls);
222
223                 wxAcceleratorEntry* accel = new wxAcceleratorEntry[accelerators];
224                 accel[0].Set(wxACCEL_NORMAL,                WXK_SPACE, ID_start_stop);
225                 accel[1].Set(wxACCEL_NORMAL,                WXK_LEFT,  ID_go_back_frame);
226                 accel[2].Set(wxACCEL_NORMAL,                WXK_RIGHT, ID_go_forward_frame);
227                 accel[3].Set(wxACCEL_SHIFT,                 WXK_LEFT,  ID_go_back_small_amount);
228                 accel[4].Set(wxACCEL_SHIFT,                 WXK_RIGHT, ID_go_forward_small_amount);
229                 accel[5].Set(wxACCEL_CTRL,                  WXK_LEFT,  ID_go_back_medium_amount);
230                 accel[6].Set(wxACCEL_CTRL,                  WXK_RIGHT, ID_go_forward_medium_amount);
231                 accel[7].Set(wxACCEL_SHIFT | wxACCEL_CTRL,  WXK_LEFT,  ID_go_back_large_amount);
232                 accel[8].Set(wxACCEL_SHIFT | wxACCEL_CTRL,  WXK_RIGHT, ID_go_forward_large_amount);
233                 accel[9].Set(wxACCEL_NORMAL,                WXK_HOME,  ID_go_to_start);
234                 accel[10].Set(wxACCEL_NORMAL,               WXK_END,   ID_go_to_end);
235 #ifdef __WXOSX__
236                 accel[11].Set(wxACCEL_CTRL, static_cast<int>('W'), ID_file_close);
237 #endif
238                 wxAcceleratorTable accel_table (accelerators, accel);
239                 SetAcceleratorTable (accel_table);
240                 delete[] accel;
241
242                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::start_stop_pressed, this), ID_start_stop);
243                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_back_frame, this),      ID_go_back_frame);
244                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_forward_frame, this),   ID_go_forward_frame);
245                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,   -60), ID_go_back_small_amount);
246                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,    60), ID_go_forward_small_amount);
247                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,  -600), ID_go_back_medium_amount);
248                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,   600), ID_go_forward_medium_amount);
249                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this, -3600), ID_go_back_large_amount);
250                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,  3600), ID_go_forward_large_amount);
251                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_to_start, this), ID_go_to_start);
252                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_to_end,   this), ID_go_to_end);
253
254                 reset_film ();
255
256                 UpdateChecker::instance()->StateChanged.connect (boost::bind (&DOMFrame::update_checker_state_changed, this));
257                 setup_screen ();
258
259                 _stress.LoadDCP.connect (boost::bind(&DOMFrame::load_dcp, this, _1));
260         }
261
262         void setup_main_sizer (Config::PlayerMode mode)
263         {
264                 _main_sizer->Detach (_viewer->panel());
265                 _main_sizer->Detach (_controls);
266                 _main_sizer->Detach (_info);
267                 if (mode != Config::PLAYER_MODE_DUAL) {
268                         _main_sizer->Add (_viewer->panel(), 1, wxEXPAND);
269                 }
270                 _main_sizer->Add (_controls, mode == Config::PLAYER_MODE_DUAL ? 1 : 0, wxEXPAND | wxALL, 6);
271                 _main_sizer->Add (_info, 0, wxEXPAND | wxALL, 6);
272                 _overall_panel->SetSizer (_main_sizer);
273                 _overall_panel->Layout ();
274         }
275
276         bool playback_permitted ()
277         {
278                 if (!_film || !Config::instance()->respect_kdm_validity_periods()) {
279                         return true;
280                 }
281
282                 bool ok = true;
283                 for (auto i: _film->content()) {
284                         auto d = dynamic_pointer_cast<DCPContent>(i);
285                         if (d && !d->kdm_timing_window_valid()) {
286                                 ok = false;
287                         }
288                 }
289
290                 if (!ok) {
291                         error_dialog (this, _("The KDM does not allow playback of this content at this time."));
292                 }
293
294                 return ok;
295         }
296
297         void playback_started (DCPTime time)
298         {
299                 /* XXX: this only logs the first piece of content; probably should be each piece? */
300                 if (_film->content().empty()) {
301                         return;
302                 }
303
304                 auto dcp = dynamic_pointer_cast<DCPContent>(_film->content().front());
305                 if (dcp) {
306                         DCPExaminer ex (dcp, true);
307                         shared_ptr<dcp::CPL> playing_cpl;
308                         for (auto i: ex.cpls()) {
309                                 if (!dcp->cpl() || i->id() == *dcp->cpl()) {
310                                         playing_cpl = i;
311                                 }
312                         }
313                         DCPOMATIC_ASSERT (playing_cpl);
314
315                         _controls->log (
316                                 wxString::Format(
317                                         "playback-started %s %s %s",
318                                         time.timecode(_film->video_frame_rate()).c_str(),
319                                         dcp->directories().front().string().c_str(),
320                                         playing_cpl->annotation_text().get_value_or("").c_str()
321                                         )
322                                 );
323                 }
324
325                 auto ffmpeg = dynamic_pointer_cast<FFmpegContent>(_film->content().front());
326                 if (ffmpeg) {
327                         _controls->log (
328                                 wxString::Format(
329                                         "playback-started %s %s",
330                                         time.timecode(_film->video_frame_rate()).c_str(),
331                                         ffmpeg->path(0).string().c_str()
332                                         )
333                                 );
334                 }
335         }
336
337         void playback_stopped (DCPTime time)
338         {
339                 _controls->log (wxString::Format("playback-stopped %s", time.timecode(_film->video_frame_rate()).c_str()));
340         }
341
342         void set_decode_reduction (optional<int> reduction)
343         {
344                 _viewer->set_dcp_decode_reduction (reduction);
345                 _info->triggered_update ();
346                 Config::instance()->set_decode_reduction (reduction);
347         }
348
349         void load_dcp (boost::filesystem::path dir)
350         {
351                 DCPOMATIC_ASSERT (_film);
352
353                 reset_film ();
354                 try {
355                         _stress.set_suspended (true);
356                         // here
357                         auto dcp = make_shared<DCPContent>(dir);
358                         auto job = make_shared<ExamineContentJob>(_film, dcp);
359                         _examine_job_connection = job->Finished.connect(bind(&DOMFrame::add_dcp_to_film, this, weak_ptr<Job>(job), weak_ptr<Content>(dcp)));
360                         JobManager::instance()->add (job);
361                         bool const ok = display_progress (_("DCP-o-matic Player"), _("Loading content"));
362                         if (!ok || !report_errors_from_last_job(this)) {
363                                 return;
364                         }
365                         Config::instance()->add_to_player_history (dir);
366                 } catch (ProjectFolderError &) {
367                         error_dialog (
368                                 this,
369                                 wxString::Format(_("Could not load a DCP from %s"), std_to_wx(dir.string())),
370                                 _(
371                                         "This looks like a DCP-o-matic project folder, which cannot be loaded into the player.  "
372                                         "Choose the DCP directory inside the DCP-o-matic project folder if that's what you want to play."
373                                  )
374                                 );
375                 } catch (dcp::ReadError& e) {
376                         error_dialog (this, wxString::Format(_("Could not load a DCP from %s"), std_to_wx(dir.string())), std_to_wx(e.what()));
377                 } catch (DCPError& e) {
378                         error_dialog (this, wxString::Format(_("Could not load a DCP from %s"), std_to_wx(dir.string())), std_to_wx(e.what()));
379                 }
380         }
381
382         void add_dcp_to_film (weak_ptr<Job> weak_job, weak_ptr<Content> weak_content)
383         {
384                 auto job = weak_job.lock ();
385                 if (!job || !job->finished_ok()) {
386                         return;
387                 }
388
389                 auto content = weak_content.lock ();
390                 if (!content) {
391                         return;
392                 }
393
394                 _film->add_content (content);
395                 _stress.set_suspended (false);
396         }
397
398         void reset_film_weak (weak_ptr<Film> weak_film)
399         {
400                 auto film = weak_film.lock ();
401                 if (film) {
402                         reset_film (film);
403                 }
404         }
405
406         void reset_film (shared_ptr<Film> film = shared_ptr<Film>(new Film(optional<boost::filesystem::path>())))
407         {
408                 _film = film;
409                 _film->set_tolerant (true);
410                 _film->set_audio_channels (MAX_DCP_AUDIO_CHANNELS);
411                 _viewer->set_film (_film);
412                 _controls->set_film (_film);
413                 _film->Change.connect (bind(&DOMFrame::film_changed, this, _1, _2));
414                 _info->triggered_update ();
415         }
416
417         void film_changed (ChangeType type, Film::Property property)
418         {
419                 if (type != ChangeType::DONE || property != Film::Property::CONTENT) {
420                         return;
421                 }
422
423                 if (_viewer->playing ()) {
424                         _viewer->stop ();
425                 }
426
427                 /* Start off as Flat */
428                 _film->set_container (Ratio::from_id("185"));
429
430                 for (auto i: _film->content()) {
431                         auto dcp = dynamic_pointer_cast<DCPContent>(i);
432
433                         for (auto j: i->text) {
434                                 j->set_use (true);
435                         }
436
437                         if (i->video) {
438                                 auto const r = Ratio::nearest_from_ratio(i->video->size().ratio());
439                                 if (r->id() == "239") {
440                                         /* Any scope content means we use scope */
441                                         _film->set_container(r);
442                                 }
443                         }
444
445                         /* Any 3D content means we use 3D mode */
446                         if (i->video && i->video->frame_type() != VideoFrameType::TWO_D) {
447                                 _film->set_three_d (true);
448                         }
449                 }
450
451                 _viewer->seek (DCPTime(), true);
452                 _info->triggered_update ();
453
454                 set_menu_sensitivity ();
455
456                 auto old = _cpl_menu->GetMenuItems();
457                 for (auto const& i: old) {
458                         _cpl_menu->Remove (i);
459                 }
460
461                 if (_film->content().size() == 1) {
462                         /* Offer a CPL menu */
463                         auto first = dynamic_pointer_cast<DCPContent>(_film->content().front());
464                         if (first) {
465                                 DCPExaminer ex (first, true);
466                                 int id = ID_view_cpl;
467                                 for (auto i: ex.cpls()) {
468                                         auto j = _cpl_menu->AppendRadioItem(
469                                                 id,
470                                                 wxString::Format("%s (%s)", std_to_wx(i->annotation_text().get_value_or("")).data(), std_to_wx(i->id()).data())
471                                                 );
472                                         j->Check(!first->cpl() || i->id() == *first->cpl());
473                                         ++id;
474                                 }
475                         }
476                 }
477         }
478
479         void load_stress_script (boost::filesystem::path path)
480         {
481                 _stress.load_script (path);
482         }
483
484 private:
485
486         void examine_content ()
487         {
488                 DCPOMATIC_ASSERT (_film);
489                 auto dcp = dynamic_pointer_cast<DCPContent>(_film->content().front());
490                 DCPOMATIC_ASSERT (dcp);
491                 dcp->examine (_film, shared_ptr<Job>());
492
493                 /* Examining content re-creates the TextContent objects, so we must re-enable them */
494                 for (auto i: dcp->text) {
495                         i->set_use (true);
496                 }
497         }
498
499         bool report_errors_from_last_job (wxWindow* parent) const
500         {
501                 auto jm = JobManager::instance ();
502
503                 DCPOMATIC_ASSERT (!jm->get().empty());
504
505                 auto last = jm->get().back();
506                 if (last->finished_in_error()) {
507                         error_dialog(parent, wxString::Format(_("Could not load DCP.\n\n%s."), std_to_wx(last->error_summary()).data()), std_to_wx(last->error_details()));
508                         return false;
509                 }
510
511                 return true;
512         }
513
514         void setup_menu (wxMenuBar* m)
515         {
516                 _file_menu = new wxMenu;
517                 _file_menu->Append (ID_file_open, _("&Open...\tCtrl-O"));
518                 _file_add_ov = _file_menu->Append (ID_file_add_ov, _("&Add OV..."));
519                 _file_add_kdm = _file_menu->Append (ID_file_add_kdm, _("Add &KDM..."));
520
521                 _history_position = _file_menu->GetMenuItems().GetCount();
522
523                 _file_menu->AppendSeparator ();
524                 _file_menu->Append (ID_file_close, _("&Close"));
525                 _file_menu->AppendSeparator ();
526
527 #ifdef __WXOSX__
528                 _file_menu->Append (wxID_EXIT, _("&Exit"));
529 #else
530                 _file_menu->Append (wxID_EXIT, _("&Quit"));
531 #endif
532
533 #ifdef __WXOSX__
534                 auto prefs = _file_menu->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
535 #else
536                 auto edit = new wxMenu;
537                 auto prefs = edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
538 #endif
539
540                 prefs->Enable (Config::instance()->have_write_permission());
541
542                 _cpl_menu = new wxMenu;
543
544                 auto view = new wxMenu;
545                 auto c = Config::instance()->decode_reduction();
546                 _view_cpl = view->Append(ID_view_cpl, _("CPL"), _cpl_menu);
547                 view->AppendSeparator();
548                 _view_full_screen = view->AppendCheckItem(ID_view_full_screen, _("Full screen\tF11"));
549                 _view_dual_screen = view->AppendCheckItem(ID_view_dual_screen, _("Dual screen\tShift+F11"));
550                 setup_menu ();
551                 view->AppendSeparator();
552                 view->Append(ID_view_closed_captions, _("Closed captions..."));
553                 view->AppendSeparator();
554                 view->AppendRadioItem(ID_view_scale_appropriate, _("Set decode resolution to match display"))->Check(!static_cast<bool>(c));
555                 view->AppendRadioItem(ID_view_scale_full, _("Decode at full resolution"))->Check(c && c.get() == 0);
556                 view->AppendRadioItem(ID_view_scale_half, _("Decode at half resolution"))->Check(c && c.get() == 1);
557                 view->AppendRadioItem(ID_view_scale_quarter, _("Decode at quarter resolution"))->Check(c && c.get() == 2);
558
559                 auto tools = new wxMenu;
560                 _tools_verify = tools->Append (ID_tools_verify, _("Verify DCP..."));
561                 tools->AppendSeparator ();
562                 tools->Append (ID_tools_check_for_updates, _("Check for updates"));
563                 tools->Append (ID_tools_timing, _("Timing..."));
564                 tools->Append (ID_tools_system_information, _("System information..."));
565
566                 auto help = new wxMenu;
567 #ifdef __WXOSX__
568                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
569 #else
570                 help->Append (wxID_ABOUT, _("About"));
571 #endif
572                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
573
574                 m->Append (_file_menu, _("&File"));
575 #ifndef __WXOSX__
576                 m->Append (edit, _("&Edit"));
577 #endif
578                 m->Append (view, _("&View"));
579                 m->Append (tools, _("&Tools"));
580                 m->Append (help, _("&Help"));
581         }
582
583         void file_open ()
584         {
585                 auto d = wxStandardPaths::Get().GetDocumentsDir();
586                 if (Config::instance()->last_player_load_directory()) {
587                         d = std_to_wx (Config::instance()->last_player_load_directory()->string());
588                 }
589
590                 auto c = new wxDirDialog (this, _("Select DCP to open"), d, wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST);
591
592                 int r;
593                 while (true) {
594                         r = c->ShowModal ();
595                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
596                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
597                         } else {
598                                 break;
599                         }
600                 }
601
602                 if (r == wxID_OK) {
603                         boost::filesystem::path const dcp (wx_to_std (c->GetPath ()));
604                         load_dcp (dcp);
605                         Config::instance()->set_last_player_load_directory (dcp.parent_path());
606                 }
607
608                 c->Destroy ();
609         }
610
611         void file_add_ov ()
612         {
613                 auto c = new wxDirDialog (
614                         this,
615                         _("Select DCP to open as OV"),
616                         wxStandardPaths::Get().GetDocumentsDir(),
617                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
618                         );
619
620                 int r;
621                 while (true) {
622                         r = c->ShowModal ();
623                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
624                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
625                         } else {
626                                 break;
627                         }
628                 }
629
630                 if (r == wxID_OK) {
631                         DCPOMATIC_ASSERT (_film);
632                         auto dcp = std::dynamic_pointer_cast<DCPContent>(_film->content().front());
633                         DCPOMATIC_ASSERT (dcp);
634                         dcp->add_ov (wx_to_std(c->GetPath()));
635                         JobManager::instance()->add(make_shared<ExamineContentJob>(_film, dcp));
636                         bool const ok = display_progress (_("DCP-o-matic Player"), _("Loading content"));
637                         if (!ok || !report_errors_from_last_job(this)) {
638                                 return;
639                         }
640                         for (auto i: dcp->text) {
641                                 i->set_use (true);
642                         }
643                         if (dcp->video) {
644                                 auto const r = Ratio::nearest_from_ratio(dcp->video->size().ratio());
645                                 if (r) {
646                                         _film->set_container(r);
647                                 }
648                         }
649                 }
650
651                 c->Destroy ();
652                 _info->triggered_update ();
653         }
654
655         void file_add_kdm ()
656         {
657                 auto d = new wxFileDialog (this, _("Select KDM"));
658
659                 if (d->ShowModal() == wxID_OK) {
660                         DCPOMATIC_ASSERT (_film);
661                         auto dcp = std::dynamic_pointer_cast<DCPContent>(_film->content().front());
662                         DCPOMATIC_ASSERT (dcp);
663                         try {
664                                 if (dcp) {
665                                         _viewer->set_coalesce_player_changes (true);
666                                         dcp->add_kdm (dcp::EncryptedKDM(dcp::file_to_string(wx_to_std(d->GetPath()), MAX_KDM_SIZE)));
667                                         examine_content();
668                                         _viewer->set_coalesce_player_changes (false);
669                                 }
670                         } catch (exception& e) {
671                                 error_dialog (this, wxString::Format (_("Could not load KDM.")), std_to_wx(e.what()));
672                                 d->Destroy ();
673                                 return;
674                         }
675                 }
676
677                 d->Destroy ();
678                 _info->triggered_update ();
679         }
680
681         void file_history (wxCommandEvent& event)
682         {
683                 auto history = Config::instance()->player_history ();
684                 int n = event.GetId() - ID_file_history;
685                 if (n >= 0 && n < static_cast<int> (history.size ())) {
686                         try {
687                                 load_dcp (history[n]);
688                         } catch (exception& e) {
689                                 error_dialog (0, std_to_wx(String::compose(wx_to_std(_("Could not load DCP %1.")), history[n])), std_to_wx(e.what()));
690                         }
691                 }
692         }
693
694         void file_close ()
695         {
696                 reset_film ();
697                 _info->triggered_update ();
698                 set_menu_sensitivity ();
699         }
700
701         void file_exit ()
702         {
703                 Close ();
704         }
705
706         void edit_preferences ()
707         {
708                 if (!Config::instance()->have_write_permission()) {
709                         return;
710                 }
711
712                 if (!_config_dialog) {
713                         _config_dialog = create_player_config_dialog ();
714                 }
715                 _config_dialog->Show (this);
716         }
717
718         void view_cpl (wxCommandEvent& ev)
719         {
720                 auto dcp = std::dynamic_pointer_cast<DCPContent>(_film->content().front());
721                 DCPOMATIC_ASSERT (dcp);
722                 DCPExaminer ex (dcp, true);
723                 int id = ev.GetId() - ID_view_cpl;
724                 DCPOMATIC_ASSERT (id >= 0);
725                 DCPOMATIC_ASSERT (id < int(ex.cpls().size()));
726                 auto cpls = ex.cpls();
727                 auto i = cpls.begin();
728                 while (id > 0) {
729                         ++i;
730                         --id;
731                 }
732
733                 _viewer->set_coalesce_player_changes (true);
734                 dcp->set_cpl ((*i)->id());
735                 examine_content ();
736                 _viewer->set_coalesce_player_changes (false);
737
738                 _info->triggered_update ();
739         }
740
741         void view_full_screen ()
742         {
743                 if (_mode == Config::PLAYER_MODE_FULL) {
744                         _mode = Config::PLAYER_MODE_WINDOW;
745                 } else {
746                         _mode = Config::PLAYER_MODE_FULL;
747                 }
748                 setup_screen ();
749                 setup_menu ();
750         }
751
752         void view_dual_screen ()
753         {
754                 if (_mode == Config::PLAYER_MODE_DUAL) {
755                         _mode = Config::PLAYER_MODE_WINDOW;
756                 } else {
757                         _mode = Config::PLAYER_MODE_DUAL;
758                 }
759                 setup_screen ();
760                 setup_menu ();
761         }
762
763         void setup_menu ()
764         {
765                 if (_view_full_screen) {
766                         _view_full_screen->Check (_mode == Config::PLAYER_MODE_FULL);
767                 }
768                 if (_view_dual_screen) {
769                         _view_dual_screen->Check (_mode == Config::PLAYER_MODE_DUAL);
770                 }
771         }
772
773         void setup_screen ()
774         {
775                 _controls->Show (_mode != Config::PLAYER_MODE_FULL);
776                 _info->Show (_mode != Config::PLAYER_MODE_FULL);
777                 _overall_panel->SetBackgroundColour (_mode == Config::PLAYER_MODE_FULL ? wxColour(0, 0, 0) : wxNullColour);
778                 ShowFullScreen (_mode == Config::PLAYER_MODE_FULL);
779                 _viewer->set_pad_black (_mode != Config::PLAYER_MODE_WINDOW);
780
781                 if (_mode == Config::PLAYER_MODE_DUAL) {
782                         _dual_screen = new wxFrame (this, wxID_ANY, wxT(""));
783                         _dual_screen->SetBackgroundColour (wxColour(0, 0, 0));
784                         _dual_screen->ShowFullScreen (true);
785                         _viewer->panel()->Reparent (_dual_screen);
786                         _dual_screen->Show ();
787                         if (wxDisplay::GetCount() > 1) {
788                                 switch (Config::instance()->image_display()) {
789                                 case 0:
790                                         _dual_screen->Move (0, 0);
791                                         Move (wxDisplay(0U).GetClientArea().GetWidth(), 0);
792                                         break;
793                                 case 1:
794                                         _dual_screen->Move (wxDisplay(0U).GetClientArea().GetWidth(), 0);
795                                         // (0, 0) doesn't seem to work for some strange reason
796                                         Move (8, 8);
797                                         break;
798                                 }
799                         }
800                 } else {
801                         if (_dual_screen) {
802                                 _viewer->panel()->Reparent (_overall_panel);
803                                 _dual_screen->Destroy ();
804                                 _dual_screen = 0;
805                         }
806                 }
807
808                 setup_main_sizer (_mode);
809         }
810
811         void view_closed_captions ()
812         {
813                 _viewer->show_closed_captions ();
814         }
815
816         void tools_verify ()
817         {
818                 auto dcp = std::dynamic_pointer_cast<DCPContent>(_film->content().front());
819                 DCPOMATIC_ASSERT (dcp);
820
821                 auto job = make_shared<VerifyDCPJob>(dcp->directories());
822                 auto progress = new VerifyDCPProgressDialog(this, _("DCP-o-matic Player"));
823                 bool const completed = progress->run (job);
824                 progress->Destroy ();
825                 if (!completed) {
826                         return;
827                 }
828
829                 auto d = new VerifyDCPDialog (this, job);
830                 d->ShowModal ();
831                 d->Destroy ();
832         }
833
834         void tools_check_for_updates ()
835         {
836                 UpdateChecker::instance()->run ();
837                 _update_news_requested = true;
838         }
839
840         void tools_timing ()
841         {
842                 auto d = new TimerDisplay (this, _viewer->state_timer(), _viewer->gets());
843                 d->ShowModal ();
844                 d->Destroy ();
845         }
846
847         void tools_system_information ()
848         {
849                 if (!_system_information_dialog) {
850                         _system_information_dialog = new SystemInformationDialog (this, _viewer);
851                 }
852
853                 _system_information_dialog->Show ();
854         }
855
856         void help_about ()
857         {
858                 auto d = new AboutDialog (this);
859                 d->ShowModal ();
860                 d->Destroy ();
861         }
862
863         void help_report_a_problem ()
864         {
865                 auto d = new ReportProblemDialog (this);
866                 if (d->ShowModal () == wxID_OK) {
867                         d->report ();
868                 }
869                 d->Destroy ();
870         }
871
872         void update_checker_state_changed ()
873         {
874                 auto uc = UpdateChecker::instance ();
875
876                 bool const announce =
877                         _update_news_requested ||
878                         (uc->stable() && Config::instance()->check_for_updates()) ||
879                         (uc->test() && Config::instance()->check_for_updates() && Config::instance()->check_for_test_updates());
880
881                 _update_news_requested = false;
882
883                 if (!announce) {
884                         return;
885                 }
886
887                 if (uc->state() == UpdateChecker::State::YES) {
888                         auto dialog = new UpdateDialog (this, uc->stable (), uc->test ());
889                         dialog->ShowModal ();
890                         dialog->Destroy ();
891                 } else if (uc->state() == UpdateChecker::State::FAILED) {
892                         error_dialog (this, _("The DCP-o-matic download server could not be contacted."));
893                 } else {
894                         error_dialog (this, _("There are no new versions of DCP-o-matic available."));
895                 }
896
897                 _update_news_requested = false;
898         }
899
900         void config_changed (Config::Property prop)
901         {
902                 /* Instantly save any config changes when using the player GUI */
903                 try {
904                         Config::instance()->write_config();
905                 } catch (FileError& e) {
906                         if (prop != Config::HISTORY) {
907                                 error_dialog (
908                                         this,
909                                         wxString::Format(
910                                                 _("Could not write to config file at %s.  Your changes have not been saved."),
911                                                 std_to_wx(e.file().string())
912                                                 )
913                                         );
914                         }
915                 } catch (exception& e) {
916                         error_dialog (
917                                 this,
918                                 _("Could not write to config file.  Your changes have not been saved.")
919                                 );
920                 }
921
922                 update_from_config (prop);
923         }
924
925         void update_from_config (Config::Property prop)
926         {
927                 for (int i = 0; i < _history_items; ++i) {
928                         delete _file_menu->Remove (ID_file_history + i);
929                 }
930
931                 if (_history_separator) {
932                         _file_menu->Remove (_history_separator);
933                 }
934                 delete _history_separator;
935                 _history_separator = nullptr;
936
937                 int pos = _history_position;
938
939                 /* Clear out non-existant history items before we re-build the menu */
940                 Config::instance()->clean_player_history ();
941                 auto history = Config::instance()->player_history ();
942
943                 if (!history.empty ()) {
944                         _history_separator = _file_menu->InsertSeparator (pos++);
945                 }
946
947                 for (size_t i = 0; i < history.size(); ++i) {
948                         string s;
949                         if (i < 9) {
950                                 s = String::compose ("&%1 %2", i + 1, history[i].string());
951                         } else {
952                                 s = history[i].string();
953                         }
954                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s));
955                 }
956
957                 _history_items = history.size ();
958
959                 if (prop == Config::PLAYER_DEBUG_LOG) {
960                         auto p = Config::instance()->player_debug_log_file();
961                         if (p) {
962                                 dcpomatic_log = make_shared<FileLog>(*p);
963                         } else {
964                                 dcpomatic_log = make_shared<NullLog>();
965                         }
966                         dcpomatic_log->set_types (LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR | LogEntry::TYPE_DEBUG_VIDEO_VIEW);
967                 }
968         }
969
970         void set_menu_sensitivity ()
971         {
972                 _tools_verify->Enable (static_cast<bool>(_film));
973                 _file_add_ov->Enable (static_cast<bool>(_film));
974                 _file_add_kdm->Enable (static_cast<bool>(_film));
975                 _view_cpl->Enable (static_cast<bool>(_film));
976         }
977
978         void start_stop_pressed ()
979         {
980                 if (_viewer->playing()) {
981                         _viewer->stop();
982                 } else {
983                         _viewer->start();
984                 }
985         }
986
987         void go_back_frame ()
988         {
989                 _viewer->seek_by (-_viewer->one_video_frame(), true);
990         }
991
992         void go_forward_frame ()
993         {
994                 _viewer->seek_by (_viewer->one_video_frame(), true);
995         }
996
997         void go_seconds (int s)
998         {
999                 _viewer->seek_by (DCPTime::from_seconds(s), true);
1000         }
1001
1002         void go_to_start ()
1003         {
1004                 _viewer->seek (DCPTime(), true);
1005         }
1006
1007         void go_to_end ()
1008         {
1009                 _viewer->seek (_film->length() - _viewer->one_video_frame(), true);
1010         }
1011
1012         wxFrame* _dual_screen;
1013         bool _update_news_requested;
1014         PlayerInformation* _info;
1015         Config::PlayerMode _mode;
1016         wxPreferencesEditor* _config_dialog;
1017         wxPanel* _overall_panel;
1018         wxMenu* _file_menu;
1019         wxMenuItem* _view_cpl;
1020         wxMenu* _cpl_menu;
1021         int _history_items;
1022         int _history_position;
1023         wxMenuItem* _history_separator;
1024         shared_ptr<FilmViewer> _viewer;
1025         Controls* _controls;
1026         SystemInformationDialog* _system_information_dialog;
1027         std::shared_ptr<Film> _film;
1028         boost::signals2::scoped_connection _config_changed_connection;
1029         boost::signals2::scoped_connection _examine_job_connection;
1030         wxMenuItem* _file_add_ov;
1031         wxMenuItem* _file_add_kdm;
1032         wxMenuItem* _tools_verify;
1033         wxMenuItem* _view_full_screen;
1034         wxMenuItem* _view_dual_screen;
1035         wxSizer* _main_sizer;
1036         PlayerStressTester _stress;
1037 };
1038
1039 static const wxCmdLineEntryDesc command_line_description[] = {
1040         { wxCMD_LINE_PARAM, 0, 0, "DCP to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1041         { wxCMD_LINE_OPTION, "c", "config", "Directory containing config.xml", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1042         { wxCMD_LINE_OPTION, "s", "stress", "File containing description of stress test", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1043         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
1044 };
1045
1046 class PlayServer : public Server
1047 {
1048 public:
1049         explicit PlayServer (DOMFrame* frame)
1050                 : Server (PLAYER_PLAY_PORT)
1051                 , _frame (frame)
1052         {}
1053
1054         void handle (shared_ptr<Socket> socket)
1055         {
1056                 try {
1057                         int const length = socket->read_uint32 ();
1058                         scoped_array<char> buffer (new char[length]);
1059                         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
1060                         string s (buffer.get());
1061                         signal_manager->when_idle (bind (&DOMFrame::load_dcp, _frame, s));
1062                         socket->write (reinterpret_cast<uint8_t const *> ("OK"), 3);
1063                 } catch (...) {
1064
1065                 }
1066         }
1067
1068 private:
1069         DOMFrame* _frame;
1070 };
1071
1072 /** @class App
1073  *  @brief The magic App class for wxWidgets.
1074  */
1075 class App : public wxApp
1076 {
1077 public:
1078         App ()
1079                 : wxApp ()
1080                 , _frame (0)
1081         {
1082 #ifdef DCPOMATIC_LINUX
1083                 XInitThreads ();
1084 #endif
1085         }
1086
1087 private:
1088
1089         bool OnInit ()
1090         {
1091                 wxSplashScreen* splash = 0;
1092                 try {
1093                         wxInitAllImageHandlers ();
1094
1095                         Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
1096                         Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
1097
1098                         splash = maybe_show_splash ();
1099
1100                         SetAppName (_("DCP-o-matic Player"));
1101
1102                         if (!wxApp::OnInit()) {
1103                                 return false;
1104                         }
1105
1106 #ifdef DCPOMATIC_LINUX
1107                         unsetenv ("UBUNTU_MENUPROXY");
1108 #endif
1109
1110 #ifdef DCPOMATIC_OSX
1111                         make_foreground_application ();
1112 #endif
1113
1114                         dcpomatic_setup_path_encoding ();
1115
1116                         /* Enable i18n; this will create a Config object
1117                            to look for a force-configured language.  This Config
1118                            object will be wrong, however, because dcpomatic_setup
1119                            hasn't yet been called and there aren't any filters etc.
1120                            set up yet.
1121                         */
1122                         dcpomatic_setup_i18n ();
1123
1124                         /* Set things up, including filters etc.
1125                            which will now be internationalised correctly.
1126                         */
1127                         dcpomatic_setup ();
1128
1129                         /* Force the configuration to be re-loaded correctly next
1130                            time it is needed.
1131                         */
1132                         Config::drop ();
1133
1134                         signal_manager = new wxSignalManager (this);
1135
1136                         _frame = new DOMFrame ();
1137                         SetTopWindow (_frame);
1138                         _frame->Maximize ();
1139                         if (splash) {
1140                                 splash->Destroy ();
1141                                 splash = 0;
1142                         }
1143                         _frame->Show ();
1144
1145                         PlayServer* server = new PlayServer (_frame);
1146                         new thread (boost::bind (&PlayServer::run, server));
1147
1148                         if (!_dcp_to_load.empty() && boost::filesystem::is_directory (_dcp_to_load)) {
1149                                 try {
1150                                         _frame->load_dcp (_dcp_to_load);
1151                                 } catch (exception& e) {
1152                                         error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load DCP %1.")), _dcp_to_load)), std_to_wx(e.what()));
1153                                 }
1154                         }
1155
1156                         if (_stress) {
1157                                 try {
1158                                         _frame->load_stress_script (*_stress);
1159                                 } catch (exception& e) {
1160                                         error_dialog (0, wxString::Format("Could not load stress test file %s", std_to_wx(*_stress)));
1161                                 }
1162                         }
1163
1164                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
1165
1166                         if (Config::instance()->check_for_updates ()) {
1167                                 UpdateChecker::instance()->run ();
1168                         }
1169                 }
1170                 catch (exception& e)
1171                 {
1172                         if (splash) {
1173                                 splash->Destroy ();
1174                         }
1175                         error_dialog (0, _("DCP-o-matic Player could not start."), std_to_wx(e.what()));
1176                 }
1177
1178                 return true;
1179         }
1180
1181         void OnInitCmdLine (wxCmdLineParser& parser)
1182         {
1183                 parser.SetDesc (command_line_description);
1184                 parser.SetSwitchChars (wxT ("-"));
1185         }
1186
1187         bool OnCmdLineParsed (wxCmdLineParser& parser)
1188         {
1189                 if (parser.GetParamCount() > 0) {
1190                         _dcp_to_load = wx_to_std (parser.GetParam (0));
1191                 }
1192
1193                 wxString config;
1194                 if (parser.Found("c", &config)) {
1195                         Config::override_path = wx_to_std (config);
1196                 }
1197                 wxString stress;
1198                 if (parser.Found("s", &stress)) {
1199                         _stress = wx_to_std (stress);
1200                 }
1201
1202                 return true;
1203         }
1204
1205         void report_exception ()
1206         {
1207                 try {
1208                         throw;
1209                 } catch (FileError& e) {
1210                         error_dialog (
1211                                 0,
1212                                 wxString::Format (
1213                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
1214                                         std_to_wx (e.what()),
1215                                         std_to_wx (e.file().string().c_str ())
1216                                         )
1217                                 );
1218                 } catch (exception& e) {
1219                         error_dialog (
1220                                 0,
1221                                 wxString::Format (
1222                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
1223                                         std_to_wx (e.what ())
1224                                         )
1225                                 );
1226                 } catch (...) {
1227                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
1228                 }
1229         }
1230
1231         /* An unhandled exception has occurred inside the main event loop */
1232         bool OnExceptionInMainLoop ()
1233         {
1234                 report_exception ();
1235                 /* This will terminate the program */
1236                 return false;
1237         }
1238
1239         void OnUnhandledException ()
1240         {
1241                 report_exception ();
1242         }
1243
1244         void idle ()
1245         {
1246                 signal_manager->ui_idle ();
1247         }
1248
1249         void config_failed_to_load ()
1250         {
1251                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
1252         }
1253
1254         void config_warning (string m)
1255         {
1256                 message_dialog (_frame, std_to_wx (m));
1257         }
1258
1259         DOMFrame* _frame;
1260         string _dcp_to_load;
1261         boost::optional<string> _stress;
1262 };
1263
1264 IMPLEMENT_APP (App)