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