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