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