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