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