Fix crash on loading non-existant DCP from recent menu.
[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/subtitle_content.h"
31 #include "wx/wx_signal_manager.h"
32 #include "wx/wx_util.h"
33 #include "wx/about_dialog.h"
34 #include "wx/report_problem_dialog.h"
35 #include "wx/film_viewer.h"
36 #include "wx/player_information.h"
37 #include "wx/update_dialog.h"
38 #include "wx/player_config_dialog.h"
39 #include <wx/wx.h>
40 #include <wx/stdpaths.h>
41 #include <wx/splash.h>
42 #include <wx/cmdline.h>
43 #include <wx/preferences.h>
44 #include <wx/progdlg.h>
45 #ifdef __WXOSX__
46 #include <ApplicationServices/ApplicationServices.h>
47 #endif
48 #include <boost/bind.hpp>
49 #include <iostream>
50
51 #ifdef check
52 #undef check
53 #endif
54
55 using std::string;
56 using std::cout;
57 using std::exception;
58 using std::vector;
59 using boost::shared_ptr;
60 using boost::optional;
61
62 enum {
63         ID_file_open = 1,
64         ID_file_add_ov,
65         ID_file_add_kdm,
66         ID_file_history,
67         /* Allow spare IDs after _history for the recent files list */
68         ID_file_close = 100,
69         ID_view_scale_appropriate,
70         ID_view_scale_full,
71         ID_view_scale_half,
72         ID_view_scale_quarter,
73         ID_help_report_a_problem,
74         ID_tools_check_for_updates,
75 };
76
77 class DOMFrame : public wxFrame
78 {
79 public:
80         DOMFrame ()
81                 : wxFrame (0, -1, _("DCP-o-matic Player"))
82                 , _update_news_requested (false)
83                 , _info (0)
84                 , _config_dialog (0)
85                 , _file_menu (0)
86                 , _history_items (0)
87                 , _history_position (0)
88                 , _history_separator (0)
89                 , _viewer (0)
90         {
91
92 #if defined(DCPOMATIC_WINDOWS)
93                 maybe_open_console ();
94                 cout << "DCP-o-matic Player is starting." << "\n";
95 #endif
96
97                 wxMenuBar* bar = new wxMenuBar;
98                 setup_menu (bar);
99                 set_menu_sensitivity ();
100                 SetMenuBar (bar);
101
102 #ifdef DCPOMATIC_WINDOWS
103                 SetIcon (wxIcon (std_to_wx ("id")));
104 #endif
105
106                 _config_changed_connection = Config::instance()->Changed.connect (boost::bind (&DOMFrame::config_changed, this));
107                 config_changed ();
108
109                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_open, this), ID_file_open);
110                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_ov, this), ID_file_add_ov);
111                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_kdm, this), ID_file_add_kdm);
112                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_history, this, _1), ID_file_history, ID_file_history + HISTORY_SIZE);
113                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_close, this), ID_file_close);
114                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this), wxID_EXIT);
115                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this), wxID_PREFERENCES);
116                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>()), ID_view_scale_appropriate);
117                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(0)), ID_view_scale_full);
118                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(1)), ID_view_scale_half);
119                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(2)), ID_view_scale_quarter);
120                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this), wxID_ABOUT);
121                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
122                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_check_for_updates, this), ID_tools_check_for_updates);
123
124                 /* Use a panel as the only child of the Frame so that we avoid
125                    the dark-grey background on Windows.
126                 */
127                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
128
129                 _viewer = new FilmViewer (overall_panel, false, false);
130                 _info = new PlayerInformation (overall_panel, _viewer);
131                 wxSizer* main_sizer = new wxBoxSizer (wxVERTICAL);
132                 main_sizer->Add (_viewer, 1, wxEXPAND | wxALL, 6);
133                 main_sizer->Add (_info, 0, wxEXPAND | wxALL, 6);
134                 overall_panel->SetSizer (main_sizer);
135
136                 UpdateChecker::instance()->StateChanged.connect (boost::bind (&DOMFrame::update_checker_state_changed, this));
137         }
138
139         void set_decode_reduction (optional<int> reduction)
140         {
141                 _viewer->set_dcp_decode_reduction (reduction);
142                 _info->triggered_update ();
143         }
144
145         void load_dcp (boost::filesystem::path dir)
146         {
147                 _film.reset (new Film (optional<boost::filesystem::path>()));
148                 shared_ptr<DCPContent> dcp;
149                 try {
150                         dcp.reset (new DCPContent (_film, dir));
151                 } catch (boost::filesystem::filesystem_error& e) {
152                         error_dialog (this, _("Could not load DCP"), std_to_wx (e.what()));
153                         return;
154                 }
155
156                 _film->examine_and_add_content (dcp, true);
157
158                 JobManager* jm = JobManager::instance ();
159
160                 wxProgressDialog* progress = new wxProgressDialog (_("DCP-o-matic Player"), _("Loading DCP"));
161
162                 while (jm->work_to_do() || signal_manager->ui_idle()) {
163                         dcpomatic_sleep (1);
164                         progress->Pulse ();
165                 }
166
167                 progress->Destroy ();
168
169                 DCPOMATIC_ASSERT (!jm->get().empty());
170
171                 shared_ptr<Job> last = jm->get().back();
172                 if (last->finished_in_error()) {
173                         error_dialog (this, std_to_wx (last->error_summary()) + ".\n");
174                         return;
175                 }
176
177                 if (dcp->subtitle) {
178                         dcp->subtitle->set_use (true);
179                 }
180
181                 _viewer->set_film (_film);
182                 _viewer->set_position (DCPTime ());
183                 _info->triggered_update ();
184
185                 Config::instance()->add_to_player_history (dir);
186
187                 set_menu_sensitivity ();
188         }
189
190 private:
191
192         void setup_menu (wxMenuBar* m)
193         {
194                 _file_menu = new wxMenu;
195                 _file_menu->Append (ID_file_open, _("&Open...\tCtrl-O"));
196                 _file_add_ov = _file_menu->Append (ID_file_add_ov, _("&Add OV..."));
197                 _file_add_kdm = _file_menu->Append (ID_file_add_kdm, _("&Add KDM..."));
198
199                 _history_position = _file_menu->GetMenuItems().GetCount();
200
201                 _file_menu->AppendSeparator ();
202                 _file_menu->Append (ID_file_close, _("&Close"));
203                 _file_menu->AppendSeparator ();
204
205 #ifdef __WXOSX__
206                 _file_menu->Append (wxID_EXIT, _("&Exit"));
207 #else
208                 _file_menu->Append (wxID_EXIT, _("&Quit"));
209 #endif
210
211 #ifdef __WXOSX__
212                 _file_menu->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
213 #else
214                 wxMenu* edit = new wxMenu;
215                 edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
216 #endif
217
218                 wxMenu* view = new wxMenu;
219                 view->AppendRadioItem (ID_view_scale_appropriate, _("Set decode resolution to match display"));
220                 view->AppendRadioItem (ID_view_scale_full, _("Decode at full resolution"));
221                 view->AppendRadioItem (ID_view_scale_half, _("Decode at half resolution"));
222                 view->AppendRadioItem (ID_view_scale_quarter, _("Decode at quarter resolution"));
223
224                 wxMenu* tools = new wxMenu;
225                 tools->Append (ID_tools_check_for_updates, _("Check for updates"));
226
227                 wxMenu* help = new wxMenu;
228 #ifdef __WXOSX__
229                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
230 #else
231                 help->Append (wxID_ABOUT, _("About"));
232 #endif
233                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
234
235                 m->Append (_file_menu, _("&File"));
236 #ifndef __WXOSX__
237                 m->Append (edit, _("&Edit"));
238 #endif
239                 m->Append (view, _("&View"));
240                 m->Append (tools, _("&Tools"));
241                 m->Append (help, _("&Help"));
242         }
243
244         void file_open ()
245         {
246                 wxString d = wxStandardPaths::Get().GetDocumentsDir();
247                 if (Config::instance()->last_player_load_directory()) {
248                         d = std_to_wx (Config::instance()->last_player_load_directory()->string());
249                 }
250
251                 wxDirDialog* c = new wxDirDialog (this, _("Select DCP to open"), d, wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST);
252
253                 int r;
254                 while (true) {
255                         r = c->ShowModal ();
256                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
257                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
258                         } else {
259                                 break;
260                         }
261                 }
262
263                 if (r == wxID_OK) {
264                         boost::filesystem::path const dcp (wx_to_std (c->GetPath ()));
265                         load_dcp (dcp);
266                         Config::instance()->set_last_player_load_directory (dcp.parent_path());
267                 }
268
269                 c->Destroy ();
270         }
271
272         void file_add_ov ()
273         {
274                 wxDirDialog* c = new wxDirDialog (
275                         this,
276                         _("Select DCP to open as OV"),
277                         wxStandardPaths::Get().GetDocumentsDir(),
278                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
279                         );
280
281                 int r;
282                 while (true) {
283                         r = c->ShowModal ();
284                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
285                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
286                         } else {
287                                 break;
288                         }
289                 }
290
291                 if (r == wxID_OK) {
292                         DCPOMATIC_ASSERT (_film);
293                         shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
294                         DCPOMATIC_ASSERT (dcp);
295                         dcp->add_ov (wx_to_std(c->GetPath()));
296                         dcp->examine (shared_ptr<Job>());
297                 }
298
299                 c->Destroy ();
300                 _info->triggered_update ();
301         }
302
303         void file_add_kdm ()
304         {
305                 wxFileDialog* d = new wxFileDialog (this, _("Select KDM"));
306
307                 if (d->ShowModal() == wxID_OK) {
308                         DCPOMATIC_ASSERT (_film);
309                         shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
310                         DCPOMATIC_ASSERT (dcp);
311                         try {
312                                 dcp->add_kdm (dcp::EncryptedKDM (dcp::file_to_string (wx_to_std (d->GetPath ()), MAX_KDM_SIZE)));
313                                 dcp->examine (shared_ptr<Job>());
314                         } catch (exception& e) {
315                                 error_dialog (this, wxString::Format (_("Could not load KDM.")), std_to_wx(e.what()));
316                                 d->Destroy ();
317                                 return;
318                         }
319                 }
320
321                 d->Destroy ();
322                 _info->triggered_update ();
323         }
324
325         void file_history (wxCommandEvent& event)
326         {
327                 vector<boost::filesystem::path> history = Config::instance()->player_history ();
328                 int n = event.GetId() - ID_file_history;
329                 if (n >= 0 && n < static_cast<int> (history.size ())) {
330                         load_dcp (history[n]);
331                 }
332         }
333
334         void file_close ()
335         {
336                 _viewer->set_film (shared_ptr<Film>());
337                 _film.reset ();
338                 _info->triggered_update ();
339                 set_menu_sensitivity ();
340         }
341
342         void file_exit ()
343         {
344                 Close ();
345         }
346
347         void edit_preferences ()
348         {
349                 if (!_config_dialog) {
350                         _config_dialog = create_player_config_dialog ();
351                 }
352                 _config_dialog->Show (this);
353         }
354
355         void tools_check_for_updates ()
356         {
357                 UpdateChecker::instance()->run ();
358                 _update_news_requested = true;
359         }
360
361         void help_about ()
362         {
363                 AboutDialog* d = new AboutDialog (this);
364                 d->ShowModal ();
365                 d->Destroy ();
366         }
367
368         void help_report_a_problem ()
369         {
370                 ReportProblemDialog* d = new ReportProblemDialog (this);
371                 if (d->ShowModal () == wxID_OK) {
372                         d->report ();
373                 }
374                 d->Destroy ();
375         }
376
377         void update_checker_state_changed ()
378         {
379                 UpdateChecker* uc = UpdateChecker::instance ();
380
381                 bool const announce =
382                         _update_news_requested ||
383                         (uc->stable() && Config::instance()->check_for_updates()) ||
384                         (uc->test() && Config::instance()->check_for_updates() && Config::instance()->check_for_test_updates());
385
386                 _update_news_requested = false;
387
388                 if (!announce) {
389                         return;
390                 }
391
392                 if (uc->state() == UpdateChecker::YES) {
393                         UpdateDialog* dialog = new UpdateDialog (this, uc->stable (), uc->test ());
394                         dialog->ShowModal ();
395                         dialog->Destroy ();
396                 } else if (uc->state() == UpdateChecker::FAILED) {
397                         error_dialog (this, _("The DCP-o-matic download server could not be contacted."));
398                 } else {
399                         error_dialog (this, _("There are no new versions of DCP-o-matic available."));
400                 }
401
402                 _update_news_requested = false;
403         }
404
405         void config_changed ()
406         {
407                 /* Instantly save any config changes when using the player GUI */
408                 try {
409                         Config::instance()->write_config();
410                 } catch (exception& e) {
411                         error_dialog (
412                                 this,
413                                 wxString::Format (
414                                         _("Could not write to config file at %s.  Your changes have not been saved."),
415                                         std_to_wx (Config::instance()->cinemas_file().string()).data()
416                                         )
417                                 );
418                 }
419
420                 for (int i = 0; i < _history_items; ++i) {
421                         delete _file_menu->Remove (ID_file_history + i);
422                 }
423
424                 if (_history_separator) {
425                         _file_menu->Remove (_history_separator);
426                 }
427                 delete _history_separator;
428                 _history_separator = 0;
429
430                 int pos = _history_position;
431
432                 vector<boost::filesystem::path> history = Config::instance()->player_history ();
433
434                 if (!history.empty ()) {
435                         _history_separator = _file_menu->InsertSeparator (pos++);
436                 }
437
438                 for (size_t i = 0; i < history.size(); ++i) {
439                         string s;
440                         if (i < 9) {
441                                 s = String::compose ("&%1 %2", i + 1, history[i].string());
442                         } else {
443                                 s = history[i].string();
444                         }
445                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s));
446                 }
447
448                 _history_items = history.size ();
449         }
450
451         void set_menu_sensitivity ()
452         {
453                 _file_add_ov->Enable (static_cast<bool>(_film));
454                 _file_add_kdm->Enable (static_cast<bool>(_film));
455         }
456
457         bool _update_news_requested;
458         PlayerInformation* _info;
459         wxPreferencesEditor* _config_dialog;
460         wxMenu* _file_menu;
461         int _history_items;
462         int _history_position;
463         wxMenuItem* _history_separator;
464         FilmViewer* _viewer;
465         boost::shared_ptr<Film> _film;
466         boost::signals2::scoped_connection _config_changed_connection;
467         wxMenuItem* _file_add_ov;
468         wxMenuItem* _file_add_kdm;
469 };
470
471 static const wxCmdLineEntryDesc command_line_description[] = {
472         { wxCMD_LINE_PARAM, 0, 0, "DCP to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
473         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
474 };
475
476 /** @class App
477  *  @brief The magic App class for wxWidgets.
478  */
479 class App : public wxApp
480 {
481 public:
482         App ()
483                 : wxApp ()
484                 , _frame (0)
485         {}
486
487 private:
488
489         bool OnInit ()
490         try
491         {
492                 wxInitAllImageHandlers ();
493
494                 Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
495                 Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
496
497                 wxSplashScreen* splash = maybe_show_splash ();
498
499                 SetAppName (_("DCP-o-matic Player"));
500
501                 if (!wxApp::OnInit()) {
502                         return false;
503                 }
504
505 #ifdef DCPOMATIC_LINUX
506                 unsetenv ("UBUNTU_MENUPROXY");
507 #endif
508
509 #ifdef __WXOSX__
510                 ProcessSerialNumber serial;
511                 GetCurrentProcess (&serial);
512                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
513 #endif
514
515                 dcpomatic_setup_path_encoding ();
516
517                 /* Enable i18n; this will create a Config object
518                    to look for a force-configured language.  This Config
519                    object will be wrong, however, because dcpomatic_setup
520                    hasn't yet been called and there aren't any filters etc.
521                    set up yet.
522                 */
523                 dcpomatic_setup_i18n ();
524
525                 /* Set things up, including filters etc.
526                    which will now be internationalised correctly.
527                 */
528                 dcpomatic_setup ();
529
530                 /* Force the configuration to be re-loaded correctly next
531                    time it is needed.
532                 */
533                 Config::drop ();
534
535                 _frame = new DOMFrame ();
536                 SetTopWindow (_frame);
537                 _frame->Maximize ();
538                 if (splash) {
539                         splash->Destroy ();
540                 }
541                 _frame->Show ();
542
543                 signal_manager = new wxSignalManager (this);
544
545                 if (!_dcp_to_load.empty() && boost::filesystem::is_directory (_dcp_to_load)) {
546                         try {
547                                 _frame->load_dcp (_dcp_to_load);
548                         } catch (exception& e) {
549                                 error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load DCP %1.")), _dcp_to_load)), std_to_wx(e.what()));
550                         }
551                 }
552
553                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
554
555                 if (Config::instance()->check_for_updates ()) {
556                         UpdateChecker::instance()->run ();
557                 }
558
559                 return true;
560         }
561         catch (exception& e)
562         {
563                 error_dialog (0, _("DCP-o-matic Player could not start."), std_to_wx(e.what()));
564                 return true;
565         }
566
567         void OnInitCmdLine (wxCmdLineParser& parser)
568         {
569                 parser.SetDesc (command_line_description);
570                 parser.SetSwitchChars (wxT ("-"));
571         }
572
573         bool OnCmdLineParsed (wxCmdLineParser& parser)
574         {
575                 if (parser.GetParamCount() > 0) {
576                         _dcp_to_load = wx_to_std (parser.GetParam (0));
577                 }
578
579                 return true;
580         }
581
582         void report_exception ()
583         {
584                 try {
585                         throw;
586                 } catch (FileError& e) {
587                         error_dialog (
588                                 0,
589                                 wxString::Format (
590                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
591                                         std_to_wx (e.what()),
592                                         std_to_wx (e.file().string().c_str ())
593                                         )
594                                 );
595                 } catch (exception& e) {
596                         error_dialog (
597                                 0,
598                                 wxString::Format (
599                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
600                                         std_to_wx (e.what ())
601                                         )
602                                 );
603                 } catch (...) {
604                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
605                 }
606         }
607
608         /* An unhandled exception has occurred inside the main event loop */
609         bool OnExceptionInMainLoop ()
610         {
611                 report_exception ();
612                 /* This will terminate the program */
613                 return false;
614         }
615
616         void OnUnhandledException ()
617         {
618                 report_exception ();
619         }
620
621         void idle ()
622         {
623                 signal_manager->ui_idle ();
624         }
625
626         void config_failed_to_load ()
627         {
628                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
629         }
630
631         void config_warning (string m)
632         {
633                 message_dialog (_frame, std_to_wx (m));
634         }
635
636         DOMFrame* _frame;
637         string _dcp_to_load;
638 };
639
640 IMPLEMENT_APP (App)