More Controls API tweaks.
[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                 setup_from_dcp (dcp);
319
320                 if (dcp->three_d()) {
321                         _film->set_three_d (true);
322                 }
323
324                 _viewer->set_film (_film);
325                 _viewer->seek (DCPTime(), true);
326                 _info->triggered_update ();
327
328                 Config::instance()->add_to_player_history (dir);
329
330                 set_menu_sensitivity ();
331
332                 wxMenuItemList old = _cpl_menu->GetMenuItems();
333                 for (wxMenuItemList::iterator i = old.begin(); i != old.end(); ++i) {
334                         _cpl_menu->Remove (*i);
335                 }
336
337                 DCPExaminer ex (dcp);
338                 int id = ID_view_cpl;
339                 BOOST_FOREACH (shared_ptr<dcp::CPL> i, ex.cpls()) {
340                         wxMenuItem* j = _cpl_menu->AppendRadioItem(
341                                 id,
342                                 wxString::Format("%s (%s)", std_to_wx(i->annotation_text()).data(), std_to_wx(i->id()).data())
343                                 );
344                         j->Check(!dcp->cpl() || i->id() == *dcp->cpl());
345                         ++id;
346                 }
347         }
348
349 private:
350
351         void setup_menu (wxMenuBar* m)
352         {
353                 _file_menu = new wxMenu;
354                 _file_menu->Append (ID_file_open, _("&Open...\tCtrl-O"));
355                 _file_add_ov = _file_menu->Append (ID_file_add_ov, _("&Add OV..."));
356                 _file_add_kdm = _file_menu->Append (ID_file_add_kdm, _("&Add KDM..."));
357
358                 _history_position = _file_menu->GetMenuItems().GetCount();
359
360                 _file_menu->AppendSeparator ();
361                 _file_menu->Append (ID_file_close, _("&Close"));
362                 _file_menu->AppendSeparator ();
363
364 #ifdef __WXOSX__
365                 _file_menu->Append (wxID_EXIT, _("&Exit"));
366 #else
367                 _file_menu->Append (wxID_EXIT, _("&Quit"));
368 #endif
369
370 #ifdef __WXOSX__
371                 _file_menu->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
372 #else
373                 wxMenu* edit = new wxMenu;
374                 edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
375 #endif
376
377                 _cpl_menu = new wxMenu;
378
379                 wxMenu* view = new wxMenu;
380                 optional<int> c = Config::instance()->decode_reduction();
381                 _view_cpl = view->Append(ID_view_cpl, _("CPL"), _cpl_menu);
382                 view->AppendSeparator();
383 #ifndef DCPOMATIC_VARIANT_SWAROOP
384                 _view_full_screen = view->AppendCheckItem(ID_view_full_screen, _("Full screen\tF11"));
385                 _view_dual_screen = view->AppendCheckItem(ID_view_dual_screen, _("Dual screen\tShift+F11"));
386 #endif
387                 setup_menu ();
388                 view->AppendSeparator();
389                 view->Append(ID_view_closed_captions, _("Closed captions..."));
390                 view->AppendSeparator();
391                 view->AppendRadioItem(ID_view_scale_appropriate, _("Set decode resolution to match display"))->Check(!static_cast<bool>(c));
392                 view->AppendRadioItem(ID_view_scale_full, _("Decode at full resolution"))->Check(c && c.get() == 0);
393                 view->AppendRadioItem(ID_view_scale_half, _("Decode at half resolution"))->Check(c && c.get() == 1);
394                 view->AppendRadioItem(ID_view_scale_quarter, _("Decode at quarter resolution"))->Check(c && c.get() == 2);
395
396                 wxMenu* tools = new wxMenu;
397                 _tools_verify = tools->Append (ID_tools_verify, _("Verify DCP"));
398                 tools->AppendSeparator ();
399                 tools->Append (ID_tools_check_for_updates, _("Check for updates"));
400
401                 wxMenu* help = new wxMenu;
402 #ifdef __WXOSX__
403                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
404 #else
405                 help->Append (wxID_ABOUT, _("About"));
406 #endif
407                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
408
409                 m->Append (_file_menu, _("&File"));
410 #ifndef __WXOSX__
411                 m->Append (edit, _("&Edit"));
412 #endif
413                 m->Append (view, _("&View"));
414                 m->Append (tools, _("&Tools"));
415                 m->Append (help, _("&Help"));
416         }
417
418         void file_open ()
419         {
420                 wxString d = wxStandardPaths::Get().GetDocumentsDir();
421                 if (Config::instance()->last_player_load_directory()) {
422                         d = std_to_wx (Config::instance()->last_player_load_directory()->string());
423                 }
424
425                 wxDirDialog* c = new wxDirDialog (this, _("Select DCP to open"), d, wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST);
426
427                 int r;
428                 while (true) {
429                         r = c->ShowModal ();
430                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
431                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
432                         } else {
433                                 break;
434                         }
435                 }
436
437                 if (r == wxID_OK) {
438                         boost::filesystem::path const dcp (wx_to_std (c->GetPath ()));
439                         load_dcp (dcp);
440                         Config::instance()->set_last_player_load_directory (dcp.parent_path());
441                 }
442
443                 c->Destroy ();
444         }
445
446         void file_add_ov ()
447         {
448                 wxDirDialog* c = new wxDirDialog (
449                         this,
450                         _("Select DCP to open as OV"),
451                         wxStandardPaths::Get().GetDocumentsDir(),
452                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
453                         );
454
455                 int r;
456                 while (true) {
457                         r = c->ShowModal ();
458                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
459                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
460                         } else {
461                                 break;
462                         }
463                 }
464
465                 if (r == wxID_OK) {
466                         DCPOMATIC_ASSERT (_film);
467                         shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
468                         DCPOMATIC_ASSERT (dcp);
469                         dcp->add_ov (wx_to_std(c->GetPath()));
470                         JobManager::instance()->add(shared_ptr<Job>(new ExamineContentJob (_film, dcp)));
471                         bool const ok = progress (_("Loading DCP"));
472                         if (!ok || !report_errors_from_last_job()) {
473                                 return;
474                         }
475                         setup_from_dcp (dcp);
476                 }
477
478                 c->Destroy ();
479                 _info->triggered_update ();
480         }
481
482         void file_add_kdm ()
483         {
484                 wxFileDialog* d = new wxFileDialog (this, _("Select KDM"));
485
486                 if (d->ShowModal() == wxID_OK) {
487                         DCPOMATIC_ASSERT (_film);
488                         shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
489                         DCPOMATIC_ASSERT (dcp);
490                         try {
491                                 dcp->add_kdm (dcp::EncryptedKDM (dcp::file_to_string (wx_to_std (d->GetPath ()), MAX_KDM_SIZE)));
492                                 dcp->examine (shared_ptr<Job>());
493                         } catch (exception& e) {
494                                 error_dialog (this, wxString::Format (_("Could not load KDM.")), std_to_wx(e.what()));
495                                 d->Destroy ();
496                                 return;
497                         }
498                 }
499
500                 d->Destroy ();
501                 _info->triggered_update ();
502         }
503
504         void file_history (wxCommandEvent& event)
505         {
506                 vector<boost::filesystem::path> history = Config::instance()->player_history ();
507                 int n = event.GetId() - ID_file_history;
508                 if (n >= 0 && n < static_cast<int> (history.size ())) {
509                         load_dcp (history[n]);
510                 }
511         }
512
513         void file_close ()
514         {
515                 _viewer->set_film (shared_ptr<Film>());
516                 _film.reset ();
517                 _info->triggered_update ();
518                 set_menu_sensitivity ();
519         }
520
521         void file_exit ()
522         {
523                 Close ();
524         }
525
526         void edit_preferences ()
527         {
528                 if (!_config_dialog) {
529                         _config_dialog = create_player_config_dialog ();
530                 }
531                 _config_dialog->Show (this);
532         }
533
534         void view_cpl (wxCommandEvent& ev)
535         {
536                 shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
537                 DCPOMATIC_ASSERT (dcp);
538                 DCPExaminer ex (dcp);
539                 int id = ev.GetId() - ID_view_cpl;
540                 DCPOMATIC_ASSERT (id >= 0);
541                 DCPOMATIC_ASSERT (id < int(ex.cpls().size()));
542                 list<shared_ptr<dcp::CPL> > cpls = ex.cpls();
543                 list<shared_ptr<dcp::CPL> >::iterator i = cpls.begin();
544                 while (id > 0) {
545                         ++i;
546                         --id;
547                 }
548
549                 dcp->set_cpl ((*i)->id());
550                 dcp->examine (shared_ptr<Job>());
551         }
552
553         void view_full_screen ()
554         {
555                 if (_mode == Config::PLAYER_MODE_FULL) {
556                         _mode = Config::PLAYER_MODE_WINDOW;
557                 } else {
558                         _mode = Config::PLAYER_MODE_FULL;
559                 }
560                 setup_screen ();
561                 setup_menu ();
562         }
563
564         void view_dual_screen ()
565         {
566                 if (_mode == Config::PLAYER_MODE_DUAL) {
567                         _mode = Config::PLAYER_MODE_WINDOW;
568                 } else {
569                         _mode = Config::PLAYER_MODE_DUAL;
570                 }
571                 setup_screen ();
572                 setup_menu ();
573         }
574
575         void setup_menu ()
576         {
577                 if (_view_full_screen) {
578                         _view_full_screen->Check (_mode == Config::PLAYER_MODE_FULL);
579                 }
580                 if (_view_dual_screen) {
581                         _view_dual_screen->Check (_mode == Config::PLAYER_MODE_DUAL);
582                 }
583         }
584
585         void setup_screen ()
586         {
587                 _controls->Show (_mode != Config::PLAYER_MODE_FULL);
588                 _controls->show_extended_player_controls (_mode == Config::PLAYER_MODE_DUAL);
589                 _info->Show (_mode != Config::PLAYER_MODE_FULL);
590                 _overall_panel->SetBackgroundColour (_mode == Config::PLAYER_MODE_FULL ? wxColour(0, 0, 0) : wxNullColour);
591                 ShowFullScreen (_mode == Config::PLAYER_MODE_FULL);
592
593                 if (_mode == Config::PLAYER_MODE_DUAL) {
594                         _dual_screen = new wxFrame (this, wxID_ANY, wxT(""));
595                         _dual_screen->SetBackgroundColour (wxColour(0, 0, 0));
596                         _dual_screen->ShowFullScreen (true);
597                         _viewer->panel()->Reparent (_dual_screen);
598                         _dual_screen->Show ();
599                         if (wxDisplay::GetCount() > 1) {
600                                 switch (Config::instance()->image_display()) {
601                                 case 0:
602                                         _dual_screen->Move (0, 0);
603                                         Move (wxDisplay(0).GetClientArea().GetWidth(), 0);
604                                         break;
605                                 case 1:
606                                         _dual_screen->Move (wxDisplay(0).GetClientArea().GetWidth(), 0);
607                                         // (0, 0) doesn't seem to work for some strange reason
608                                         Move (8, 8);
609                                         break;
610                                 }
611                         }
612                 } else {
613                         if (_dual_screen) {
614                                 _viewer->panel()->Reparent (_overall_panel);
615                                 _dual_screen->Destroy ();
616                                 _dual_screen = 0;
617                         }
618                 }
619
620                 setup_main_sizer (_mode != Config::PLAYER_MODE_DUAL);
621         }
622
623         void view_closed_captions ()
624         {
625                 _viewer->show_closed_captions ();
626         }
627
628         void tools_verify ()
629         {
630                 shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
631                 DCPOMATIC_ASSERT (dcp);
632
633                 JobManager* jm = JobManager::instance ();
634                 jm->add (shared_ptr<Job> (new VerifyDCPJob (dcp->directories())));
635                 bool const ok = progress (_("Verifying DCP"));
636                 if (!ok) {
637                         return;
638                 }
639
640                 DCPOMATIC_ASSERT (!jm->get().empty());
641                 shared_ptr<VerifyDCPJob> last = dynamic_pointer_cast<VerifyDCPJob> (jm->get().back());
642                 DCPOMATIC_ASSERT (last);
643
644                 VerifyDCPDialog* d = new VerifyDCPDialog (this, last);
645                 d->ShowModal ();
646                 d->Destroy ();
647         }
648
649         void tools_check_for_updates ()
650         {
651                 UpdateChecker::instance()->run ();
652                 _update_news_requested = true;
653         }
654
655         void help_about ()
656         {
657                 AboutDialog* d = new AboutDialog (this);
658                 d->ShowModal ();
659                 d->Destroy ();
660         }
661
662         void help_report_a_problem ()
663         {
664                 ReportProblemDialog* d = new ReportProblemDialog (this);
665                 if (d->ShowModal () == wxID_OK) {
666                         d->report ();
667                 }
668                 d->Destroy ();
669         }
670
671         void update_checker_state_changed ()
672         {
673                 UpdateChecker* uc = UpdateChecker::instance ();
674
675                 bool const announce =
676                         _update_news_requested ||
677                         (uc->stable() && Config::instance()->check_for_updates()) ||
678                         (uc->test() && Config::instance()->check_for_updates() && Config::instance()->check_for_test_updates());
679
680                 _update_news_requested = false;
681
682                 if (!announce) {
683                         return;
684                 }
685
686                 if (uc->state() == UpdateChecker::YES) {
687                         UpdateDialog* dialog = new UpdateDialog (this, uc->stable (), uc->test ());
688                         dialog->ShowModal ();
689                         dialog->Destroy ();
690                 } else if (uc->state() == UpdateChecker::FAILED) {
691                         error_dialog (this, _("The DCP-o-matic download server could not be contacted."));
692                 } else {
693                         error_dialog (this, _("There are no new versions of DCP-o-matic available."));
694                 }
695
696                 _update_news_requested = false;
697         }
698
699         void config_changed ()
700         {
701                 /* Instantly save any config changes when using the player GUI */
702                 try {
703                         Config::instance()->write_config();
704                 } catch (exception& e) {
705                         error_dialog (
706                                 this,
707                                 wxString::Format (
708                                         _("Could not write to config file at %s.  Your changes have not been saved."),
709                                         std_to_wx (Config::instance()->cinemas_file().string()).data()
710                                         )
711                                 );
712                 }
713
714                 for (int i = 0; i < _history_items; ++i) {
715                         delete _file_menu->Remove (ID_file_history + i);
716                 }
717
718                 if (_history_separator) {
719                         _file_menu->Remove (_history_separator);
720                 }
721                 delete _history_separator;
722                 _history_separator = 0;
723
724                 int pos = _history_position;
725
726                 vector<boost::filesystem::path> history = Config::instance()->player_history ();
727
728                 if (!history.empty ()) {
729                         _history_separator = _file_menu->InsertSeparator (pos++);
730                 }
731
732                 for (size_t i = 0; i < history.size(); ++i) {
733                         string s;
734                         if (i < 9) {
735                                 s = String::compose ("&%1 %2", i + 1, history[i].string());
736                         } else {
737                                 s = history[i].string();
738                         }
739                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s));
740                 }
741
742                 _history_items = history.size ();
743         }
744
745         void set_menu_sensitivity ()
746         {
747                 _tools_verify->Enable (static_cast<bool>(_film));
748                 _file_add_ov->Enable (static_cast<bool>(_film));
749                 _file_add_kdm->Enable (static_cast<bool>(_film));
750                 _view_cpl->Enable (static_cast<bool>(_film));
751         }
752
753         void start_stop_pressed ()
754         {
755                 if (_viewer->playing()) {
756                         _viewer->stop();
757                 } else {
758                         _viewer->start();
759                 }
760         }
761
762         void back_frame ()
763         {
764                 _viewer->seek_by (-_viewer->one_video_frame(), true);
765         }
766
767         void forward_frame ()
768         {
769                 _viewer->seek_by (_viewer->one_video_frame(), true);
770         }
771
772 private:
773
774         /** @return false if the task was cancelled */
775         bool progress (wxString task)
776         {
777                 JobManager* jm = JobManager::instance ();
778
779                 wxProgressDialog* progress = new wxProgressDialog (_("DCP-o-matic Player"), task, 100, 0, wxPD_CAN_ABORT);
780
781                 bool ok = true;
782
783                 while (jm->work_to_do() || signal_manager->ui_idle()) {
784                         dcpomatic_sleep (1);
785                         if (!progress->Pulse()) {
786                                 /* user pressed cancel */
787                                 BOOST_FOREACH (shared_ptr<Job> i, jm->get()) {
788                                         i->cancel();
789                                 }
790                                 ok = false;
791                                 break;
792                         }
793                 }
794
795                 progress->Destroy ();
796                 return ok;
797         }
798
799         bool report_errors_from_last_job ()
800         {
801                 JobManager* jm = JobManager::instance ();
802
803                 DCPOMATIC_ASSERT (!jm->get().empty());
804
805                 shared_ptr<Job> last = jm->get().back();
806                 if (last->finished_in_error()) {
807                         error_dialog(this, std_to_wx(last->error_summary()) + ".\n", std_to_wx(last->error_details()));
808                         return false;
809                 }
810
811                 return true;
812         }
813
814         void setup_from_dcp (shared_ptr<DCPContent> dcp)
815         {
816                 BOOST_FOREACH (shared_ptr<TextContent> i, dcp->text) {
817                         i->set_use (true);
818                 }
819
820                 if (dcp->video) {
821                         Ratio const * r = Ratio::nearest_from_ratio(dcp->video->size().ratio());
822                         if (r) {
823                                 _film->set_container(r);
824                         }
825                 }
826         }
827
828         wxFrame* _dual_screen;
829         bool _update_news_requested;
830         PlayerInformation* _info;
831         Config::PlayerMode _mode;
832         wxPreferencesEditor* _config_dialog;
833         wxPanel* _overall_panel;
834         wxMenu* _file_menu;
835         wxMenuItem* _view_cpl;
836         wxMenu* _cpl_menu;
837         int _history_items;
838         int _history_position;
839         wxMenuItem* _history_separator;
840         shared_ptr<FilmViewer> _viewer;
841         Controls* _controls;
842         boost::shared_ptr<Film> _film;
843         boost::signals2::scoped_connection _config_changed_connection;
844         wxMenuItem* _file_add_ov;
845         wxMenuItem* _file_add_kdm;
846         wxMenuItem* _tools_verify;
847         wxMenuItem* _view_full_screen;
848         wxMenuItem* _view_dual_screen;
849 };
850
851 static const wxCmdLineEntryDesc command_line_description[] = {
852         { wxCMD_LINE_PARAM, 0, 0, "DCP to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
853         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
854 };
855
856 class PlayServer : public Server
857 {
858 public:
859         explicit PlayServer (DOMFrame* frame)
860                 : Server (PLAYER_PLAY_PORT)
861                 , _frame (frame)
862         {}
863
864         void handle (shared_ptr<Socket> socket)
865         {
866                 try {
867                         int const length = socket->read_uint32 ();
868                         scoped_array<char> buffer (new char[length]);
869                         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
870                         string s (buffer.get());
871                         signal_manager->when_idle (bind (&DOMFrame::load_dcp, _frame, s));
872                         socket->write (reinterpret_cast<uint8_t const *> ("OK"), 3);
873                 } catch (...) {
874
875                 }
876         }
877
878 private:
879         DOMFrame* _frame;
880 };
881
882 /** @class App
883  *  @brief The magic App class for wxWidgets.
884  */
885 class App : public wxApp
886 {
887 public:
888         App ()
889                 : wxApp ()
890                 , _frame (0)
891         {}
892
893 private:
894
895         bool OnInit ()
896         try
897         {
898                 wxInitAllImageHandlers ();
899
900                 Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
901                 Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
902
903                 wxSplashScreen* splash = maybe_show_splash ();
904
905                 SetAppName (_("DCP-o-matic Player"));
906
907                 if (!wxApp::OnInit()) {
908                         return false;
909                 }
910
911 #ifdef DCPOMATIC_LINUX
912                 unsetenv ("UBUNTU_MENUPROXY");
913 #endif
914
915 #ifdef __WXOSX__
916                 ProcessSerialNumber serial;
917                 GetCurrentProcess (&serial);
918                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
919 #endif
920
921                 dcpomatic_setup_path_encoding ();
922
923                 /* Enable i18n; this will create a Config object
924                    to look for a force-configured language.  This Config
925                    object will be wrong, however, because dcpomatic_setup
926                    hasn't yet been called and there aren't any filters etc.
927                    set up yet.
928                 */
929                 dcpomatic_setup_i18n ();
930
931                 /* Set things up, including filters etc.
932                    which will now be internationalised correctly.
933                 */
934                 dcpomatic_setup ();
935
936                 /* Force the configuration to be re-loaded correctly next
937                    time it is needed.
938                 */
939                 Config::drop ();
940
941                 _frame = new DOMFrame ();
942                 SetTopWindow (_frame);
943                 _frame->Maximize ();
944                 if (splash) {
945                         splash->Destroy ();
946                 }
947                 _frame->Show ();
948
949                 signal_manager = new wxSignalManager (this);
950
951                 PlayServer* server = new PlayServer (_frame);
952                 new thread (boost::bind (&PlayServer::run, server));
953
954                 if (!_dcp_to_load.empty() && boost::filesystem::is_directory (_dcp_to_load)) {
955                         try {
956                                 _frame->load_dcp (_dcp_to_load);
957                         } catch (exception& e) {
958                                 error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load DCP %1.")), _dcp_to_load)), std_to_wx(e.what()));
959                         }
960                 }
961
962                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
963
964                 if (Config::instance()->check_for_updates ()) {
965                         UpdateChecker::instance()->run ();
966                 }
967
968                 return true;
969         }
970         catch (exception& e)
971         {
972                 error_dialog (0, _("DCP-o-matic Player could not start."), std_to_wx(e.what()));
973                 return true;
974         }
975
976         void OnInitCmdLine (wxCmdLineParser& parser)
977         {
978                 parser.SetDesc (command_line_description);
979                 parser.SetSwitchChars (wxT ("-"));
980         }
981
982         bool OnCmdLineParsed (wxCmdLineParser& parser)
983         {
984                 if (parser.GetParamCount() > 0) {
985                         _dcp_to_load = wx_to_std (parser.GetParam (0));
986                 }
987
988                 return true;
989         }
990
991         void report_exception ()
992         {
993                 try {
994                         throw;
995                 } catch (FileError& e) {
996                         error_dialog (
997                                 0,
998                                 wxString::Format (
999                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
1000                                         std_to_wx (e.what()),
1001                                         std_to_wx (e.file().string().c_str ())
1002                                         )
1003                                 );
1004                 } catch (exception& e) {
1005                         error_dialog (
1006                                 0,
1007                                 wxString::Format (
1008                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
1009                                         std_to_wx (e.what ())
1010                                         )
1011                                 );
1012                 } catch (...) {
1013                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
1014                 }
1015         }
1016
1017         /* An unhandled exception has occurred inside the main event loop */
1018         bool OnExceptionInMainLoop ()
1019         {
1020                 report_exception ();
1021                 /* This will terminate the program */
1022                 return false;
1023         }
1024
1025         void OnUnhandledException ()
1026         {
1027                 report_exception ();
1028         }
1029
1030         void idle ()
1031         {
1032                 signal_manager->ui_idle ();
1033         }
1034
1035         void config_failed_to_load ()
1036         {
1037                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
1038         }
1039
1040         void config_warning (string m)
1041         {
1042                 message_dialog (_frame, std_to_wx (m));
1043         }
1044
1045         DOMFrame* _frame;
1046         string _dcp_to_load;
1047 };
1048
1049 IMPLEMENT_APP (App)