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