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