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