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