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