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