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