Remove player activity logging. Fixes #2122.
[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 "wx/nag_dialog.h"
37 #include "lib/cross.h"
38 #include "lib/config.h"
39 #include "lib/util.h"
40 #include "lib/internet.h"
41 #include "lib/update_checker.h"
42 #include "lib/compose.hpp"
43 #include "lib/dcp_content.h"
44 #include "lib/job_manager.h"
45 #include "lib/job.h"
46 #include "lib/film.h"
47 #include "lib/null_log.h"
48 #include "lib/video_content.h"
49 #include "lib/text_content.h"
50 #include "lib/ratio.h"
51 #include "lib/verify_dcp_job.h"
52 #include "lib/dcp_examiner.h"
53 #include "lib/examine_content_job.h"
54 #include "lib/server.h"
55 #include "lib/dcpomatic_socket.h"
56 #include "lib/scoped_temporary.h"
57 #include "lib/ffmpeg_content.h"
58 #include "lib/dcpomatic_log.h"
59 #include "lib/file_log.h"
60 #include <dcp/cpl.h>
61 #include <dcp/dcp.h>
62 #include <dcp/raw_convert.h>
63 #include <dcp/exceptions.h>
64 #include <wx/wx.h>
65 #include <wx/stdpaths.h>
66 #include <wx/splash.h>
67 #include <wx/cmdline.h>
68 #include <wx/preferences.h>
69 #include <wx/progdlg.h>
70 #include <wx/display.h>
71 #ifdef __WXGTK__
72 #include <X11/Xlib.h>
73 #endif
74 #include <boost/bind/bind.hpp>
75 #include <boost/algorithm/string.hpp>
76 #include <iostream>
77
78 #ifdef check
79 #undef check
80 #endif
81
82 #define MAX_CPLS 32
83
84 using std::cout;
85 using std::dynamic_pointer_cast;
86 using std::exception;
87 using std::list;
88 using std::make_shared;
89 using std::shared_ptr;
90 using std::string;
91 using std::vector;
92 using std::weak_ptr;
93 using boost::scoped_array;
94 using boost::optional;
95 using boost::thread;
96 using boost::bind;
97 #if BOOST_VERSION >= 106100
98 using namespace boost::placeholders;
99 #endif
100 using dcp::raw_convert;
101 using namespace dcpomatic;
102
103 enum {
104         ID_file_open = 1,
105         ID_file_add_ov,
106         ID_file_add_kdm,
107         ID_file_history,
108         /* Allow spare IDs after _history for the recent files list */
109         ID_file_close = 100,
110         ID_view_cpl,
111         /* Allow spare IDs for CPLs */
112         ID_view_full_screen = 200,
113         ID_view_dual_screen,
114         ID_view_closed_captions,
115         ID_view_scale_appropriate,
116         ID_view_scale_full,
117         ID_view_scale_half,
118         ID_view_scale_quarter,
119         ID_help_report_a_problem,
120         ID_tools_verify,
121         ID_tools_check_for_updates,
122         ID_tools_timing,
123         ID_tools_system_information,
124         /* IDs for shortcuts (with no associated menu item) */
125         ID_start_stop,
126         ID_go_back_frame,
127         ID_go_forward_frame,
128         ID_go_back_small_amount,
129         ID_go_forward_small_amount,
130         ID_go_back_medium_amount,
131         ID_go_forward_medium_amount,
132         ID_go_back_large_amount,
133         ID_go_forward_large_amount,
134         ID_go_to_start,
135         ID_go_to_end
136 };
137
138 class DOMFrame : public wxFrame
139 {
140 public:
141         DOMFrame ()
142                 : wxFrame (nullptr, -1, _("DCP-o-matic Player"))
143                 , _mode (Config::instance()->player_mode())
144                 , _main_sizer (new wxBoxSizer(wxVERTICAL))
145         {
146                 dcpomatic_log = make_shared<NullLog>();
147
148 #if defined(DCPOMATIC_WINDOWS)
149                 maybe_open_console ();
150                 cout << "DCP-o-matic Player is starting." << "\n";
151 #endif
152
153                 auto bar = new wxMenuBar;
154                 setup_menu (bar);
155                 set_menu_sensitivity ();
156                 SetMenuBar (bar);
157
158 #ifdef DCPOMATIC_WINDOWS
159                 SetIcon (wxIcon (std_to_wx ("id")));
160 #endif
161
162                 _config_changed_connection = Config::instance()->Changed.connect (boost::bind (&DOMFrame::config_changed, this, _1));
163                 update_from_config (Config::PLAYER_DEBUG_LOG);
164
165                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_open, this), ID_file_open);
166                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_ov, this), ID_file_add_ov);
167                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_kdm, this), ID_file_add_kdm);
168                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_history, this, _1), ID_file_history, ID_file_history + HISTORY_SIZE);
169                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_close, this), ID_file_close);
170                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this), wxID_EXIT);
171                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this), wxID_PREFERENCES);
172                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_full_screen, this), ID_view_full_screen);
173                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_dual_screen, this), ID_view_dual_screen);
174                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_closed_captions, this), ID_view_closed_captions);
175                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_cpl, this, _1), ID_view_cpl, ID_view_cpl + MAX_CPLS);
176                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(0)), ID_view_scale_full);
177                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(1)), ID_view_scale_half);
178                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(2)), ID_view_scale_quarter);
179                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this), wxID_ABOUT);
180                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
181                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_verify, this), ID_tools_verify);
182                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_check_for_updates, this), ID_tools_check_for_updates);
183                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_timing, this), ID_tools_timing);
184                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_system_information, this), ID_tools_system_information);
185
186                 /* Use a panel as the only child of the Frame so that we avoid
187                    the dark-grey background on Windows.
188                 */
189                 _overall_panel = new wxPanel (this, wxID_ANY);
190
191                 _viewer = make_shared<FilmViewer>(_overall_panel);
192                 if (Config::instance()->player_mode() == Config::PLAYER_MODE_DUAL) {
193                         auto pc = new PlaylistControls (_overall_panel, _viewer);
194                         _controls = pc;
195                         pc->ResetFilm.connect (bind(&DOMFrame::reset_film_weak, this, _1));
196                 } else {
197                         _controls = new StandardControls (_overall_panel, _viewer, false);
198                 }
199                 _viewer->set_dcp_decode_reduction (Config::instance()->decode_reduction ());
200                 _viewer->set_optimise_for_j2k (true);
201                 _viewer->PlaybackPermitted.connect (bind(&DOMFrame::playback_permitted, this));
202                 _viewer->TooManyDropped.connect (bind(&DOMFrame::too_many_frames_dropped, this));
203                 _info = new PlayerInformation (_overall_panel, _viewer);
204                 setup_main_sizer (Config::instance()->player_mode());
205 #ifdef __WXOSX__
206                 int accelerators = 12;
207 #else
208                 int accelerators = 11;
209 #endif
210
211                 _stress.setup (this, _controls);
212
213                 std::vector<wxAcceleratorEntry> accel(accelerators);
214                 accel[0].Set(wxACCEL_NORMAL,                WXK_SPACE, ID_start_stop);
215                 accel[1].Set(wxACCEL_NORMAL,                WXK_LEFT,  ID_go_back_frame);
216                 accel[2].Set(wxACCEL_NORMAL,                WXK_RIGHT, ID_go_forward_frame);
217                 accel[3].Set(wxACCEL_SHIFT,                 WXK_LEFT,  ID_go_back_small_amount);
218                 accel[4].Set(wxACCEL_SHIFT,                 WXK_RIGHT, ID_go_forward_small_amount);
219                 accel[5].Set(wxACCEL_CTRL,                  WXK_LEFT,  ID_go_back_medium_amount);
220                 accel[6].Set(wxACCEL_CTRL,                  WXK_RIGHT, ID_go_forward_medium_amount);
221                 accel[7].Set(wxACCEL_SHIFT | wxACCEL_CTRL,  WXK_LEFT,  ID_go_back_large_amount);
222                 accel[8].Set(wxACCEL_SHIFT | wxACCEL_CTRL,  WXK_RIGHT, ID_go_forward_large_amount);
223                 accel[9].Set(wxACCEL_NORMAL,                WXK_HOME,  ID_go_to_start);
224                 accel[10].Set(wxACCEL_NORMAL,               WXK_END,   ID_go_to_end);
225 #ifdef __WXOSX__
226                 accel[11].Set(wxACCEL_CTRL, static_cast<int>('W'), ID_file_close);
227 #endif
228                 wxAcceleratorTable accel_table (accelerators, accel.data());
229                 SetAcceleratorTable (accel_table);
230
231                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::start_stop_pressed, this), ID_start_stop);
232                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_back_frame, this),      ID_go_back_frame);
233                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_forward_frame, this),   ID_go_forward_frame);
234                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,   -60), ID_go_back_small_amount);
235                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,    60), ID_go_forward_small_amount);
236                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,  -600), ID_go_back_medium_amount);
237                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,   600), ID_go_forward_medium_amount);
238                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this, -3600), ID_go_back_large_amount);
239                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,  3600), ID_go_forward_large_amount);
240                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_to_start, this), ID_go_to_start);
241                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_to_end,   this), ID_go_to_end);
242
243                 reset_film ();
244
245                 UpdateChecker::instance()->StateChanged.connect (boost::bind(&DOMFrame::update_checker_state_changed, this));
246                 setup_screen ();
247
248                 _stress.LoadDCP.connect (boost::bind(&DOMFrame::load_dcp, this, _1));
249         }
250
251         ~DOMFrame ()
252         {
253                 /* It's important that this is stopped before our frame starts destroying its children,
254                  * otherwise UI elements that it depends on will disappear from under it.
255                  */
256                 _viewer.reset ();
257         }
258
259         void setup_main_sizer (Config::PlayerMode mode)
260         {
261                 _main_sizer->Detach (_viewer->panel());
262                 _main_sizer->Detach (_controls);
263                 _main_sizer->Detach (_info);
264                 if (mode != Config::PLAYER_MODE_DUAL) {
265                         _main_sizer->Add (_viewer->panel(), 1, wxEXPAND);
266                 }
267                 _main_sizer->Add (_controls, mode == Config::PLAYER_MODE_DUAL ? 1 : 0, wxEXPAND | wxALL, 6);
268                 _main_sizer->Add (_info, 0, wxEXPAND | wxALL, 6);
269                 _overall_panel->SetSizer (_main_sizer);
270                 _overall_panel->Layout ();
271         }
272
273         bool playback_permitted ()
274         {
275                 if (!_film || !Config::instance()->respect_kdm_validity_periods()) {
276                         return true;
277                 }
278
279                 bool ok = true;
280                 for (auto i: _film->content()) {
281                         auto d = dynamic_pointer_cast<DCPContent>(i);
282                         if (d && !d->kdm_timing_window_valid()) {
283                                 ok = false;
284                         }
285                 }
286
287                 if (!ok) {
288                         error_dialog (this, _("The KDM does not allow playback of this content at this time."));
289                 }
290
291                 return ok;
292         }
293
294
295         void too_many_frames_dropped ()
296         {
297                 if (!Config::instance()->nagged(Config::NAG_TOO_MANY_DROPPED_FRAMES)) {
298                         _viewer->stop ();
299                 }
300
301                 NagDialog::maybe_nag (
302                         this,
303                         Config::NAG_TOO_MANY_DROPPED_FRAMES,
304                         _(wxS("The player is dropping a lot of frames, so playback may not be accurate.\n\n"
305                           "<b>This does not necessarily mean that the DCP you are playing is defective!</b>\n\n"
306                           "You may be able to improve player performance by:\n"
307                           "• choosing 'decode at half resolution' or 'decode at quarter resolution' from the View menu\n"
308                           "• using a more powerful computer.\n"
309                          ))
310                         );
311         }
312
313         void set_decode_reduction (optional<int> reduction)
314         {
315                 _viewer->set_dcp_decode_reduction (reduction);
316                 _info->triggered_update ();
317                 Config::instance()->set_decode_reduction (reduction);
318         }
319
320         void load_dcp (boost::filesystem::path dir)
321         {
322                 DCPOMATIC_ASSERT (_film);
323
324                 reset_film ();
325                 try {
326                         _stress.set_suspended (true);
327                         // here
328                         auto dcp = make_shared<DCPContent>(dir);
329                         auto job = make_shared<ExamineContentJob>(_film, dcp);
330                         _examine_job_connection = job->Finished.connect(bind(&DOMFrame::add_dcp_to_film, this, weak_ptr<Job>(job), weak_ptr<Content>(dcp)));
331                         JobManager::instance()->add (job);
332                         bool const ok = display_progress (_("DCP-o-matic Player"), _("Loading content"));
333                         if (!ok || !report_errors_from_last_job(this)) {
334                                 return;
335                         }
336                         Config::instance()->add_to_player_history (dir);
337                 } catch (ProjectFolderError &) {
338                         error_dialog (
339                                 this,
340                                 wxString::Format(_("Could not load a DCP from %s"), std_to_wx(dir.string())),
341                                 _(
342                                         "This looks like a DCP-o-matic project folder, which cannot be loaded into the player.  "
343                                         "Choose the DCP directory inside the DCP-o-matic project folder if that's what you want to play."
344                                  )
345                                 );
346                 } catch (dcp::ReadError& e) {
347                         error_dialog (this, wxString::Format(_("Could not load a DCP from %s"), std_to_wx(dir.string())), std_to_wx(e.what()));
348                 } catch (DCPError& e) {
349                         error_dialog (this, wxString::Format(_("Could not load a DCP from %s"), std_to_wx(dir.string())), std_to_wx(e.what()));
350                 }
351         }
352
353         void add_dcp_to_film (weak_ptr<Job> weak_job, weak_ptr<Content> weak_content)
354         {
355                 auto job = weak_job.lock ();
356                 if (!job || !job->finished_ok()) {
357                         return;
358                 }
359
360                 auto content = weak_content.lock ();
361                 if (!content) {
362                         return;
363                 }
364
365                 _film->add_content (content);
366                 _stress.set_suspended (false);
367         }
368
369         void reset_film_weak (weak_ptr<Film> weak_film)
370         {
371                 auto film = weak_film.lock ();
372                 if (film) {
373                         reset_film (film);
374                 }
375         }
376
377         void reset_film (shared_ptr<Film> film = shared_ptr<Film>(new Film(optional<boost::filesystem::path>())))
378         {
379                 _film = film;
380                 _film->set_tolerant (true);
381                 _film->set_audio_channels (MAX_DCP_AUDIO_CHANNELS);
382                 _viewer->set_film (_film);
383                 _controls->set_film (_film);
384                 _film->Change.connect (bind(&DOMFrame::film_changed, this, _1, _2));
385                 _info->triggered_update ();
386         }
387
388         void film_changed (ChangeType type, Film::Property property)
389         {
390                 if (type != ChangeType::DONE || property != Film::Property::CONTENT) {
391                         return;
392                 }
393
394                 if (_viewer->playing ()) {
395                         _viewer->stop ();
396                 }
397
398                 /* Start off as Flat */
399                 _film->set_container (Ratio::from_id("185"));
400
401                 for (auto i: _film->content()) {
402                         auto dcp = dynamic_pointer_cast<DCPContent>(i);
403
404                         for (auto j: i->text) {
405                                 j->set_use (true);
406                         }
407
408                         if (i->video) {
409                                 auto const r = Ratio::nearest_from_ratio(i->video->size().ratio());
410                                 if (r->id() == "239") {
411                                         /* Any scope content means we use scope */
412                                         _film->set_container(r);
413                                 }
414                         }
415
416                         /* Any 3D content means we use 3D mode */
417                         if (i->video && i->video->frame_type() != VideoFrameType::TWO_D) {
418                                 _film->set_three_d (true);
419                         }
420                 }
421
422                 _viewer->seek (DCPTime(), true);
423                 _info->triggered_update ();
424
425                 set_menu_sensitivity ();
426
427                 auto old = _cpl_menu->GetMenuItems();
428                 for (auto const& i: old) {
429                         _cpl_menu->Remove (i);
430                 }
431
432                 if (_film->content().size() == 1) {
433                         /* Offer a CPL menu */
434                         auto first = dynamic_pointer_cast<DCPContent>(_film->content().front());
435                         if (first) {
436                                 DCPExaminer ex (first, true);
437                                 int id = ID_view_cpl;
438                                 for (auto i: ex.cpls()) {
439                                         auto j = _cpl_menu->AppendRadioItem(
440                                                 id,
441                                                 wxString::Format("%s (%s)", std_to_wx(i->annotation_text().get_value_or("")).data(), std_to_wx(i->id()).data())
442                                                 );
443                                         j->Check(!first->cpl() || i->id() == *first->cpl());
444                                         ++id;
445                                 }
446                         }
447                 }
448         }
449
450         void load_stress_script (boost::filesystem::path path)
451         {
452                 _stress.load_script (path);
453         }
454
455 private:
456
457         void examine_content ()
458         {
459                 DCPOMATIC_ASSERT (_film);
460                 auto dcp = dynamic_pointer_cast<DCPContent>(_film->content().front());
461                 DCPOMATIC_ASSERT (dcp);
462                 dcp->examine (_film, shared_ptr<Job>());
463
464                 /* Examining content re-creates the TextContent objects, so we must re-enable them */
465                 for (auto i: dcp->text) {
466                         i->set_use (true);
467                 }
468         }
469
470         bool report_errors_from_last_job (wxWindow* parent) const
471         {
472                 auto jm = JobManager::instance ();
473
474                 DCPOMATIC_ASSERT (!jm->get().empty());
475
476                 auto last = jm->get().back();
477                 if (last->finished_in_error()) {
478                         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()));
479                         return false;
480                 }
481
482                 return true;
483         }
484
485         void setup_menu (wxMenuBar* m)
486         {
487                 _file_menu = new wxMenu;
488                 _file_menu->Append (ID_file_open, _("&Open...\tCtrl-O"));
489                 _file_add_ov = _file_menu->Append (ID_file_add_ov, _("&Add OV..."));
490                 _file_add_kdm = _file_menu->Append (ID_file_add_kdm, _("Add &KDM..."));
491
492                 _history_position = _file_menu->GetMenuItems().GetCount();
493
494                 _file_menu->AppendSeparator ();
495                 _file_menu->Append (ID_file_close, _("&Close"));
496                 _file_menu->AppendSeparator ();
497
498 #ifdef __WXOSX__
499                 _file_menu->Append (wxID_EXIT, _("&Exit"));
500 #else
501                 _file_menu->Append (wxID_EXIT, _("&Quit"));
502 #endif
503
504 #ifdef __WXOSX__
505                 auto prefs = _file_menu->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
506 #else
507                 auto edit = new wxMenu;
508                 auto prefs = edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
509 #endif
510
511                 prefs->Enable (Config::instance()->have_write_permission());
512
513                 _cpl_menu = new wxMenu;
514
515                 auto view = new wxMenu;
516                 auto c = Config::instance()->decode_reduction();
517                 _view_cpl = view->Append(ID_view_cpl, _("CPL"), _cpl_menu);
518                 view->AppendSeparator();
519                 _view_full_screen = view->AppendCheckItem(ID_view_full_screen, _("Full screen\tF11"));
520                 _view_dual_screen = view->AppendCheckItem(ID_view_dual_screen, _("Dual screen\tShift+F11"));
521                 setup_menu ();
522                 view->AppendSeparator();
523                 view->Append(ID_view_closed_captions, _("Closed captions..."));
524                 view->AppendSeparator();
525                 view->AppendRadioItem(ID_view_scale_appropriate, _("Set decode resolution to match display"))->Check(!static_cast<bool>(c));
526                 view->AppendRadioItem(ID_view_scale_full, _("Decode at full resolution"))->Check(c && c.get() == 0);
527                 view->AppendRadioItem(ID_view_scale_half, _("Decode at half resolution"))->Check(c && c.get() == 1);
528                 view->AppendRadioItem(ID_view_scale_quarter, _("Decode at quarter resolution"))->Check(c && c.get() == 2);
529
530                 auto tools = new wxMenu;
531                 _tools_verify = tools->Append (ID_tools_verify, _("Verify DCP..."));
532                 tools->AppendSeparator ();
533                 tools->Append (ID_tools_check_for_updates, _("Check for updates"));
534                 tools->Append (ID_tools_timing, _("Timing..."));
535                 tools->Append (ID_tools_system_information, _("System information..."));
536
537                 auto help = new wxMenu;
538 #ifdef __WXOSX__
539                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
540 #else
541                 help->Append (wxID_ABOUT, _("About"));
542 #endif
543                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
544
545                 m->Append (_file_menu, _("&File"));
546 #ifndef __WXOSX__
547                 m->Append (edit, _("&Edit"));
548 #endif
549                 m->Append (view, _("&View"));
550                 m->Append (tools, _("&Tools"));
551                 m->Append (help, _("&Help"));
552         }
553
554         void file_open ()
555         {
556                 auto d = wxStandardPaths::Get().GetDocumentsDir();
557                 if (Config::instance()->last_player_load_directory()) {
558                         d = std_to_wx (Config::instance()->last_player_load_directory()->string());
559                 }
560
561                 auto c = new wxDirDialog (this, _("Select DCP to open"), d, wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST);
562
563                 int r;
564                 while (true) {
565                         r = c->ShowModal ();
566                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
567                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
568                         } else {
569                                 break;
570                         }
571                 }
572
573                 if (r == wxID_OK) {
574                         boost::filesystem::path const dcp (wx_to_std (c->GetPath ()));
575                         load_dcp (dcp);
576                         Config::instance()->set_last_player_load_directory (dcp.parent_path());
577                 }
578
579                 c->Destroy ();
580         }
581
582         void file_add_ov ()
583         {
584                 auto c = new wxDirDialog (
585                         this,
586                         _("Select DCP to open as OV"),
587                         wxStandardPaths::Get().GetDocumentsDir(),
588                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
589                         );
590
591                 int r;
592                 while (true) {
593                         r = c->ShowModal ();
594                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
595                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
596                         } else {
597                                 break;
598                         }
599                 }
600
601                 if (r == wxID_OK) {
602                         DCPOMATIC_ASSERT (_film);
603                         auto dcp = std::dynamic_pointer_cast<DCPContent>(_film->content().front());
604                         DCPOMATIC_ASSERT (dcp);
605                         dcp->add_ov (wx_to_std(c->GetPath()));
606                         JobManager::instance()->add(make_shared<ExamineContentJob>(_film, dcp));
607                         bool const ok = display_progress (_("DCP-o-matic Player"), _("Loading content"));
608                         if (!ok || !report_errors_from_last_job(this)) {
609                                 return;
610                         }
611                         for (auto i: dcp->text) {
612                                 i->set_use (true);
613                         }
614                         if (dcp->video) {
615                                 auto const r = Ratio::nearest_from_ratio(dcp->video->size().ratio());
616                                 if (r) {
617                                         _film->set_container(r);
618                                 }
619                         }
620                 }
621
622                 c->Destroy ();
623                 _info->triggered_update ();
624         }
625
626         void file_add_kdm ()
627         {
628                 auto d = new wxFileDialog (this, _("Select KDM"));
629
630                 if (d->ShowModal() == wxID_OK) {
631                         DCPOMATIC_ASSERT (_film);
632                         auto dcp = std::dynamic_pointer_cast<DCPContent>(_film->content().front());
633                         DCPOMATIC_ASSERT (dcp);
634                         try {
635                                 if (dcp) {
636                                         _viewer->set_coalesce_player_changes (true);
637                                         dcp->add_kdm (dcp::EncryptedKDM(dcp::file_to_string(wx_to_std(d->GetPath()), MAX_KDM_SIZE)));
638                                         examine_content();
639                                         _viewer->set_coalesce_player_changes (false);
640                                 }
641                         } catch (exception& e) {
642                                 error_dialog (this, wxString::Format (_("Could not load KDM.")), std_to_wx(e.what()));
643                                 d->Destroy ();
644                                 return;
645                         }
646                 }
647
648                 d->Destroy ();
649                 _info->triggered_update ();
650         }
651
652         void file_history (wxCommandEvent& event)
653         {
654                 auto history = Config::instance()->player_history ();
655                 int n = event.GetId() - ID_file_history;
656                 if (n >= 0 && n < static_cast<int> (history.size ())) {
657                         try {
658                                 load_dcp (history[n]);
659                         } catch (exception& e) {
660                                 error_dialog (0, std_to_wx(String::compose(wx_to_std(_("Could not load DCP %1.")), history[n])), std_to_wx(e.what()));
661                         }
662                 }
663         }
664
665         void file_close ()
666         {
667                 reset_film ();
668                 _info->triggered_update ();
669                 set_menu_sensitivity ();
670         }
671
672         void file_exit ()
673         {
674                 Close ();
675         }
676
677         void edit_preferences ()
678         {
679                 if (!Config::instance()->have_write_permission()) {
680                         return;
681                 }
682
683                 if (!_config_dialog) {
684                         _config_dialog = create_player_config_dialog ();
685                 }
686                 _config_dialog->Show (this);
687         }
688
689         void view_cpl (wxCommandEvent& ev)
690         {
691                 auto dcp = std::dynamic_pointer_cast<DCPContent>(_film->content().front());
692                 DCPOMATIC_ASSERT (dcp);
693                 DCPExaminer ex (dcp, true);
694                 int id = ev.GetId() - ID_view_cpl;
695                 DCPOMATIC_ASSERT (id >= 0);
696                 DCPOMATIC_ASSERT (id < int(ex.cpls().size()));
697                 auto cpls = ex.cpls();
698                 auto i = cpls.begin();
699                 while (id > 0) {
700                         ++i;
701                         --id;
702                 }
703
704                 _viewer->set_coalesce_player_changes (true);
705                 dcp->set_cpl ((*i)->id());
706                 examine_content ();
707                 _viewer->set_coalesce_player_changes (false);
708
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::State::YES) {
859                         auto dialog = new UpdateDialog (this, uc->stable (), uc->test ());
860                         dialog->ShowModal ();
861                         dialog->Destroy ();
862                 } else if (uc->state() == UpdateChecker::State::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 = nullptr;
984         bool _update_news_requested = false;
985         PlayerInformation* _info = nullptr;
986         Config::PlayerMode _mode;
987         wxPreferencesEditor* _config_dialog = nullptr;
988         wxPanel* _overall_panel = nullptr;
989         wxMenu* _file_menu = nullptr;
990         wxMenuItem* _view_cpl = nullptr;
991         wxMenu* _cpl_menu = nullptr;
992         int _history_items = 0;
993         int _history_position = 0;
994         wxMenuItem* _history_separator = nullptr;
995         shared_ptr<FilmViewer> _viewer;
996         Controls* _controls;
997         SystemInformationDialog* _system_information_dialog = nullptr;
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 = nullptr;
1002         wxMenuItem* _file_add_kdm = nullptr;
1003         wxMenuItem* _tools_verify = nullptr;
1004         wxMenuItem* _view_full_screen = nullptr;
1005         wxMenuItem* _view_dual_screen = nullptr;
1006         wxSizer* _main_sizer = nullptr;
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         {
1052 #ifdef DCPOMATIC_LINUX
1053                 XInitThreads ();
1054 #endif
1055         }
1056
1057 private:
1058
1059         bool OnInit ()
1060         {
1061                 wxSplashScreen* splash = nullptr;
1062                 try {
1063                         wxInitAllImageHandlers ();
1064
1065                         Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
1066                         Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
1067
1068                         splash = maybe_show_splash ();
1069
1070                         SetAppName (_("DCP-o-matic Player"));
1071
1072                         if (!wxApp::OnInit()) {
1073                                 return false;
1074                         }
1075
1076 #ifdef DCPOMATIC_LINUX
1077                         unsetenv ("UBUNTU_MENUPROXY");
1078 #endif
1079
1080 #ifdef DCPOMATIC_OSX
1081                         make_foreground_application ();
1082 #endif
1083
1084                         dcpomatic_setup_path_encoding ();
1085
1086                         /* Enable i18n; this will create a Config object
1087                            to look for a force-configured language.  This Config
1088                            object will be wrong, however, because dcpomatic_setup
1089                            hasn't yet been called and there aren't any filters etc.
1090                            set up yet.
1091                         */
1092                         dcpomatic_setup_i18n ();
1093
1094                         /* Set things up, including filters etc.
1095                            which will now be internationalised correctly.
1096                         */
1097                         dcpomatic_setup ();
1098
1099                         /* Force the configuration to be re-loaded correctly next
1100                            time it is needed.
1101                         */
1102                         Config::drop ();
1103
1104                         signal_manager = new wxSignalManager (this);
1105
1106                         _frame = new DOMFrame ();
1107                         SetTopWindow (_frame);
1108                         _frame->Maximize ();
1109                         if (splash) {
1110                                 splash->Destroy ();
1111                                 splash = nullptr;
1112                         }
1113                         _frame->Show ();
1114
1115                         try {
1116                                 auto server = new PlayServer (_frame);
1117                                 new thread (boost::bind (&PlayServer::run, server));
1118                         } catch (std::exception& e) {
1119                                 /* This is not the end of the world; probably a failure to bind the server socket
1120                                  * because there's already another player running.
1121                                  */
1122                                 LOG_DEBUG_PLAYER ("Failed to start play server (%1)", e.what());
1123                         }
1124
1125                         if (!_dcp_to_load.empty() && boost::filesystem::is_directory (_dcp_to_load)) {
1126                                 try {
1127                                         _frame->load_dcp (_dcp_to_load);
1128                                 } catch (exception& e) {
1129                                         error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load DCP %1.")), _dcp_to_load)), std_to_wx(e.what()));
1130                                 }
1131                         }
1132
1133                         if (_stress) {
1134                                 try {
1135                                         _frame->load_stress_script (*_stress);
1136                                 } catch (exception& e) {
1137                                         error_dialog (0, wxString::Format("Could not load stress test file %s", std_to_wx(*_stress)));
1138                                 }
1139                         }
1140
1141                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
1142
1143                         if (Config::instance()->check_for_updates ()) {
1144                                 UpdateChecker::instance()->run ();
1145                         }
1146                 }
1147                 catch (exception& e)
1148                 {
1149                         if (splash) {
1150                                 splash->Destroy ();
1151                         }
1152                         error_dialog (0, _("DCP-o-matic Player could not start."), std_to_wx(e.what()));
1153                 }
1154
1155                 return true;
1156         }
1157
1158         void OnInitCmdLine (wxCmdLineParser& parser)
1159         {
1160                 parser.SetDesc (command_line_description);
1161                 parser.SetSwitchChars (wxT ("-"));
1162         }
1163
1164         bool OnCmdLineParsed (wxCmdLineParser& parser)
1165         {
1166                 if (parser.GetParamCount() > 0) {
1167                         _dcp_to_load = wx_to_std (parser.GetParam (0));
1168                 }
1169
1170                 wxString config;
1171                 if (parser.Found("c", &config)) {
1172                         Config::override_path = wx_to_std (config);
1173                 }
1174                 wxString stress;
1175                 if (parser.Found("s", &stress)) {
1176                         _stress = wx_to_std (stress);
1177                 }
1178
1179                 return true;
1180         }
1181
1182         void report_exception ()
1183         {
1184                 try {
1185                         throw;
1186                 } catch (FileError& e) {
1187                         error_dialog (
1188                                 0,
1189                                 wxString::Format (
1190                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
1191                                         std_to_wx (e.what()),
1192                                         std_to_wx (e.file().string().c_str ())
1193                                         )
1194                                 );
1195                 } catch (exception& e) {
1196                         error_dialog (
1197                                 0,
1198                                 wxString::Format (
1199                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
1200                                         std_to_wx (e.what ())
1201                                         )
1202                                 );
1203                 } catch (...) {
1204                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
1205                 }
1206         }
1207
1208         /* An unhandled exception has occurred inside the main event loop */
1209         bool OnExceptionInMainLoop ()
1210         {
1211                 report_exception ();
1212                 /* This will terminate the program */
1213                 return false;
1214         }
1215
1216         void OnUnhandledException ()
1217         {
1218                 report_exception ();
1219         }
1220
1221         void idle ()
1222         {
1223                 signal_manager->ui_idle ();
1224         }
1225
1226         void config_failed_to_load ()
1227         {
1228                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
1229         }
1230
1231         void config_warning (string m)
1232         {
1233                 message_dialog (_frame, std_to_wx (m));
1234         }
1235
1236         DOMFrame* _frame = nullptr;
1237         string _dcp_to_load;
1238         boost::optional<string> _stress;
1239 };
1240
1241 IMPLEMENT_APP (App)