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