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