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