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