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