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