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