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