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