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