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