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