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