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