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