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