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