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