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