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