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