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