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