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