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