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