Nag users to backup config.xml if they make a DKDM.
[dcpomatic.git] / src / tools / dcpomatic.cc
1 /*
2     Copyright (C) 2012-2016 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 /** @file  src/tools/dcpomatic.cc
22  *  @brief The main DCP-o-matic GUI.
23  */
24
25 #include "wx/film_viewer.h"
26 #include "wx/film_editor.h"
27 #include "wx/job_manager_view.h"
28 #include "wx/config_dialog.h"
29 #include "wx/wx_util.h"
30 #include "wx/new_film_dialog.h"
31 #include "wx/wx_signal_manager.h"
32 #include "wx/about_dialog.h"
33 #include "wx/kdm_dialog.h"
34 #include "wx/self_dkdm_dialog.h"
35 #include "wx/servers_list_dialog.h"
36 #include "wx/hints_dialog.h"
37 #include "wx/update_dialog.h"
38 #include "wx/content_panel.h"
39 #include "wx/report_problem_dialog.h"
40 #include "wx/video_waveform_dialog.h"
41 #include "wx/save_template_dialog.h"
42 #include "wx/templates_dialog.h"
43 #include "wx/nag_dialog.h"
44 #include "lib/film.h"
45 #include "lib/config.h"
46 #include "lib/util.h"
47 #include "lib/video_content.h"
48 #include "lib/content.h"
49 #include "lib/version.h"
50 #include "lib/signal_manager.h"
51 #include "lib/log.h"
52 #include "lib/job_manager.h"
53 #include "lib/exceptions.h"
54 #include "lib/cinema.h"
55 #include "lib/screen_kdm.h"
56 #include "lib/send_kdm_email_job.h"
57 #include "lib/encode_server_finder.h"
58 #include "lib/update_checker.h"
59 #include "lib/cross.h"
60 #include "lib/content_factory.h"
61 #include "lib/compose.hpp"
62 #include "lib/cinema_kdms.h"
63 #include "lib/dcpomatic_socket.h"
64 #include "lib/hints.h"
65 #include "lib/dcp_content.h"
66 #include <dcp/exceptions.h>
67 #include <dcp/raw_convert.h>
68 #include <wx/generic/aboutdlgg.h>
69 #include <wx/stdpaths.h>
70 #include <wx/cmdline.h>
71 #include <wx/preferences.h>
72 #include <wx/splash.h>
73 #ifdef __WXMSW__
74 #include <shellapi.h>
75 #endif
76 #ifdef __WXOSX__
77 #include <ApplicationServices/ApplicationServices.h>
78 #endif
79 #include <boost/filesystem.hpp>
80 #include <boost/noncopyable.hpp>
81 #include <boost/foreach.hpp>
82 #include <iostream>
83 #include <fstream>
84 /* This is OK as it's only used with DCPOMATIC_WINDOWS */
85 #include <sstream>
86
87 #ifdef check
88 #undef check
89 #endif
90
91 using std::cout;
92 using std::wcout;
93 using std::string;
94 using std::vector;
95 using std::wstring;
96 using std::wstringstream;
97 using std::map;
98 using std::make_pair;
99 using std::list;
100 using std::exception;
101 using boost::shared_ptr;
102 using boost::dynamic_pointer_cast;
103 using boost::optional;
104 using dcp::raw_convert;
105
106 class FilmChangedDialog : public boost::noncopyable
107 {
108 public:
109         FilmChangedDialog (string name)
110         {
111                 _dialog = new wxMessageDialog (
112                         0,
113                         wxString::Format (_("Save changes to film \"%s\" before closing?"), std_to_wx (name).data()),
114                         /// TRANSLATORS: this is the heading for a dialog box, which tells the user that the current
115                         /// project (Film) has been changed since it was last saved.
116                         _("Film changed"),
117                         wxYES_NO | wxCANCEL | wxYES_DEFAULT | wxICON_QUESTION
118                         );
119
120                 _dialog->SetYesNoCancelLabels (
121                         _("Save film and close"), _("Close without saving film"), _("Don't close")
122                         );
123         }
124
125         ~FilmChangedDialog ()
126         {
127                 _dialog->Destroy ();
128         }
129
130         int run ()
131         {
132                 return _dialog->ShowModal ();
133         }
134
135 private:
136         wxMessageDialog* _dialog;
137 };
138
139 #define ALWAYS                       0x0
140 #define NEEDS_FILM                   0x1
141 #define NOT_DURING_DCP_CREATION      0x2
142 #define NEEDS_CPL                    0x4
143 #define NEEDS_SELECTED_VIDEO_CONTENT 0x8
144
145 map<wxMenuItem*, int> menu_items;
146
147 enum {
148         ID_file_new = 1,
149         ID_file_open,
150         ID_file_save,
151         ID_file_save_as_template,
152         ID_file_history,
153         /* Allow spare IDs after _history for the recent files list */
154         ID_content_scale_to_fit_width = 100,
155         ID_content_scale_to_fit_height,
156         ID_jobs_make_dcp,
157         ID_jobs_make_dcp_batch,
158         ID_jobs_make_kdms,
159         ID_jobs_make_self_dkdm,
160         ID_jobs_send_dcp_to_tms,
161         ID_jobs_show_dcp,
162         ID_tools_video_waveform,
163         ID_tools_hints,
164         ID_tools_encoding_servers,
165         ID_tools_manage_templates,
166         ID_tools_check_for_updates,
167         ID_tools_restore_default_preferences,
168         ID_help_report_a_problem,
169         /* IDs for shortcuts (with no associated menu item) */
170         ID_add_file,
171         ID_remove
172 };
173
174 class DOMFrame : public wxFrame
175 {
176 public:
177         DOMFrame (wxString const & title)
178                 : wxFrame (NULL, -1, title)
179                 , _video_waveform_dialog (0)
180                 , _hints_dialog (0)
181                 , _servers_list_dialog (0)
182                 , _config_dialog (0)
183                 , _kdm_dialog (0)
184                 , _templates_dialog (0)
185                 , _file_menu (0)
186                 , _history_items (0)
187                 , _history_position (0)
188                 , _history_separator (0)
189                 , _update_news_requested (false)
190         {
191 #if defined(DCPOMATIC_WINDOWS)
192                 if (Config::instance()->win32_console ()) {
193                         AllocConsole();
194
195                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
196                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
197                         FILE* hf_out = _fdopen(hCrt, "w");
198                         setvbuf(hf_out, NULL, _IONBF, 1);
199                         *stdout = *hf_out;
200
201                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
202                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
203                         FILE* hf_in = _fdopen(hCrt, "r");
204                         setvbuf(hf_in, NULL, _IONBF, 128);
205                         *stdin = *hf_in;
206
207                         cout << "DCP-o-matic is starting." << "\n";
208                 }
209 #endif
210
211                 wxMenuBar* bar = new wxMenuBar;
212                 setup_menu (bar);
213                 SetMenuBar (bar);
214
215 #ifdef DCPOMATIC_WINDOWS
216                 SetIcon (wxIcon (std_to_wx ("id")));
217 #endif
218
219                 _config_changed_connection = Config::instance()->Changed.connect (boost::bind (&DOMFrame::config_changed, this, _1));
220                 config_changed (Config::OTHER);
221
222                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_new, this),                ID_file_new);
223                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_open, this),               ID_file_open);
224                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_save, this),               ID_file_save);
225                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_save_as_template, this),   ID_file_save_as_template);
226                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_history, this, _1),        ID_file_history, ID_file_history + HISTORY_SIZE);
227                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this),               wxID_EXIT);
228                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this),        wxID_PREFERENCES);
229                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::content_scale_to_fit_width, this), ID_content_scale_to_fit_width);
230                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::content_scale_to_fit_height, this), ID_content_scale_to_fit_height);
231                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_dcp, this),           ID_jobs_make_dcp);
232                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_kdms, this),          ID_jobs_make_kdms);
233                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_dcp_batch, this),     ID_jobs_make_dcp_batch);
234                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_self_dkdm, this),     ID_jobs_make_self_dkdm);
235                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_send_dcp_to_tms, this),    ID_jobs_send_dcp_to_tms);
236                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_show_dcp, this),           ID_jobs_show_dcp);
237                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_video_waveform, this),    ID_tools_video_waveform);
238                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_hints, this),             ID_tools_hints);
239                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_encoding_servers, this),  ID_tools_encoding_servers);
240                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_manage_templates, this),  ID_tools_manage_templates);
241                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_check_for_updates, this), ID_tools_check_for_updates);
242                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_restore_default_preferences, this), ID_tools_restore_default_preferences);
243                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this),              wxID_ABOUT);
244                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this),   ID_help_report_a_problem);
245
246                 Bind (wxEVT_CLOSE_WINDOW, boost::bind (&DOMFrame::close, this, _1));
247
248                 /* Use a panel as the only child of the Frame so that we avoid
249                    the dark-grey background on Windows.
250                 */
251                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
252
253                 _film_viewer = new FilmViewer (overall_panel);
254                 _film_editor = new FilmEditor (overall_panel, _film_viewer);
255                 JobManagerView* job_manager_view = new JobManagerView (overall_panel, false);
256
257                 wxBoxSizer* right_sizer = new wxBoxSizer (wxVERTICAL);
258                 right_sizer->Add (_film_viewer, 2, wxEXPAND | wxALL, 6);
259                 right_sizer->Add (job_manager_view, 1, wxEXPAND | wxALL, 6);
260
261                 wxBoxSizer* main_sizer = new wxBoxSizer (wxHORIZONTAL);
262                 main_sizer->Add (_film_editor, 1, wxEXPAND | wxALL, 6);
263                 main_sizer->Add (right_sizer, 2, wxEXPAND | wxALL, 6);
264
265                 set_menu_sensitivity ();
266
267                 _film_editor->FileChanged.connect (bind (&DOMFrame::file_changed, this, _1));
268                 file_changed ("");
269
270                 JobManager::instance()->ActiveJobsChanged.connect (boost::bind (&DOMFrame::set_menu_sensitivity, this));
271
272                 overall_panel->SetSizer (main_sizer);
273
274                 wxAcceleratorEntry accel[2];
275                 accel[0].Set (wxACCEL_CTRL, static_cast<int>('A'), ID_add_file);
276                 accel[1].Set (wxACCEL_NORMAL, WXK_DELETE, ID_remove);
277                 Bind (wxEVT_MENU, boost::bind (&ContentPanel::add_file_clicked, _film_editor->content_panel()), ID_add_file);
278                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::remove_clicked, this, _1), ID_remove);
279                 wxAcceleratorTable accel_table (2, accel);
280                 SetAcceleratorTable (accel_table);
281
282                 UpdateChecker::instance()->StateChanged.connect (boost::bind (&DOMFrame::update_checker_state_changed, this));
283         }
284
285         void remove_clicked (wxCommandEvent& ev)
286         {
287                 if (_film_editor->content_panel()->remove_clicked (true)) {
288                         ev.Skip ();
289                 }
290         }
291
292         void new_film (boost::filesystem::path path, optional<string> template_name)
293         {
294                 shared_ptr<Film> film (new Film (path));
295                 if (template_name) {
296                         film->use_template (template_name.get());
297                 }
298                 film->write_metadata ();
299                 film->set_name (path.filename().generic_string());
300                 set_film (film);
301         }
302
303         void load_film (boost::filesystem::path file)
304         try
305         {
306                 shared_ptr<Film> film (new Film (file));
307                 list<string> const notes = film->read_metadata ();
308
309                 if (film->state_version() == 4) {
310                         error_dialog (
311                                 0,
312                                 _("This film was created with an old version of DVD-o-matic and may not load correctly "
313                                   "in this version.  Please check the film's settings carefully.")
314                                 );
315                 }
316
317                 for (list<string>::const_iterator i = notes.begin(); i != notes.end(); ++i) {
318                         error_dialog (0, std_to_wx (*i));
319                 }
320
321                 set_film (film);
322         }
323         catch (std::exception& e) {
324                 wxString p = std_to_wx (file.string ());
325                 wxCharBuffer b = p.ToUTF8 ();
326                 error_dialog (this, wxString::Format (_("Could not open film at %s (%s)"), p.data(), std_to_wx (e.what()).data()));
327         }
328
329         void set_film (shared_ptr<Film> film)
330         {
331                 _film = film;
332                 _film_viewer->set_film (_film);
333                 _film_editor->set_film (_film);
334                 delete _video_waveform_dialog;
335                 _video_waveform_dialog = 0;
336                 set_menu_sensitivity ();
337                 if (_film->directory()) {
338                         Config::instance()->add_to_history (_film->directory().get());
339                 }
340         }
341
342         shared_ptr<Film> film () const {
343                 return _film;
344         }
345
346 private:
347
348         void file_changed (boost::filesystem::path f)
349         {
350                 string s = wx_to_std (_("DCP-o-matic"));
351                 if (!f.empty ()) {
352                         s += " - " + f.string ();
353                 }
354
355                 SetTitle (std_to_wx (s));
356         }
357
358         void file_new ()
359         {
360                 NewFilmDialog* d = new NewFilmDialog (this);
361                 int const r = d->ShowModal ();
362
363                 if (r == wxID_OK) {
364
365                         if (boost::filesystem::is_directory (d->path()) && !boost::filesystem::is_empty(d->path())) {
366                                 if (!confirm_dialog (
367                                             this,
368                                             std_to_wx (
369                                                     String::compose (wx_to_std (_("The directory %1 already exists and is not empty.  "
370                                                                                   "Are you sure you want to use it?")),
371                                                                      d->path().string().c_str())
372                                                     )
373                                             )) {
374                                         return;
375                                 }
376                         } else if (boost::filesystem::is_regular_file (d->path())) {
377                                 error_dialog (
378                                         this,
379                                         String::compose (wx_to_std (_("%1 already exists as a file, so you cannot use it for a new film.")), d->path().c_str())
380                                         );
381                                 return;
382                         }
383
384                         if (maybe_save_then_delete_film ()) {
385                                 new_film (d->path(), d->template_name());
386                         }
387                 }
388
389                 d->Destroy ();
390         }
391
392         void file_open ()
393         {
394                 wxDirDialog* c = new wxDirDialog (
395                         this,
396                         _("Select film to open"),
397                         std_to_wx (Config::instance()->default_directory_or (wx_to_std (wxStandardPaths::Get().GetDocumentsDir())).string ()),
398                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
399                         );
400
401                 int r;
402                 while (true) {
403                         r = c->ShowModal ();
404                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
405                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
406                         } else {
407                                 break;
408                         }
409                 }
410
411                 if (r == wxID_OK && maybe_save_then_delete_film()) {
412                         load_film (wx_to_std (c->GetPath ()));
413                 }
414
415                 c->Destroy ();
416         }
417
418         void file_save ()
419         {
420                 _film->write_metadata ();
421         }
422
423         void file_save_as_template ()
424         {
425                 SaveTemplateDialog* d = new SaveTemplateDialog (this);
426                 int const r = d->ShowModal ();
427                 if (r == wxID_OK) {
428                         Config::instance()->save_template (_film, d->name ());
429                 }
430                 d->Destroy ();
431         }
432
433         void file_history (wxCommandEvent& event)
434         {
435                 vector<boost::filesystem::path> history = Config::instance()->history ();
436                 int n = event.GetId() - ID_file_history;
437                 if (n >= 0 && n < static_cast<int> (history.size ()) && maybe_save_then_delete_film()) {
438                         load_film (history[n]);
439                 }
440         }
441
442         void file_exit ()
443         {
444                 /* false here allows the close handler to veto the close request */
445                 Close (false);
446         }
447
448         void edit_preferences ()
449         {
450                 if (!_config_dialog) {
451                         _config_dialog = create_config_dialog ();
452                 }
453                 _config_dialog->Show (this);
454         }
455
456         void tools_restore_default_preferences ()
457         {
458                 wxMessageDialog* d = new wxMessageDialog (
459                         0,
460                         _("Are you sure you want to restore preferences to their defaults?  This cannot be undone."),
461                         _("Restore default preferences"),
462                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
463                         );
464
465                 int const r = d->ShowModal ();
466                 d->Destroy ();
467
468                 if (r == wxID_YES) {
469                         Config::restore_defaults ();
470                 }
471         }
472
473         void jobs_make_dcp ()
474         {
475                 double required;
476                 double available;
477                 bool can_hard_link;
478
479                 if (!_film->should_be_enough_disk_space (required, available, can_hard_link)) {
480                         wxString message;
481                         if (can_hard_link) {
482                                 message = wxString::Format (_("The DCP for this film will take up about %.1f Gb, and the disk that you are using only has %.1f Gb available.  Do you want to continue anyway?"), required, available);
483                         } else {
484                                 message = wxString::Format (_("The DCP and intermediate files for this film will take up about %.1f Gb, and the disk that you are using only has %.1f Gb available.  You would need half as much space if the filesystem supported hard links, but it does not.  Do you want to continue anyway?"), required, available);
485                         }
486                         if (!confirm_dialog (this, message)) {
487                                 return;
488                         }
489                 }
490
491                 if (!get_hints(_film).empty() && Config::instance()->show_hints_before_make_dcp()) {
492                         HintsDialog* hints = new HintsDialog (this, _film, false);
493                         int const r = hints->ShowModal();
494                         hints->Destroy ();
495                         if (r == wxID_CANCEL) {
496                                 return;
497                         }
498                 }
499
500
501                 /* Remove any existing DCP if the user agrees */
502                 boost::filesystem::path const dcp_dir = _film->dir (_film->dcp_name(), false);
503                 if (boost::filesystem::exists (dcp_dir)) {
504                         if (!confirm_dialog (this, wxString::Format (_("Do you want to overwrite the existing DCP %s?"), std_to_wx(dcp_dir.string()).data()))) {
505                                 return;
506                         }
507                         boost::filesystem::remove_all (dcp_dir);
508                 }
509
510                 try {
511                         /* It seems to make sense to auto-save metadata here, since the make DCP may last
512                            a long time, and crashes/power failures are moderately likely.
513                         */
514                         _film->write_metadata ();
515                         _film->make_dcp ();
516                 } catch (BadSettingError& e) {
517                         error_dialog (this, wxString::Format (_("Bad setting for %s (%s)"), std_to_wx(e.setting()).data(), std_to_wx(e.what()).data()));
518                 } catch (std::exception& e) {
519                         error_dialog (this, wxString::Format (_("Could not make DCP: %s."), std_to_wx(e.what()).data()));
520                 }
521         }
522
523         void jobs_make_kdms ()
524         {
525                 if (!_film) {
526                         return;
527                 }
528
529                 if (_kdm_dialog) {
530                         _kdm_dialog->Destroy ();
531                         _kdm_dialog = 0;
532                 }
533
534                 _kdm_dialog = new KDMDialog (this, _film);
535                 _kdm_dialog->Show ();
536         }
537
538         void jobs_make_dcp_batch ()
539         {
540                 if (!_film) {
541                         return;
542                 }
543
544                 if (!get_hints(_film).empty() && Config::instance()->show_hints_before_make_dcp()) {
545                         HintsDialog* hints = new HintsDialog (this, _film, false);
546                         int const r = hints->ShowModal();
547                         hints->Destroy ();
548                         if (r == wxID_CANCEL) {
549                                 return;
550                         }
551                 }
552
553                 _film->write_metadata ();
554
555                 /* i = 0; try to connect via socket
556                    i = 1; try again, and then try to start the batch converter
557                    i = 2 onwards; try again.
558                 */
559                 for (int i = 0; i < 8; ++i) {
560                         try {
561                                 boost::asio::io_service io_service;
562                                 boost::asio::ip::tcp::resolver resolver (io_service);
563                                 boost::asio::ip::tcp::resolver::query query ("127.0.0.1", raw_convert<string> (BATCH_JOB_PORT));
564                                 boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query);
565                                 Socket socket (5);
566                                 socket.connect (*endpoint_iterator);
567                                 DCPOMATIC_ASSERT (_film->directory ());
568                                 string s = _film->directory()->string ();
569                                 socket.write (s.length() + 1);
570                                 socket.write ((uint8_t *) s.c_str(), s.length() + 1);
571                                 /* OK\0 */
572                                 uint8_t ok[3];
573                                 socket.read (ok, 3);
574                                 return;
575                         } catch (exception& e) {
576
577                         }
578
579                         if (i == 1) {
580                                 start_batch_converter (wx_to_std (wxStandardPaths::Get().GetExecutablePath()));
581                         }
582
583                         dcpomatic_sleep (1);
584                 }
585
586                 error_dialog (this, _("Could not find batch converter."));
587         }
588
589         void jobs_make_self_dkdm ()
590         {
591                 if (!_film) {
592                         return;
593                 }
594
595                 SelfDKDMDialog* d = new SelfDKDMDialog (this, _film);
596                 if (d->ShowModal () != wxID_OK) {
597                         d->Destroy ();
598                         return;
599                 }
600
601                 NagDialog::maybe_nag (
602                         this,
603                         Config::NAG_DKDM_CONFIG,
604                         wxString::Format (
605                                 _("You are making a DKDM which is encrypted by a private key held in"
606                                   "\n\n<tt>%s</tt>\n\nIt is <span weight=\"bold\" size=\"larger\">VITALLY IMPORTANT</span> "
607                                   "that you <span weight=\"bold\" size=\"larger\">BACK UP THIS FILE</span> since if it is lost "
608                                   "your DKDMs (and the DCPs they protect) will become useless."), std_to_wx(Config::config_path().string()).data()
609                                 )
610                         );
611
612                 optional<dcp::EncryptedKDM> kdm;
613                 try {
614                         kdm = _film->make_kdm (
615                                 Config::instance()->decryption_chain()->leaf(),
616                                 vector<dcp::Certificate> (),
617                                 d->cpl (),
618                                 dcp::LocalTime ("2012-01-01T01:00:00+00:00"),
619                                 dcp::LocalTime ("2112-01-01T01:00:00+00:00"),
620                                 dcp::MODIFIED_TRANSITIONAL_1
621                                 );
622                 } catch (dcp::NotEncryptedError& e) {
623                         error_dialog (this, _("CPL's content is not encrypted."));
624                 } catch (exception& e) {
625                         error_dialog (this, e.what ());
626                 } catch (...) {
627                         error_dialog (this, _("An unknown exception occurred."));
628                 }
629
630                 if (kdm) {
631                         if (d->internal ()) {
632                                 vector<dcp::EncryptedKDM> dkdms = Config::instance()->dkdms ();
633                                 dkdms.push_back (kdm.get());
634                                 Config::instance()->set_dkdms (dkdms);
635                         } else {
636                                 boost::filesystem::path path = d->directory() / (_film->dcp_name(false) + "_DKDM.xml");
637                                 kdm->as_xml (path);
638                         }
639                 }
640
641                 d->Destroy ();
642         }
643
644         void content_scale_to_fit_width ()
645         {
646                 ContentList vc = _film_editor->content_panel()->selected_video ();
647                 for (ContentList::iterator i = vc.begin(); i != vc.end(); ++i) {
648                         (*i)->video->scale_and_crop_to_fit_width ();
649                 }
650         }
651
652         void content_scale_to_fit_height ()
653         {
654                 ContentList vc = _film_editor->content_panel()->selected_video ();
655                 for (ContentList::iterator i = vc.begin(); i != vc.end(); ++i) {
656                         (*i)->video->scale_and_crop_to_fit_height ();
657                 }
658         }
659
660         void jobs_send_dcp_to_tms ()
661         {
662                 _film->send_dcp_to_tms ();
663         }
664
665         void jobs_show_dcp ()
666         {
667                 DCPOMATIC_ASSERT (_film->directory ());
668 #ifdef DCPOMATIC_WINDOWS
669                 wstringstream args;
670                 args << "/select," << _film->dir (_film->dcp_name(false));
671                 ShellExecute (0, L"open", L"explorer.exe", args.str().c_str(), 0, SW_SHOWDEFAULT);
672 #endif
673
674 #ifdef DCPOMATIC_LINUX
675                 int r = system ("which nautilus");
676                 if (WEXITSTATUS (r) == 0) {
677                         r = system (string ("nautilus " + _film->directory()->string()).c_str ());
678                         if (WEXITSTATUS (r)) {
679                                 error_dialog (this, _("Could not show DCP (could not run nautilus)"));
680                         }
681                 } else {
682                         int r = system ("which konqueror");
683                         if (WEXITSTATUS (r) == 0) {
684                                 r = system (string ("konqueror " + _film->directory()->string()).c_str ());
685                                 if (WEXITSTATUS (r)) {
686                                         error_dialog (this, _("Could not show DCP (could not run konqueror)"));
687                                 }
688                         }
689                 }
690 #endif
691
692 #ifdef DCPOMATIC_OSX
693                 int r = system (string ("open -R " + _film->dir (_film->dcp_name (false)).string ()).c_str ());
694                 if (WEXITSTATUS (r)) {
695                         error_dialog (this, _("Could not show DCP"));
696                 }
697 #endif
698         }
699
700         void tools_video_waveform ()
701         {
702                 if (!_video_waveform_dialog) {
703                         _video_waveform_dialog = new VideoWaveformDialog (this, _film, _film_viewer);
704                 }
705
706                 _video_waveform_dialog->Show ();
707         }
708
709         void tools_hints ()
710         {
711                 if (!_hints_dialog) {
712                         _hints_dialog = new HintsDialog (this, _film, true);
713                 }
714
715                 _hints_dialog->Show ();
716         }
717
718         void tools_encoding_servers ()
719         {
720                 if (!_servers_list_dialog) {
721                         _servers_list_dialog = new ServersListDialog (this);
722                 }
723
724                 _servers_list_dialog->Show ();
725         }
726
727         void tools_manage_templates ()
728         {
729                 if (!_templates_dialog) {
730                         _templates_dialog = new TemplatesDialog (this);
731                 }
732
733                 _templates_dialog->Show ();
734         }
735
736         void tools_check_for_updates ()
737         {
738                 UpdateChecker::instance()->run ();
739                 _update_news_requested = true;
740         }
741
742         void help_about ()
743         {
744                 AboutDialog* d = new AboutDialog (this);
745                 d->ShowModal ();
746                 d->Destroy ();
747         }
748
749         void help_report_a_problem ()
750         {
751                 ReportProblemDialog* d = new ReportProblemDialog (this, _film);
752                 if (d->ShowModal () == wxID_OK) {
753                         d->report ();
754                 }
755                 d->Destroy ();
756         }
757
758         bool should_close ()
759         {
760                 if (!JobManager::instance()->work_to_do ()) {
761                         return true;
762                 }
763
764                 wxMessageDialog* d = new wxMessageDialog (
765                         0,
766                         _("There are unfinished jobs; are you sure you want to quit?"),
767                         _("Unfinished jobs"),
768                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
769                         );
770
771                 bool const r = d->ShowModal() == wxID_YES;
772                 d->Destroy ();
773                 return r;
774         }
775
776         void close (wxCloseEvent& ev)
777         {
778                 if (!should_close ()) {
779                         ev.Veto ();
780                         return;
781                 }
782
783                 if (_film && _film->dirty ()) {
784
785                         FilmChangedDialog* dialog = new FilmChangedDialog (_film->name ());
786                         int const r = dialog->run ();
787                         delete dialog;
788
789                         switch (r) {
790                         case wxID_NO:
791                                 /* Don't save and carry on to close */
792                                 break;
793                         case wxID_YES:
794                                 /* Save and carry on to close */
795                                 _film->write_metadata ();
796                                 break;
797                         case wxID_CANCEL:
798                                 /* Veto the event and stop */
799                                 ev.Veto ();
800                                 return;
801                         }
802                 }
803
804                 /* We don't want to hear about any more configuration changes, since they
805                    cause the File menu to be altered, which itself will be deleted around
806                    now (without, as far as I can see, any way for us to find out).
807                 */
808                 _config_changed_connection.disconnect ();
809
810                 ev.Skip ();
811         }
812
813         void set_menu_sensitivity ()
814         {
815                 list<shared_ptr<Job> > jobs = JobManager::instance()->get ();
816                 list<shared_ptr<Job> >::iterator i = jobs.begin();
817                 while (i != jobs.end() && (*i)->json_name() != "transcode") {
818                         ++i;
819                 }
820                 bool const dcp_creation = (i != jobs.end ()) && !(*i)->finished ();
821                 bool const have_cpl = _film && !_film->cpls().empty ();
822                 bool const have_selected_video_content = !_film_editor->content_panel()->selected_video().empty();
823
824                 for (map<wxMenuItem*, int>::iterator j = menu_items.begin(); j != menu_items.end(); ++j) {
825
826                         bool enabled = true;
827
828                         if ((j->second & NEEDS_FILM) && !_film) {
829                                 enabled = false;
830                         }
831
832                         if ((j->second & NOT_DURING_DCP_CREATION) && dcp_creation) {
833                                 enabled = false;
834                         }
835
836                         if ((j->second & NEEDS_CPL) && !have_cpl) {
837                                 enabled = false;
838                         }
839
840                         if ((j->second & NEEDS_SELECTED_VIDEO_CONTENT) && !have_selected_video_content) {
841                                 enabled = false;
842                         }
843
844                         j->first->Enable (enabled);
845                 }
846         }
847
848         /** @return true if the operation that called this method
849          *  should continue, false to abort it.
850          */
851         bool maybe_save_then_delete_film ()
852         {
853                 if (!_film) {
854                         return true;
855                 }
856
857                 if (_film->dirty ()) {
858                         FilmChangedDialog d (_film->name ());
859                         switch (d.run ()) {
860                         case wxID_NO:
861                                 break;
862                         case wxID_YES:
863                                 _film->write_metadata ();
864                                 break;
865                         case wxID_CANCEL:
866                                 return false;
867                         }
868                 }
869
870                 _film.reset ();
871                 return true;
872         }
873
874         void add_item (wxMenu* menu, wxString text, int id, int sens)
875         {
876                 wxMenuItem* item = menu->Append (id, text);
877                 menu_items.insert (make_pair (item, sens));
878         }
879
880         void setup_menu (wxMenuBar* m)
881         {
882                 _file_menu = new wxMenu;
883                 add_item (_file_menu, _("New...\tCtrl-N"), ID_file_new, ALWAYS);
884                 add_item (_file_menu, _("&Open...\tCtrl-O"), ID_file_open, ALWAYS);
885                 _file_menu->AppendSeparator ();
886                 add_item (_file_menu, _("&Save\tCtrl-S"), ID_file_save, NEEDS_FILM);
887                 _file_menu->AppendSeparator ();
888                 add_item (_file_menu, _("Save as &template..."), ID_file_save_as_template, NEEDS_FILM);
889
890                 _history_position = _file_menu->GetMenuItems().GetCount();
891
892 #ifndef __WXOSX__
893                 _file_menu->AppendSeparator ();
894 #endif
895
896 #ifdef __WXOSX__
897                 add_item (_file_menu, _("&Exit"), wxID_EXIT, ALWAYS);
898 #else
899                 add_item (_file_menu, _("&Quit"), wxID_EXIT, ALWAYS);
900 #endif
901
902 #ifdef __WXOSX__
903                 add_item (_file_menu, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
904 #else
905                 wxMenu* edit = new wxMenu;
906                 add_item (edit, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
907 #endif
908
909                 wxMenu* content = new wxMenu;
910                 add_item (content, _("Scale to fit &width"), ID_content_scale_to_fit_width, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
911                 add_item (content, _("Scale to fit &height"), ID_content_scale_to_fit_height, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
912
913                 wxMenu* jobs_menu = new wxMenu;
914                 add_item (jobs_menu, _("&Make DCP\tCtrl-M"), ID_jobs_make_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION);
915                 add_item (jobs_menu, _("Make DCP in &batch converter\tCtrl-B"), ID_jobs_make_dcp_batch, NEEDS_FILM | NOT_DURING_DCP_CREATION);
916                 add_item (jobs_menu, _("Make &KDMs...\tCtrl-K"), ID_jobs_make_kdms, NEEDS_FILM);
917                 add_item (jobs_menu, _("Make DKDM for DCP-o-matic..."), ID_jobs_make_self_dkdm, NEEDS_FILM);
918                 add_item (jobs_menu, _("&Send DCP to TMS"), ID_jobs_send_dcp_to_tms, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
919                 add_item (jobs_menu, _("S&how DCP"), ID_jobs_show_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
920
921                 wxMenu* tools = new wxMenu;
922                 add_item (tools, _("Video waveform..."), ID_tools_video_waveform, NEEDS_FILM);
923                 add_item (tools, _("Hints..."), ID_tools_hints, 0);
924                 add_item (tools, _("Encoding servers..."), ID_tools_encoding_servers, 0);
925                 add_item (tools, _("Manage templates..."), ID_tools_manage_templates, 0);
926                 add_item (tools, _("Check for updates"), ID_tools_check_for_updates, 0);
927                 tools->AppendSeparator ();
928                 add_item (tools, _("Restore default preferences"), ID_tools_restore_default_preferences, ALWAYS);
929
930                 wxMenu* help = new wxMenu;
931 #ifdef __WXOSX__
932                 add_item (help, _("About DCP-o-matic"), wxID_ABOUT, ALWAYS);
933 #else
934                 add_item (help, _("About"), wxID_ABOUT, ALWAYS);
935 #endif
936                 add_item (help, _("Report a problem..."), ID_help_report_a_problem, NEEDS_FILM);
937
938                 m->Append (_file_menu, _("&File"));
939 #ifndef __WXOSX__
940                 m->Append (edit, _("&Edit"));
941 #endif
942                 m->Append (content, _("&Content"));
943                 m->Append (jobs_menu, _("&Jobs"));
944                 m->Append (tools, _("&Tools"));
945                 m->Append (help, _("&Help"));
946         }
947
948         void config_changed (Config::Property what)
949         {
950                 /* Instantly save any config changes when using the DCP-o-matic GUI */
951                 if (what == Config::CINEMAS) {
952                         try {
953                                 Config::instance()->write_cinemas();
954                         } catch (exception& e) {
955                                 error_dialog (
956                                         this,
957                                         wxString::Format (
958                                                 _("Could not write to cinemas file at %s.  Your changes have not been saved."),
959                                                 std_to_wx (Config::instance()->cinemas_file().string()).data()
960                                                 )
961                                         );
962                         }
963                 } else {
964                         try {
965                                 Config::instance()->write_config();
966                         } catch (exception& e) {
967                                 error_dialog (
968                                         this,
969                                         wxString::Format (
970                                                 _("Could not write to config file at %s.  Your changes have not been saved."),
971                                                 std_to_wx (Config::instance()->cinemas_file().string()).data()
972                                                 )
973                                         );
974                         }
975                 }
976
977                 for (int i = 0; i < _history_items; ++i) {
978                         delete _file_menu->Remove (ID_file_history + i);
979                 }
980
981                 if (_history_separator) {
982                         _file_menu->Remove (_history_separator);
983                 }
984                 delete _history_separator;
985                 _history_separator = 0;
986
987                 int pos = _history_position;
988
989                 vector<boost::filesystem::path> history = Config::instance()->history ();
990
991                 if (!history.empty ()) {
992                         _history_separator = _file_menu->InsertSeparator (pos++);
993                 }
994
995                 for (size_t i = 0; i < history.size(); ++i) {
996                         string s;
997                         if (i < 9) {
998                                 s = String::compose ("&%1 %2", i + 1, history[i].string());
999                         } else {
1000                                 s = history[i].string();
1001                         }
1002                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s));
1003                 }
1004
1005                 _history_items = history.size ();
1006         }
1007
1008         void update_checker_state_changed ()
1009         {
1010                 UpdateChecker* uc = UpdateChecker::instance ();
1011
1012                 bool const announce =
1013                         _update_news_requested ||
1014                         (uc->stable() && Config::instance()->check_for_updates()) ||
1015                         (uc->test() && Config::instance()->check_for_updates() && Config::instance()->check_for_test_updates());
1016
1017                 _update_news_requested = false;
1018
1019                 if (!announce) {
1020                         return;
1021                 }
1022
1023                 if (uc->state() == UpdateChecker::YES) {
1024                         UpdateDialog* dialog = new UpdateDialog (this, uc->stable (), uc->test ());
1025                         dialog->ShowModal ();
1026                         dialog->Destroy ();
1027                 } else if (uc->state() == UpdateChecker::FAILED) {
1028                         error_dialog (this, _("The DCP-o-matic download server could not be contacted."));
1029                 } else {
1030                         error_dialog (this, _("There are no new versions of DCP-o-matic available."));
1031                 }
1032
1033                 _update_news_requested = false;
1034         }
1035
1036         FilmEditor* _film_editor;
1037         FilmViewer* _film_viewer;
1038         VideoWaveformDialog* _video_waveform_dialog;
1039         HintsDialog* _hints_dialog;
1040         ServersListDialog* _servers_list_dialog;
1041         wxPreferencesEditor* _config_dialog;
1042         KDMDialog* _kdm_dialog;
1043         TemplatesDialog* _templates_dialog;
1044         wxMenu* _file_menu;
1045         shared_ptr<Film> _film;
1046         int _history_items;
1047         int _history_position;
1048         wxMenuItem* _history_separator;
1049         boost::signals2::scoped_connection _config_changed_connection;
1050         bool _update_news_requested;
1051 };
1052
1053 static const wxCmdLineEntryDesc command_line_description[] = {
1054         { wxCMD_LINE_SWITCH, "n", "new", "create new film", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
1055         { wxCMD_LINE_OPTION, "c", "content", "add content file / directory", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1056         { wxCMD_LINE_OPTION, "d", "dcp", "add content DCP", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1057         { wxCMD_LINE_PARAM, 0, 0, "film to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1058         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
1059 };
1060
1061 /** @class App
1062  *  @brief The magic App class for wxWidgets.
1063  */
1064 class App : public wxApp
1065 {
1066 public:
1067         App ()
1068                 : wxApp ()
1069                 , _frame (0)
1070         {}
1071
1072 private:
1073
1074         bool OnInit ()
1075         try
1076         {
1077                 wxInitAllImageHandlers ();
1078
1079                 Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
1080
1081                 wxSplashScreen* splash = 0;
1082                 try {
1083                         if (!Config::have_existing ("config.xml")) {
1084                                 wxBitmap bitmap;
1085                                 boost::filesystem::path p = shared_path () / "splash.png";
1086                                 if (bitmap.LoadFile (std_to_wx (p.string ()), wxBITMAP_TYPE_PNG)) {
1087                                         splash = new wxSplashScreen (bitmap, wxSPLASH_CENTRE_ON_SCREEN | wxSPLASH_NO_TIMEOUT, 0, 0, -1);
1088                                         wxYield ();
1089                                 }
1090                         }
1091                 } catch (boost::filesystem::filesystem_error& e) {
1092                         /* Maybe we couldn't find the splash image; never mind */
1093                 }
1094
1095                 SetAppName (_("DCP-o-matic"));
1096
1097                 if (!wxApp::OnInit()) {
1098                         return false;
1099                 }
1100
1101 #ifdef DCPOMATIC_LINUX
1102                 unsetenv ("UBUNTU_MENUPROXY");
1103 #endif
1104
1105 #ifdef __WXOSX__
1106                 ProcessSerialNumber serial;
1107                 GetCurrentProcess (&serial);
1108                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
1109 #endif
1110
1111                 dcpomatic_setup_path_encoding ();
1112
1113                 /* Enable i18n; this will create a Config object
1114                    to look for a force-configured language.  This Config
1115                    object will be wrong, however, because dcpomatic_setup
1116                    hasn't yet been called and there aren't any filters etc.
1117                    set up yet.
1118                 */
1119                 dcpomatic_setup_i18n ();
1120
1121                 /* Set things up, including filters etc.
1122                    which will now be internationalised correctly.
1123                 */
1124                 dcpomatic_setup ();
1125
1126                 /* Force the configuration to be re-loaded correctly next
1127                    time it is needed.
1128                 */
1129                 Config::drop ();
1130
1131                 _frame = new DOMFrame (_("DCP-o-matic"));
1132                 SetTopWindow (_frame);
1133                 _frame->Maximize ();
1134                 if (splash) {
1135                         splash->Destroy ();
1136                 }
1137                 _frame->Show ();
1138
1139                 if (!_film_to_load.empty() && boost::filesystem::is_directory (_film_to_load)) {
1140                         try {
1141                                 _frame->load_film (_film_to_load);
1142                         } catch (exception& e) {
1143                                 error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load film %1 (%2)")), _film_to_load, e.what())));
1144                         }
1145                 }
1146
1147                 if (!_film_to_create.empty ()) {
1148                         _frame->new_film (_film_to_create, optional<string> ());
1149                         if (!_content_to_add.empty ()) {
1150                                 BOOST_FOREACH (shared_ptr<Content> i, content_factory (_frame->film(), _content_to_add)) {
1151                                         _frame->film()->examine_and_add_content (i);
1152                                 }
1153                         }
1154                         if (!_dcp_to_add.empty ()) {
1155                                 _frame->film()->examine_and_add_content (shared_ptr<DCPContent> (new DCPContent (_frame->film(), _dcp_to_add)));
1156                         }
1157                 }
1158
1159                 signal_manager = new wxSignalManager (this);
1160                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
1161
1162                 Bind (wxEVT_TIMER, boost::bind (&App::check, this));
1163                 _timer.reset (new wxTimer (this));
1164                 _timer->Start (1000);
1165
1166                 if (Config::instance()->check_for_updates ()) {
1167                         UpdateChecker::instance()->run ();
1168                 }
1169
1170                 return true;
1171         }
1172         catch (exception& e)
1173         {
1174                 error_dialog (0, wxString::Format ("DCP-o-matic could not start: %s", e.what ()));
1175                 return true;
1176         }
1177
1178         void OnInitCmdLine (wxCmdLineParser& parser)
1179         {
1180                 parser.SetDesc (command_line_description);
1181                 parser.SetSwitchChars (wxT ("-"));
1182         }
1183
1184         bool OnCmdLineParsed (wxCmdLineParser& parser)
1185         {
1186                 if (parser.GetParamCount() > 0) {
1187                         if (parser.Found (wxT ("new"))) {
1188                                 _film_to_create = wx_to_std (parser.GetParam (0));
1189                         } else {
1190                                 _film_to_load = wx_to_std (parser.GetParam (0));
1191                         }
1192                 }
1193
1194                 wxString content;
1195                 if (parser.Found (wxT ("content"), &content)) {
1196                         _content_to_add = wx_to_std (content);
1197                 }
1198
1199                 wxString dcp;
1200                 if (parser.Found (wxT ("dcp"), &dcp)) {
1201                         _dcp_to_add = wx_to_std (dcp);
1202                 }
1203
1204                 return true;
1205         }
1206
1207         void report_exception ()
1208         {
1209                 try {
1210                         throw;
1211                 } catch (FileError& e) {
1212                         error_dialog (
1213                                 0,
1214                                 wxString::Format (
1215                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
1216                                         std_to_wx (e.what()),
1217                                         std_to_wx (e.file().string().c_str ())
1218                                         )
1219                                 );
1220                 } catch (exception& e) {
1221                         error_dialog (
1222                                 0,
1223                                 wxString::Format (
1224                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
1225                                         std_to_wx (e.what ())
1226                                         )
1227                                 );
1228                 } catch (...) {
1229                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
1230                 }
1231         }
1232
1233         /* An unhandled exception has occurred inside the main event loop */
1234         bool OnExceptionInMainLoop ()
1235         {
1236                 report_exception ();
1237                 /* This will terminate the program */
1238                 return false;
1239         }
1240
1241         void OnUnhandledException ()
1242         {
1243                 report_exception ();
1244         }
1245
1246         void idle ()
1247         {
1248                 signal_manager->ui_idle ();
1249         }
1250
1251         void check ()
1252         {
1253                 try {
1254                         EncodeServerFinder::instance()->rethrow ();
1255                 } catch (exception& e) {
1256                         error_dialog (0, std_to_wx (e.what ()));
1257                 }
1258         }
1259
1260         void config_failed_to_load ()
1261         {
1262                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
1263         }
1264
1265         DOMFrame* _frame;
1266         shared_ptr<wxTimer> _timer;
1267         string _film_to_load;
1268         string _film_to_create;
1269         string _content_to_add;
1270         string _dcp_to_add;
1271 };
1272
1273 IMPLEMENT_APP (App)