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