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