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