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