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