Disable preferences menu if the config can't be written.
[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         optional<dcp::EncryptedKDM> get_kdm_from_url (shared_ptr<DCPContent> dcp)
304         {
305                 ScopedTemporary temp;
306                 string url = Config::instance()->kdm_server_url();
307                 boost::algorithm::replace_all (url, "{CPL}", *dcp->cpl());
308                 optional<dcp::EncryptedKDM> kdm;
309                 if (dcp->cpl() && !get_from_url(url, false, temp)) {
310                         try {
311                                 kdm = dcp::EncryptedKDM (dcp::file_to_string(temp.file()));
312                                 if (kdm->cpl_id() != dcp->cpl()) {
313                                         kdm = boost::none;
314                                 }
315                         } catch (std::exception& e) {
316                                 /* Hey well */
317                         }
318                 }
319                 return kdm;
320         }
321
322         optional<dcp::EncryptedKDM> get_kdm_from_directory (shared_ptr<DCPContent> dcp)
323         {
324                 using namespace boost::filesystem;
325                 optional<path> kdm_dir = Config::instance()->player_kdm_directory();
326                 if (!kdm_dir) {
327                         return optional<dcp::EncryptedKDM>();
328                 }
329                 for (directory_iterator i = directory_iterator(*kdm_dir); i != directory_iterator(); ++i) {
330                         if (file_size(i->path()) < MAX_KDM_SIZE) {
331                                 try {
332                                         dcp::EncryptedKDM kdm (dcp::file_to_string(i->path()));
333                                         if (kdm.cpl_id() == dcp->cpl()) {
334                                                 return kdm;
335                                         }
336                                 } catch (std::exception& e) {
337                                         /* Hey well */
338                                 }
339                         }
340                 }
341                 return optional<dcp::EncryptedKDM>();
342         }
343
344         void set_spl (list<SPLEntry> spl)
345         {
346                 if (_viewer->playing ()) {
347                         _viewer->stop ();
348                 }
349
350                 _film.reset (new Film (optional<boost::filesystem::path>()));
351
352                 if (spl.empty ()) {
353                         _viewer->set_film (_film);
354                         _info->triggered_update ();
355                         return;
356                 }
357
358                 /* Start off as Flat */
359                 _film->set_container (Ratio::from_id("185"));
360
361                 DCPTime position;
362                 shared_ptr<DCPContent> first;
363
364                 BOOST_FOREACH (SPLEntry i, spl) {
365                         shared_ptr<DCPContent> dcp;
366                         try {
367                                 dcp.reset (new DCPContent (_film, i.dcp));
368                         } catch (boost::filesystem::filesystem_error& e) {
369                                 error_dialog (this, _("Could not load DCP"), std_to_wx (e.what()));
370                                 return;
371                         }
372
373                         if (!first) {
374                                 first = dcp;
375                         }
376
377                         _film->examine_and_add_content (dcp, true);
378                         bool const ok = progress (_("Loading DCP"));
379                         if (!ok || !report_errors_from_last_job()) {
380                                 return;
381                         }
382
383                         dcp->set_position (position + i.black_before);
384                         position += dcp->length_after_trim() + i.black_before;
385
386                         /* This DCP has been examined and loaded */
387
388                         if (dcp->needs_kdm()) {
389                                 optional<dcp::EncryptedKDM> kdm;
390 #ifdef DCPOMATIC_VARIANT_SWAROOP
391                                 kdm = get_kdm_from_url (dcp);
392 #endif
393                                 if (!kdm) {
394                                         get_kdm_from_directory (dcp);
395                                 }
396
397                                 if (kdm) {
398                                         dcp->add_kdm (*kdm);
399                                         dcp->examine (shared_ptr<Job>());
400                                 }
401                         }
402
403                         BOOST_FOREACH (shared_ptr<TextContent> j, dcp->text) {
404                                 j->set_use (true);
405                         }
406
407                         if (dcp->video) {
408                                 Ratio const * r = Ratio::nearest_from_ratio(dcp->video->size().ratio());
409                                 if (r->id() == "239") {
410                                         /* Any scope content means we use scope */
411                                         _film->set_container(r);
412                                 }
413                         }
414
415                         /* Any 3D content means we use 3D mode */
416                         if (dcp->three_d()) {
417                                 _film->set_three_d (true);
418                         }
419
420                         _viewer->set_film (_film);
421                         _viewer->seek (DCPTime(), true);
422                         _info->triggered_update ();
423
424                         set_menu_sensitivity ();
425                         _controls->log (wxString::Format(_("Load DCP %s"), i.dcp.filename().string().c_str()));
426                 }
427
428                 wxMenuItemList old = _cpl_menu->GetMenuItems();
429                 for (wxMenuItemList::iterator i = old.begin(); i != old.end(); ++i) {
430                         _cpl_menu->Remove (*i);
431                 }
432
433                 if (spl.size() == 1) {
434                         /* Offer a CPL menu */
435                         DCPExaminer ex (first);
436                         int id = ID_view_cpl;
437                         BOOST_FOREACH (shared_ptr<dcp::CPL> i, ex.cpls()) {
438                                 wxMenuItem* j = _cpl_menu->AppendRadioItem(
439                                         id,
440                                         wxString::Format("%s (%s)", std_to_wx(i->annotation_text()).data(), std_to_wx(i->id()).data())
441                                         );
442                                 j->Check(!first->cpl() || i->id() == *first->cpl());
443                                 ++id;
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 = progress (_("Loading DCP"));
573                         if (!ok || !report_errors_from_last_job()) {
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 (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                         load_dcp (history[n]);
619                 }
620         }
621
622         void file_close ()
623         {
624                 _viewer->set_film (shared_ptr<Film>());
625                 _film.reset ();
626                 _info->triggered_update ();
627                 set_menu_sensitivity ();
628         }
629
630         void file_exit ()
631         {
632                 Close ();
633         }
634
635         void edit_preferences ()
636         {
637                 if (!Config::instance()->have_write_permission()) {
638                         return;
639                 }
640
641                 if (!_config_dialog) {
642                         _config_dialog = create_player_config_dialog ();
643                 }
644                 _config_dialog->Show (this);
645         }
646
647         void view_cpl (wxCommandEvent& ev)
648         {
649                 shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
650                 DCPOMATIC_ASSERT (dcp);
651                 DCPExaminer ex (dcp);
652                 int id = ev.GetId() - ID_view_cpl;
653                 DCPOMATIC_ASSERT (id >= 0);
654                 DCPOMATIC_ASSERT (id < int(ex.cpls().size()));
655                 list<shared_ptr<dcp::CPL> > cpls = ex.cpls();
656                 list<shared_ptr<dcp::CPL> >::iterator i = cpls.begin();
657                 while (id > 0) {
658                         ++i;
659                         --id;
660                 }
661
662                 dcp->set_cpl ((*i)->id());
663                 dcp->examine (shared_ptr<Job>());
664         }
665
666         void view_full_screen ()
667         {
668                 if (_mode == Config::PLAYER_MODE_FULL) {
669                         _mode = Config::PLAYER_MODE_WINDOW;
670                 } else {
671                         _mode = Config::PLAYER_MODE_FULL;
672                 }
673                 setup_screen ();
674                 setup_menu ();
675         }
676
677         void view_dual_screen ()
678         {
679                 if (_mode == Config::PLAYER_MODE_DUAL) {
680                         _mode = Config::PLAYER_MODE_WINDOW;
681                 } else {
682                         _mode = Config::PLAYER_MODE_DUAL;
683                 }
684                 setup_screen ();
685                 setup_menu ();
686         }
687
688         void setup_menu ()
689         {
690                 if (_view_full_screen) {
691                         _view_full_screen->Check (_mode == Config::PLAYER_MODE_FULL);
692                 }
693                 if (_view_dual_screen) {
694                         _view_dual_screen->Check (_mode == Config::PLAYER_MODE_DUAL);
695                 }
696         }
697
698         void setup_screen ()
699         {
700                 _controls->Show (_mode != Config::PLAYER_MODE_FULL);
701                 _controls->show_extended_player_controls (_mode == Config::PLAYER_MODE_DUAL);
702                 _info->Show (_mode != Config::PLAYER_MODE_FULL);
703                 _overall_panel->SetBackgroundColour (_mode == Config::PLAYER_MODE_FULL ? wxColour(0, 0, 0) : wxNullColour);
704                 ShowFullScreen (_mode == Config::PLAYER_MODE_FULL);
705
706                 if (_mode == Config::PLAYER_MODE_DUAL) {
707                         _dual_screen = new wxFrame (this, wxID_ANY, wxT(""));
708                         _dual_screen->SetBackgroundColour (wxColour(0, 0, 0));
709                         _dual_screen->ShowFullScreen (true);
710                         _viewer->panel()->Reparent (_dual_screen);
711                         _dual_screen->Show ();
712                         if (wxDisplay::GetCount() > 1) {
713                                 switch (Config::instance()->image_display()) {
714                                 case 0:
715                                         _dual_screen->Move (0, 0);
716                                         Move (wxDisplay(0).GetClientArea().GetWidth(), 0);
717                                         break;
718                                 case 1:
719                                         _dual_screen->Move (wxDisplay(0).GetClientArea().GetWidth(), 0);
720                                         // (0, 0) doesn't seem to work for some strange reason
721                                         Move (8, 8);
722                                         break;
723                                 }
724                         }
725                 } else {
726                         if (_dual_screen) {
727                                 _viewer->panel()->Reparent (_overall_panel);
728                                 _dual_screen->Destroy ();
729                                 _dual_screen = 0;
730                         }
731                 }
732
733                 setup_main_sizer (_mode);
734         }
735
736         void view_closed_captions ()
737         {
738                 _viewer->show_closed_captions ();
739         }
740
741         void tools_verify ()
742         {
743                 shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
744                 DCPOMATIC_ASSERT (dcp);
745
746                 JobManager* jm = JobManager::instance ();
747                 jm->add (shared_ptr<Job> (new VerifyDCPJob (dcp->directories())));
748                 bool const ok = progress (_("Verifying DCP"));
749                 if (!ok) {
750                         return;
751                 }
752
753                 DCPOMATIC_ASSERT (!jm->get().empty());
754                 shared_ptr<VerifyDCPJob> last = dynamic_pointer_cast<VerifyDCPJob> (jm->get().back());
755                 DCPOMATIC_ASSERT (last);
756
757                 VerifyDCPDialog* d = new VerifyDCPDialog (this, last);
758                 d->ShowModal ();
759                 d->Destroy ();
760         }
761
762         void tools_check_for_updates ()
763         {
764                 UpdateChecker::instance()->run ();
765                 _update_news_requested = true;
766         }
767
768         void help_about ()
769         {
770                 AboutDialog* d = new AboutDialog (this);
771                 d->ShowModal ();
772                 d->Destroy ();
773         }
774
775         void help_report_a_problem ()
776         {
777                 ReportProblemDialog* d = new ReportProblemDialog (this);
778                 if (d->ShowModal () == wxID_OK) {
779                         d->report ();
780                 }
781                 d->Destroy ();
782         }
783
784         void update_checker_state_changed ()
785         {
786                 UpdateChecker* uc = UpdateChecker::instance ();
787
788                 bool const announce =
789                         _update_news_requested ||
790                         (uc->stable() && Config::instance()->check_for_updates()) ||
791                         (uc->test() && Config::instance()->check_for_updates() && Config::instance()->check_for_test_updates());
792
793                 _update_news_requested = false;
794
795                 if (!announce) {
796                         return;
797                 }
798
799                 if (uc->state() == UpdateChecker::YES) {
800                         UpdateDialog* dialog = new UpdateDialog (this, uc->stable (), uc->test ());
801                         dialog->ShowModal ();
802                         dialog->Destroy ();
803                 } else if (uc->state() == UpdateChecker::FAILED) {
804                         error_dialog (this, _("The DCP-o-matic download server could not be contacted."));
805                 } else {
806                         error_dialog (this, _("There are no new versions of DCP-o-matic available."));
807                 }
808
809                 _update_news_requested = false;
810         }
811
812         void config_changed ()
813         {
814                 /* Instantly save any config changes when using the player GUI */
815                 try {
816                         Config::instance()->write_config();
817                 } catch (FileError& e) {
818                         error_dialog (
819                                 this,
820                                 wxString::Format(
821                                         _("Could not write to config file at %s.  Your changes have not been saved."),
822                                         std_to_wx(e.file().string())
823                                         )
824                                 );
825                 } catch (exception& e) {
826                         error_dialog (
827                                 this,
828                                 _("Could not write to config file.  Your changes have not been saved.")
829                                 );
830                 }
831
832                 update_from_config ();
833         }
834
835         void update_from_config ()
836         {
837                 for (int i = 0; i < _history_items; ++i) {
838                         delete _file_menu->Remove (ID_file_history + i);
839                 }
840
841                 if (_history_separator) {
842                         _file_menu->Remove (_history_separator);
843                 }
844                 delete _history_separator;
845                 _history_separator = 0;
846
847                 int pos = _history_position;
848
849                 vector<boost::filesystem::path> history = Config::instance()->player_history ();
850
851                 if (!history.empty ()) {
852                         _history_separator = _file_menu->InsertSeparator (pos++);
853                 }
854
855                 for (size_t i = 0; i < history.size(); ++i) {
856                         string s;
857                         if (i < 9) {
858                                 s = String::compose ("&%1 %2", i + 1, history[i].string());
859                         } else {
860                                 s = history[i].string();
861                         }
862                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s));
863                 }
864
865                 _history_items = history.size ();
866         }
867
868         void set_menu_sensitivity ()
869         {
870                 _tools_verify->Enable (static_cast<bool>(_film));
871                 _file_add_ov->Enable (static_cast<bool>(_film));
872                 _file_add_kdm->Enable (static_cast<bool>(_film));
873                 _view_cpl->Enable (static_cast<bool>(_film));
874         }
875
876         void start_stop_pressed ()
877         {
878                 if (_viewer->playing()) {
879                         _viewer->stop();
880                 } else {
881                         _viewer->start();
882                 }
883         }
884
885         void back_frame ()
886         {
887                 _viewer->seek_by (-_viewer->one_video_frame(), true);
888         }
889
890         void forward_frame ()
891         {
892                 _viewer->seek_by (_viewer->one_video_frame(), true);
893         }
894
895 private:
896
897         /** @return false if the task was cancelled */
898         bool progress (wxString task)
899         {
900                 JobManager* jm = JobManager::instance ();
901
902                 wxProgressDialog* progress = new wxProgressDialog (_("DCP-o-matic Player"), task, 100, 0, wxPD_CAN_ABORT);
903
904                 bool ok = true;
905
906                 while (jm->work_to_do() || signal_manager->ui_idle()) {
907                         dcpomatic_sleep (1);
908                         if (!progress->Pulse()) {
909                                 /* user pressed cancel */
910                                 BOOST_FOREACH (shared_ptr<Job> i, jm->get()) {
911                                         i->cancel();
912                                 }
913                                 ok = false;
914                                 break;
915                         }
916                 }
917
918                 progress->Destroy ();
919                 return ok;
920         }
921
922         bool report_errors_from_last_job ()
923         {
924                 JobManager* jm = JobManager::instance ();
925
926                 DCPOMATIC_ASSERT (!jm->get().empty());
927
928                 shared_ptr<Job> last = jm->get().back();
929                 if (last->finished_in_error()) {
930                         error_dialog(this, std_to_wx(last->error_summary()) + ".\n", std_to_wx(last->error_details()));
931                         return false;
932                 }
933
934                 return true;
935         }
936
937         wxFrame* _dual_screen;
938         bool _update_news_requested;
939         PlayerInformation* _info;
940         Config::PlayerMode _mode;
941         wxPreferencesEditor* _config_dialog;
942         wxPanel* _overall_panel;
943         wxMenu* _file_menu;
944         wxMenuItem* _view_cpl;
945         wxMenu* _cpl_menu;
946         int _history_items;
947         int _history_position;
948         wxMenuItem* _history_separator;
949         shared_ptr<FilmViewer> _viewer;
950         Controls* _controls;
951         boost::shared_ptr<Film> _film;
952         boost::signals2::scoped_connection _config_changed_connection;
953         wxMenuItem* _file_add_ov;
954         wxMenuItem* _file_add_kdm;
955         wxMenuItem* _tools_verify;
956         wxMenuItem* _view_full_screen;
957         wxMenuItem* _view_dual_screen;
958 };
959
960 static const wxCmdLineEntryDesc command_line_description[] = {
961         { wxCMD_LINE_PARAM, 0, 0, "DCP to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
962         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
963 };
964
965 class PlayServer : public Server
966 {
967 public:
968         explicit PlayServer (DOMFrame* frame)
969                 : Server (PLAYER_PLAY_PORT)
970                 , _frame (frame)
971         {}
972
973         void handle (shared_ptr<Socket> socket)
974         {
975                 try {
976                         int const length = socket->read_uint32 ();
977                         scoped_array<char> buffer (new char[length]);
978                         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
979                         string s (buffer.get());
980                         signal_manager->when_idle (bind (&DOMFrame::load_dcp, _frame, s));
981                         socket->write (reinterpret_cast<uint8_t const *> ("OK"), 3);
982                 } catch (...) {
983
984                 }
985         }
986
987 private:
988         DOMFrame* _frame;
989 };
990
991 /** @class App
992  *  @brief The magic App class for wxWidgets.
993  */
994 class App : public wxApp
995 {
996 public:
997         App ()
998                 : wxApp ()
999                 , _frame (0)
1000         {}
1001
1002 private:
1003
1004         bool OnInit ()
1005         try
1006         {
1007                 wxInitAllImageHandlers ();
1008
1009                 Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
1010                 Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
1011
1012                 wxSplashScreen* splash = maybe_show_splash ();
1013
1014                 SetAppName (_("DCP-o-matic Player"));
1015
1016                 if (!wxApp::OnInit()) {
1017                         return false;
1018                 }
1019
1020 #ifdef DCPOMATIC_LINUX
1021                 unsetenv ("UBUNTU_MENUPROXY");
1022 #endif
1023
1024 #ifdef __WXOSX__
1025                 ProcessSerialNumber serial;
1026                 GetCurrentProcess (&serial);
1027                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
1028 #endif
1029
1030                 dcpomatic_setup_path_encoding ();
1031
1032                 /* Enable i18n; this will create a Config object
1033                    to look for a force-configured language.  This Config
1034                    object will be wrong, however, because dcpomatic_setup
1035                    hasn't yet been called and there aren't any filters etc.
1036                    set up yet.
1037                 */
1038                 dcpomatic_setup_i18n ();
1039
1040                 /* Set things up, including filters etc.
1041                    which will now be internationalised correctly.
1042                 */
1043                 dcpomatic_setup ();
1044
1045                 /* Force the configuration to be re-loaded correctly next
1046                    time it is needed.
1047                 */
1048                 Config::drop ();
1049
1050                 _frame = new DOMFrame ();
1051                 SetTopWindow (_frame);
1052                 _frame->Maximize ();
1053                 if (splash) {
1054                         splash->Destroy ();
1055                 }
1056                 _frame->Show ();
1057
1058                 signal_manager = new wxSignalManager (this);
1059
1060                 PlayServer* server = new PlayServer (_frame);
1061                 new thread (boost::bind (&PlayServer::run, server));
1062
1063                 if (!_dcp_to_load.empty() && boost::filesystem::is_directory (_dcp_to_load)) {
1064                         try {
1065                                 _frame->load_dcp (_dcp_to_load);
1066                         } catch (exception& e) {
1067                                 error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load DCP %1.")), _dcp_to_load)), std_to_wx(e.what()));
1068                         }
1069                 }
1070
1071                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
1072
1073                 if (Config::instance()->check_for_updates ()) {
1074                         UpdateChecker::instance()->run ();
1075                 }
1076
1077                 return true;
1078         }
1079         catch (exception& e)
1080         {
1081                 error_dialog (0, _("DCP-o-matic Player could not start."), std_to_wx(e.what()));
1082                 return true;
1083         }
1084
1085         void OnInitCmdLine (wxCmdLineParser& parser)
1086         {
1087                 parser.SetDesc (command_line_description);
1088                 parser.SetSwitchChars (wxT ("-"));
1089         }
1090
1091         bool OnCmdLineParsed (wxCmdLineParser& parser)
1092         {
1093                 if (parser.GetParamCount() > 0) {
1094                         _dcp_to_load = wx_to_std (parser.GetParam (0));
1095                 }
1096
1097                 return true;
1098         }
1099
1100         void report_exception ()
1101         {
1102                 try {
1103                         throw;
1104                 } catch (FileError& e) {
1105                         error_dialog (
1106                                 0,
1107                                 wxString::Format (
1108                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
1109                                         std_to_wx (e.what()),
1110                                         std_to_wx (e.file().string().c_str ())
1111                                         )
1112                                 );
1113                 } catch (exception& e) {
1114                         error_dialog (
1115                                 0,
1116                                 wxString::Format (
1117                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
1118                                         std_to_wx (e.what ())
1119                                         )
1120                                 );
1121                 } catch (...) {
1122                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
1123                 }
1124         }
1125
1126         /* An unhandled exception has occurred inside the main event loop */
1127         bool OnExceptionInMainLoop ()
1128         {
1129                 report_exception ();
1130                 /* This will terminate the program */
1131                 return false;
1132         }
1133
1134         void OnUnhandledException ()
1135         {
1136                 report_exception ();
1137         }
1138
1139         void idle ()
1140         {
1141                 signal_manager->ui_idle ();
1142         }
1143
1144         void config_failed_to_load ()
1145         {
1146                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
1147         }
1148
1149         void config_warning (string m)
1150         {
1151                 message_dialog (_frame, std_to_wx (m));
1152         }
1153
1154         DOMFrame* _frame;
1155         string _dcp_to_load;
1156 };
1157
1158 IMPLEMENT_APP (App)