Fix build.
[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                                 wxString message = _("Could not create folder to store film.");
492                                 if (!found_bad_chars.empty()) {
493                                         message += "  ";
494                                         message += wxString::Format (_("Try removing the %s characters from your folder name."), std_to_wx(found_bad_chars).data());
495                                 }
496                                 error_dialog (this, message, std_to_wx(e.what()));
497 #else
498                                 error_dialog (this, _("Could not create folder to store film."), std_to_wx(e.what()));
499 #endif
500                         }
501                 }
502
503                 d->Destroy ();
504         }
505
506         void file_open ()
507         {
508                 wxDirDialog* c = new wxDirDialog (
509                         this,
510                         _("Select film to open"),
511                         std_to_wx (Config::instance()->default_directory_or (wx_to_std (wxStandardPaths::Get().GetDocumentsDir())).string ()),
512                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
513                         );
514
515                 int r;
516                 while (true) {
517                         r = c->ShowModal ();
518                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
519                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
520                         } else {
521                                 break;
522                         }
523                 }
524
525                 if (r == wxID_OK && maybe_save_then_delete_film<FilmChangedClosingDialog>()) {
526                         load_film (wx_to_std (c->GetPath ()));
527                 }
528
529                 c->Destroy ();
530         }
531
532         void file_save ()
533         {
534                 _film->write_metadata ();
535         }
536
537         void file_save_as_template ()
538         {
539                 SaveTemplateDialog* d = new SaveTemplateDialog (this);
540                 int const r = d->ShowModal ();
541                 if (r == wxID_OK) {
542                         Config::instance()->save_template (_film, d->name ());
543                 }
544                 d->Destroy ();
545         }
546
547         void file_duplicate ()
548         {
549                 FilmNameLocationDialog* d = new FilmNameLocationDialog (this, _("Duplicate Film"), false);
550                 int const r = d->ShowModal ();
551
552                 if (r == wxID_OK && d->check_path() && maybe_save_film<FilmChangedDuplicatingDialog>()) {
553                         shared_ptr<Film> film (new Film (d->path()));
554                         film->copy_from (_film);
555                         film->set_name (d->path().filename().generic_string());
556                         film->write_metadata ();
557                 }
558
559                 d->Destroy ();
560         }
561
562         void file_duplicate_and_open ()
563         {
564                 FilmNameLocationDialog* d = new FilmNameLocationDialog (this, _("Duplicate Film"), false);
565                 int const r = d->ShowModal ();
566
567                 if (r == wxID_OK && d->check_path() && maybe_save_film<FilmChangedDuplicatingDialog>()) {
568                         shared_ptr<Film> film (new Film (d->path()));
569                         film->copy_from (_film);
570                         film->set_name (d->path().filename().generic_string());
571                         film->write_metadata ();
572                         set_film (film);
573                 }
574
575                 d->Destroy ();
576         }
577
578         void file_history (wxCommandEvent& event)
579         {
580                 vector<boost::filesystem::path> history = Config::instance()->history ();
581                 int n = event.GetId() - ID_file_history;
582                 if (n >= 0 && n < static_cast<int> (history.size ()) && maybe_save_then_delete_film<FilmChangedClosingDialog>()) {
583                         load_film (history[n]);
584                 }
585         }
586
587         void file_exit ()
588         {
589                 /* false here allows the close handler to veto the close request */
590                 Close (false);
591         }
592
593         void edit_copy ()
594         {
595                 ContentList const sel = _film_editor->content_panel()->selected();
596                 DCPOMATIC_ASSERT (sel.size() == 1);
597                 _clipboard = sel.front()->clone();
598         }
599
600         void edit_paste ()
601         {
602                 DCPOMATIC_ASSERT (_clipboard);
603
604                 PasteDialog* d = new PasteDialog (this, static_cast<bool>(_clipboard->video), static_cast<bool>(_clipboard->audio), !_clipboard->text.empty());
605                 if (d->ShowModal() == wxID_OK) {
606                         BOOST_FOREACH (shared_ptr<Content> i, _film_editor->content_panel()->selected()) {
607                                 if (d->video() && i->video) {
608                                         DCPOMATIC_ASSERT (_clipboard->video);
609                                         i->video->take_settings_from (_clipboard->video);
610                                 }
611                                 if (d->audio() && i->audio) {
612                                         DCPOMATIC_ASSERT (_clipboard->audio);
613                                         i->audio->take_settings_from (_clipboard->audio);
614                                 }
615
616                                 if (d->text()) {
617                                         list<shared_ptr<TextContent> >::iterator j = i->text.begin ();
618                                         list<shared_ptr<TextContent> >::const_iterator k = _clipboard->text.begin ();
619                                         while (j != i->text.end() && k != _clipboard->text.end()) {
620                                                 (*j)->take_settings_from (*k);
621                                                 ++j;
622                                                 ++k;
623                                         }
624                                 }
625                         }
626                 }
627                 d->Destroy ();
628         }
629
630         void edit_preferences ()
631         {
632                 if (!_config_dialog) {
633                         _config_dialog = create_full_config_dialog ();
634                 }
635                 _config_dialog->Show (this);
636         }
637
638         void tools_restore_default_preferences ()
639         {
640                 wxMessageDialog* d = new wxMessageDialog (
641                         0,
642                         _("Are you sure you want to restore preferences to their defaults?  This cannot be undone."),
643                         _("Restore default preferences"),
644                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
645                         );
646
647                 int const r = d->ShowModal ();
648                 d->Destroy ();
649
650                 if (r == wxID_YES) {
651                         Config::restore_defaults ();
652                 }
653         }
654
655         void jobs_make_dcp ()
656         {
657                 double required;
658                 double available;
659                 bool can_hard_link;
660
661                 if (!_film->should_be_enough_disk_space (required, available, can_hard_link)) {
662                         wxString message;
663                         if (can_hard_link) {
664                                 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);
665                         } else {
666                                 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);
667                         }
668                         if (!confirm_dialog (this, message)) {
669                                 return;
670                         }
671                 }
672
673                 if (Config::instance()->show_hints_before_make_dcp()) {
674                         HintsDialog* hints = new HintsDialog (this, _film, false);
675                         int const r = hints->ShowModal();
676                         hints->Destroy ();
677                         if (r == wxID_CANCEL) {
678                                 return;
679                         }
680                 }
681
682                 if (_film->encrypted ()) {
683                         NagDialog::maybe_nag (
684                                 this,
685                                 Config::NAG_ENCRYPTED_METADATA,
686                                 _("You are making an encrypted DCP.  It will not be possible to make KDMs for this DCP unless you have copies of "
687                                   "the <tt>metadata.xml</tt> file within the film and the metadata files within the DCP.\n\n"
688                                   "You should ensure that these files are <span weight=\"bold\" size=\"larger\">BACKED UP</span> "
689                                   "if you want to make KDMs for this film.")
690                                 );
691                 }
692
693                 /* Remove any existing DCP if the user agrees */
694                 boost::filesystem::path const dcp_dir = _film->dir (_film->dcp_name(), false);
695                 if (boost::filesystem::exists (dcp_dir)) {
696                         if (!confirm_dialog (this, wxString::Format (_("Do you want to overwrite the existing DCP %s?"), std_to_wx(dcp_dir.string()).data()))) {
697                                 return;
698                         }
699                         boost::filesystem::remove_all (dcp_dir);
700                 }
701
702                 try {
703                         /* It seems to make sense to auto-save metadata here, since the make DCP may last
704                            a long time, and crashes/power failures are moderately likely.
705                         */
706                         _film->write_metadata ();
707                         _film->make_dcp ();
708                 } catch (BadSettingError& e) {
709                         error_dialog (this, wxString::Format (_("Bad setting for %s."), std_to_wx(e.setting()).data()), std_to_wx(e.what()));
710                 } catch (std::exception& e) {
711                         error_dialog (this, wxString::Format (_("Could not make DCP.")), std_to_wx(e.what()));
712                 }
713         }
714
715         void jobs_make_kdms ()
716         {
717                 if (!_film) {
718                         return;
719                 }
720
721                 if (_kdm_dialog) {
722                         _kdm_dialog->Destroy ();
723                         _kdm_dialog = 0;
724                 }
725
726                 _kdm_dialog = new KDMDialog (this, _film);
727                 _kdm_dialog->Show ();
728         }
729
730         /** @return false if we succeeded, true if not */
731         bool send_to_other_tool (int port, function<void(boost::filesystem::path)> start, string message)
732         {
733                 /* i = 0; try to connect via socket
734                    i = 1; try again, and then try to start the tool
735                    i = 2 onwards; try again.
736                 */
737                 for (int i = 0; i < 8; ++i) {
738                         try {
739                                 boost::asio::io_service io_service;
740                                 boost::asio::ip::tcp::resolver resolver (io_service);
741                                 boost::asio::ip::tcp::resolver::query query ("127.0.0.1", raw_convert<string> (port));
742                                 boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query);
743                                 Socket socket (5);
744                                 socket.connect (*endpoint_iterator);
745                                 DCPOMATIC_ASSERT (_film->directory ());
746                                 socket.write (message.length() + 1);
747                                 socket.write ((uint8_t *) message.c_str(), message.length() + 1);
748                                 /* OK\0 */
749                                 uint8_t ok[3];
750                                 socket.read (ok, 3);
751                                 return false;
752                         } catch (exception& e) {
753
754                         }
755
756                         if (i == 1) {
757                                 start (wx_to_std (wxStandardPaths::Get().GetExecutablePath()));
758                         }
759
760                         dcpomatic_sleep (1);
761                 }
762
763                 return true;
764         }
765
766         void jobs_make_dcp_batch ()
767         {
768                 if (!_film) {
769                         return;
770                 }
771
772                 if (Config::instance()->show_hints_before_make_dcp()) {
773                         HintsDialog* hints = new HintsDialog (this, _film, false);
774                         int const r = hints->ShowModal();
775                         hints->Destroy ();
776                         if (r == wxID_CANCEL) {
777                                 return;
778                         }
779                 }
780
781                 _film->write_metadata ();
782
783                 if (send_to_other_tool (BATCH_JOB_PORT, bind (&start_batch_converter, _1), _film->directory()->string())) {
784                         error_dialog (this, _("Could not find batch converter."));
785                 }
786         }
787
788         void jobs_open_dcp_in_player ()
789         {
790                 if (!_film) {
791                         return;
792                 }
793
794                 if (send_to_other_tool (PLAYER_PLAY_PORT, bind (&start_player, _1), _film->dir(_film->dcp_name(false)).string())) {
795                         error_dialog (this, _("Could not find player."));
796                 }
797         }
798
799         void jobs_make_self_dkdm ()
800         {
801                 if (!_film) {
802                         return;
803                 }
804
805                 SelfDKDMDialog* d = new SelfDKDMDialog (this, _film);
806                 if (d->ShowModal () != wxID_OK) {
807                         d->Destroy ();
808                         return;
809                 }
810
811                 NagDialog::maybe_nag (
812                         this,
813                         Config::NAG_DKDM_CONFIG,
814                         wxString::Format (
815                                 _("You are making a DKDM which is encrypted by a private key held in"
816                                   "\n\n<tt>%s</tt>\n\nIt is <span weight=\"bold\" size=\"larger\">VITALLY IMPORTANT</span> "
817                                   "that you <span weight=\"bold\" size=\"larger\">BACK UP THIS FILE</span> since if it is lost "
818                                   "your DKDMs (and the DCPs they protect) will become useless."), std_to_wx(Config::config_file().string()).data()
819                                 )
820                         );
821
822                 optional<dcp::EncryptedKDM> kdm;
823                 try {
824                         kdm = _film->make_kdm (
825                                 Config::instance()->decryption_chain()->leaf(),
826                                 vector<dcp::Certificate> (),
827                                 d->cpl (),
828                                 dcp::LocalTime ("2012-01-01T01:00:00+00:00"),
829                                 dcp::LocalTime ("2112-01-01T01:00:00+00:00"),
830                                 dcp::MODIFIED_TRANSITIONAL_1,
831                                 true,
832                                 0
833                                 );
834                 } catch (dcp::NotEncryptedError& e) {
835                         error_dialog (this, _("CPL's content is not encrypted."));
836                 } catch (exception& e) {
837                         error_dialog (this, e.what ());
838                 } catch (...) {
839                         error_dialog (this, _("An unknown exception occurred."));
840                 }
841
842                 if (kdm) {
843                         if (d->internal ()) {
844                                 shared_ptr<DKDMGroup> dkdms = Config::instance()->dkdms ();
845                                 dkdms->add (shared_ptr<DKDM> (new DKDM (kdm.get())));
846                                 Config::instance()->changed ();
847                         } else {
848                                 boost::filesystem::path path = d->directory() / (_film->dcp_name(false) + "_DKDM.xml");
849                                 kdm->as_xml (path);
850                         }
851                 }
852
853                 d->Destroy ();
854         }
855
856         void jobs_export ()
857         {
858                 ExportDialog* d = new ExportDialog (this);
859                 if (d->ShowModal() == wxID_OK) {
860                         shared_ptr<TranscodeJob> job (new TranscodeJob (_film));
861                         job->set_encoder (
862                                 shared_ptr<FFmpegEncoder> (
863                                         new FFmpegEncoder (_film, job, d->path(), d->format(), d->mixdown_to_stereo(), d->split_reels(), d->x264_crf())
864                                         )
865                                 );
866                         JobManager::instance()->add (job);
867                 }
868                 d->Destroy ();
869         }
870
871         void content_scale_to_fit_width ()
872         {
873                 ContentList vc = _film_editor->content_panel()->selected_video ();
874                 for (ContentList::iterator i = vc.begin(); i != vc.end(); ++i) {
875                         (*i)->video->scale_and_crop_to_fit_width ();
876                 }
877         }
878
879         void content_scale_to_fit_height ()
880         {
881                 ContentList vc = _film_editor->content_panel()->selected_video ();
882                 for (ContentList::iterator i = vc.begin(); i != vc.end(); ++i) {
883                         (*i)->video->scale_and_crop_to_fit_height ();
884                 }
885         }
886
887         void jobs_send_dcp_to_tms ()
888         {
889                 _film->send_dcp_to_tms ();
890         }
891
892         void jobs_show_dcp ()
893         {
894                 DCPOMATIC_ASSERT (_film->directory ());
895 #ifdef DCPOMATIC_WINDOWS
896                 wstringstream args;
897                 args << "/select," << _film->dir (_film->dcp_name(false));
898                 ShellExecute (0, L"open", L"explorer.exe", args.str().c_str(), 0, SW_SHOWDEFAULT);
899 #endif
900
901 #ifdef DCPOMATIC_LINUX
902                 int r = system ("which nautilus");
903                 if (WEXITSTATUS (r) == 0) {
904                         r = system (String::compose("nautilus \"%1\"", _film->directory()->string()).c_str());
905                         if (WEXITSTATUS (r)) {
906                                 error_dialog (this, _("Could not show DCP."), _("Could not run nautilus"));
907                         }
908                 } else {
909                         int r = system ("which konqueror");
910                         if (WEXITSTATUS (r) == 0) {
911                                 r = system (String::compose ("konqueror \"%1\"", _film->directory()->string()).c_str());
912                                 if (WEXITSTATUS (r)) {
913                                         error_dialog (this, _("Could not show DCP"), _("Could not run konqueror"));
914                                 }
915                         }
916                 }
917 #endif
918
919 #ifdef DCPOMATIC_OSX
920                 int r = system (String::compose ("open -R \"%1\"", _film->dir (_film->dcp_name(false)).string()).c_str());
921                 if (WEXITSTATUS (r)) {
922                         error_dialog (this, _("Could not show DCP"));
923                 }
924 #endif
925         }
926
927         void view_closed_captions ()
928         {
929                 _film_viewer->show_closed_captions ();
930         }
931
932         void view_video_waveform ()
933         {
934                 if (!_video_waveform_dialog) {
935                         _video_waveform_dialog = new VideoWaveformDialog (this, _film, _film_viewer);
936                 }
937
938                 _video_waveform_dialog->Show ();
939         }
940
941         void tools_hints ()
942         {
943                 if (!_hints_dialog) {
944                         _hints_dialog = new HintsDialog (this, _film, true);
945                 }
946
947                 _hints_dialog->Show ();
948         }
949
950         void tools_encoding_servers ()
951         {
952                 if (!_servers_list_dialog) {
953                         _servers_list_dialog = new ServersListDialog (this);
954                 }
955
956                 _servers_list_dialog->Show ();
957         }
958
959         void tools_manage_templates ()
960         {
961                 if (!_templates_dialog) {
962                         _templates_dialog = new TemplatesDialog (this);
963                 }
964
965                 _templates_dialog->Show ();
966         }
967
968         void tools_check_for_updates ()
969         {
970                 UpdateChecker::instance()->run ();
971                 _update_news_requested = true;
972         }
973
974         void help_about ()
975         {
976                 AboutDialog* d = new AboutDialog (this);
977                 d->ShowModal ();
978                 d->Destroy ();
979         }
980
981         void help_report_a_problem ()
982         {
983                 ReportProblemDialog* d = new ReportProblemDialog (this, _film);
984                 if (d->ShowModal () == wxID_OK) {
985                         d->report ();
986                 }
987                 d->Destroy ();
988         }
989
990         bool should_close ()
991         {
992                 if (!JobManager::instance()->work_to_do ()) {
993                         return true;
994                 }
995
996                 wxMessageDialog* d = new wxMessageDialog (
997                         0,
998                         _("There are unfinished jobs; are you sure you want to quit?"),
999                         _("Unfinished jobs"),
1000                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
1001                         );
1002
1003                 bool const r = d->ShowModal() == wxID_YES;
1004                 d->Destroy ();
1005                 return r;
1006         }
1007
1008         void close (wxCloseEvent& ev)
1009         {
1010                 if (!should_close ()) {
1011                         ev.Veto ();
1012                         return;
1013                 }
1014
1015                 if (_film && _film->dirty ()) {
1016
1017                         FilmChangedClosingDialog* dialog = new FilmChangedClosingDialog (_film->name ());
1018                         int const r = dialog->run ();
1019                         delete dialog;
1020
1021                         switch (r) {
1022                         case wxID_NO:
1023                                 /* Don't save and carry on to close */
1024                                 break;
1025                         case wxID_YES:
1026                                 /* Save and carry on to close */
1027                                 _film->write_metadata ();
1028                                 break;
1029                         case wxID_CANCEL:
1030                                 /* Veto the event and stop */
1031                                 ev.Veto ();
1032                                 return;
1033                         }
1034                 }
1035
1036                 /* We don't want to hear about any more configuration changes, since they
1037                    cause the File menu to be altered, which itself will be deleted around
1038                    now (without, as far as I can see, any way for us to find out).
1039                 */
1040                 _config_changed_connection.disconnect ();
1041
1042                 ev.Skip ();
1043         }
1044
1045         void set_menu_sensitivity ()
1046         {
1047                 list<shared_ptr<Job> > jobs = JobManager::instance()->get ();
1048                 list<shared_ptr<Job> >::iterator i = jobs.begin();
1049                 while (i != jobs.end() && (*i)->json_name() != "transcode") {
1050                         ++i;
1051                 }
1052                 bool const dcp_creation = (i != jobs.end ()) && !(*i)->finished ();
1053                 bool const have_cpl = _film && !_film->cpls().empty ();
1054                 bool const have_single_selected_content = _film_editor->content_panel()->selected().size() == 1;
1055                 bool const have_selected_content = !_film_editor->content_panel()->selected().empty();
1056                 bool const have_selected_video_content = !_film_editor->content_panel()->selected_video().empty();
1057
1058                 for (map<wxMenuItem*, int>::iterator j = menu_items.begin(); j != menu_items.end(); ++j) {
1059
1060                         bool enabled = true;
1061
1062                         if ((j->second & NEEDS_FILM) && !_film) {
1063                                 enabled = false;
1064                         }
1065
1066                         if ((j->second & NOT_DURING_DCP_CREATION) && dcp_creation) {
1067                                 enabled = false;
1068                         }
1069
1070                         if ((j->second & NEEDS_CPL) && !have_cpl) {
1071                                 enabled = false;
1072                         }
1073
1074                         if ((j->second & NEEDS_SELECTED_CONTENT) && !have_selected_content) {
1075                                 enabled = false;
1076                         }
1077
1078                         if ((j->second & NEEDS_SINGLE_SELECTED_CONTENT) && !have_single_selected_content) {
1079                                 enabled = false;
1080                         }
1081
1082                         if ((j->second & NEEDS_SELECTED_VIDEO_CONTENT) && !have_selected_video_content) {
1083                                 enabled = false;
1084                         }
1085
1086                         if ((j->second & NEEDS_CLIPBOARD) && !_clipboard) {
1087                                 enabled = false;
1088                         }
1089
1090                         if ((j->second & NEEDS_ENCRYPTION) && (!_film || !_film->encrypted())) {
1091                                 enabled = false;
1092                         }
1093
1094                         j->first->Enable (enabled);
1095                 }
1096         }
1097
1098         /** @return true if the operation that called this method
1099          *  should continue, false to abort it.
1100          */
1101         template <class T>
1102         bool maybe_save_film ()
1103         {
1104                 if (!_film) {
1105                         return true;
1106                 }
1107
1108                 if (_film->dirty ()) {
1109                         T d (_film->name ());
1110                         switch (d.run ()) {
1111                         case wxID_NO:
1112                                 return true;
1113                         case wxID_YES:
1114                                 _film->write_metadata ();
1115                                 return true;
1116                         case wxID_CANCEL:
1117                                 return false;
1118                         }
1119                 }
1120
1121                 return true;
1122         }
1123
1124         template <class T>
1125         bool maybe_save_then_delete_film ()
1126         {
1127                 bool const r = maybe_save_film<T> ();
1128                 if (r) {
1129                         _film.reset ();
1130                 }
1131                 return r;
1132         }
1133
1134         void add_item (wxMenu* menu, wxString text, int id, int sens)
1135         {
1136                 wxMenuItem* item = menu->Append (id, text);
1137                 menu_items.insert (make_pair (item, sens));
1138         }
1139
1140         void setup_menu (wxMenuBar* m)
1141         {
1142                 _file_menu = new wxMenu;
1143                 add_item (_file_menu, _("New...\tCtrl-N"), ID_file_new, ALWAYS);
1144                 add_item (_file_menu, _("&Open...\tCtrl-O"), ID_file_open, ALWAYS);
1145                 _file_menu->AppendSeparator ();
1146                 add_item (_file_menu, _("&Save\tCtrl-S"), ID_file_save, NEEDS_FILM);
1147                 _file_menu->AppendSeparator ();
1148                 add_item (_file_menu, _("Save as &template..."), ID_file_save_as_template, NEEDS_FILM);
1149                 add_item (_file_menu, _("Duplicate..."), ID_file_duplicate, NEEDS_FILM);
1150                 add_item (_file_menu, _("Duplicate and open..."), ID_file_duplicate_and_open, NEEDS_FILM);
1151
1152                 _history_position = _file_menu->GetMenuItems().GetCount();
1153
1154 #ifndef __WXOSX__
1155                 _file_menu->AppendSeparator ();
1156 #endif
1157
1158 #ifdef __WXOSX__
1159                 add_item (_file_menu, _("&Exit"), wxID_EXIT, ALWAYS);
1160 #else
1161                 add_item (_file_menu, _("&Quit"), wxID_EXIT, ALWAYS);
1162 #endif
1163
1164                 wxMenu* edit = new wxMenu;
1165                 add_item (edit, _("Copy settings\tCtrl-C"), ID_edit_copy, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_SINGLE_SELECTED_CONTENT);
1166                 add_item (edit, _("Paste settings...\tCtrl-V"), ID_edit_paste, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_SELECTED_CONTENT | NEEDS_CLIPBOARD);
1167
1168 #ifdef __WXOSX__
1169                 add_item (_file_menu, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
1170 #else
1171                 add_item (edit, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
1172 #endif
1173
1174                 wxMenu* content = new wxMenu;
1175                 add_item (content, _("Scale to fit &width"), ID_content_scale_to_fit_width, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
1176                 add_item (content, _("Scale to fit &height"), ID_content_scale_to_fit_height, NEEDS_FILM | NEEDS_SELECTED_VIDEO_CONTENT);
1177
1178                 wxMenu* jobs_menu = new wxMenu;
1179                 add_item (jobs_menu, _("&Make DCP\tCtrl-M"), ID_jobs_make_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION);
1180                 add_item (jobs_menu, _("Make DCP in &batch converter\tCtrl-B"), ID_jobs_make_dcp_batch, NEEDS_FILM | NOT_DURING_DCP_CREATION);
1181                 jobs_menu->AppendSeparator ();
1182                 add_item (jobs_menu, _("Make &KDMs...\tCtrl-K"), ID_jobs_make_kdms, NEEDS_FILM);
1183                 add_item (jobs_menu, _("Make DKDM for DCP-o-matic..."), ID_jobs_make_self_dkdm, NEEDS_FILM | NEEDS_ENCRYPTION);
1184                 jobs_menu->AppendSeparator ();
1185                 add_item (jobs_menu, _("Export...\tCtrl-E"), ID_jobs_export, NEEDS_FILM);
1186                 jobs_menu->AppendSeparator ();
1187                 add_item (jobs_menu, _("&Send DCP to TMS"), ID_jobs_send_dcp_to_tms, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
1188                 add_item (jobs_menu, _("S&how DCP"), ID_jobs_show_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
1189                 add_item (jobs_menu, _("Open DCP in &player"), ID_jobs_open_dcp_in_player, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
1190
1191                 wxMenu* view = new wxMenu;
1192                 add_item (view, _("Closed captions..."), ID_view_closed_captions, NEEDS_FILM);
1193                 add_item (view, _("Video waveform..."), ID_view_video_waveform, NEEDS_FILM);
1194
1195                 wxMenu* tools = new wxMenu;
1196                 add_item (tools, _("Hints..."), ID_tools_hints, 0);
1197                 add_item (tools, _("Encoding servers..."), ID_tools_encoding_servers, 0);
1198                 add_item (tools, _("Manage templates..."), ID_tools_manage_templates, 0);
1199                 add_item (tools, _("Check for updates"), ID_tools_check_for_updates, 0);
1200                 tools->AppendSeparator ();
1201                 add_item (tools, _("Restore default preferences"), ID_tools_restore_default_preferences, ALWAYS);
1202
1203                 wxMenu* help = new wxMenu;
1204 #ifdef __WXOSX__
1205                 add_item (help, _("About DCP-o-matic"), wxID_ABOUT, ALWAYS);
1206 #else
1207                 add_item (help, _("About"), wxID_ABOUT, ALWAYS);
1208 #endif
1209                 add_item (help, _("Report a problem..."), ID_help_report_a_problem, NEEDS_FILM);
1210
1211                 m->Append (_file_menu, _("&File"));
1212                 m->Append (edit, _("&Edit"));
1213                 m->Append (content, _("&Content"));
1214                 m->Append (jobs_menu, _("&Jobs"));
1215                 m->Append (view, _("&View"));
1216                 m->Append (tools, _("&Tools"));
1217                 m->Append (help, _("&Help"));
1218         }
1219
1220         void config_changed (Config::Property what)
1221         {
1222                 /* Instantly save any config changes when using the DCP-o-matic GUI */
1223                 if (what == Config::CINEMAS) {
1224                         try {
1225                                 Config::instance()->write_cinemas();
1226                         } catch (exception& e) {
1227                                 error_dialog (
1228                                         this,
1229                                         wxString::Format (
1230                                                 _("Could not write to cinemas file at %s.  Your changes have not been saved."),
1231                                                 std_to_wx (Config::instance()->cinemas_file().string()).data()
1232                                                 )
1233                                         );
1234                         }
1235                 } else {
1236                         try {
1237                                 Config::instance()->write_config();
1238                         } catch (exception& e) {
1239                                 error_dialog (
1240                                         this,
1241                                         wxString::Format (
1242                                                 _("Could not write to config file at %s.  Your changes have not been saved."),
1243                                                 std_to_wx (Config::instance()->cinemas_file().string()).data()
1244                                                 )
1245                                         );
1246                         }
1247                 }
1248
1249                 for (int i = 0; i < _history_items; ++i) {
1250                         delete _file_menu->Remove (ID_file_history + i);
1251                 }
1252
1253                 if (_history_separator) {
1254                         _file_menu->Remove (_history_separator);
1255                 }
1256                 delete _history_separator;
1257                 _history_separator = 0;
1258
1259                 int pos = _history_position;
1260
1261                 vector<boost::filesystem::path> history = Config::instance()->history ();
1262
1263                 if (!history.empty ()) {
1264                         _history_separator = _file_menu->InsertSeparator (pos++);
1265                 }
1266
1267                 for (size_t i = 0; i < history.size(); ++i) {
1268                         string s;
1269                         if (i < 9) {
1270                                 s = String::compose ("&%1 %2", i + 1, history[i].string());
1271                         } else {
1272                                 s = history[i].string();
1273                         }
1274                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s));
1275                 }
1276
1277                 _history_items = history.size ();
1278         }
1279
1280         void update_checker_state_changed ()
1281         {
1282                 UpdateChecker* uc = UpdateChecker::instance ();
1283
1284                 bool const announce =
1285                         _update_news_requested ||
1286                         (uc->stable() && Config::instance()->check_for_updates()) ||
1287                         (uc->test() && Config::instance()->check_for_updates() && Config::instance()->check_for_test_updates());
1288
1289                 _update_news_requested = false;
1290
1291                 if (!announce) {
1292                         return;
1293                 }
1294
1295                 if (uc->state() == UpdateChecker::YES) {
1296                         UpdateDialog* dialog = new UpdateDialog (this, uc->stable (), uc->test ());
1297                         dialog->ShowModal ();
1298                         dialog->Destroy ();
1299                 } else if (uc->state() == UpdateChecker::FAILED) {
1300                         error_dialog (this, _("The DCP-o-matic download server could not be contacted."));
1301                 } else {
1302                         error_dialog (this, _("There are no new versions of DCP-o-matic available."));
1303                 }
1304
1305                 _update_news_requested = false;
1306         }
1307
1308         void start_stop_pressed ()
1309         {
1310                 if (_film_viewer->playing()) {
1311                         _film_viewer->stop();
1312                 } else {
1313                         _film_viewer->start();
1314                 }
1315         }
1316
1317         void timeline_pressed ()
1318         {
1319                 _film_editor->content_panel()->timeline_clicked ();
1320         }
1321
1322         void back_frame ()
1323         {
1324                 _film_viewer->seek_by (-_film_viewer->one_video_frame(), true);
1325         }
1326
1327         void forward_frame ()
1328         {
1329                 _film_viewer->seek_by (_film_viewer->one_video_frame(), true);
1330         }
1331
1332         FilmEditor* _film_editor;
1333         boost::shared_ptr<FilmViewer> _film_viewer;
1334         Controls* _controls;
1335         VideoWaveformDialog* _video_waveform_dialog;
1336         HintsDialog* _hints_dialog;
1337         ServersListDialog* _servers_list_dialog;
1338         wxPreferencesEditor* _config_dialog;
1339         KDMDialog* _kdm_dialog;
1340         TemplatesDialog* _templates_dialog;
1341         wxMenu* _file_menu;
1342         shared_ptr<Film> _film;
1343         int _history_items;
1344         int _history_position;
1345         wxMenuItem* _history_separator;
1346         boost::signals2::scoped_connection _config_changed_connection;
1347         bool _update_news_requested;
1348         shared_ptr<Content> _clipboard;
1349 };
1350
1351 static const wxCmdLineEntryDesc command_line_description[] = {
1352         { wxCMD_LINE_SWITCH, "n", "new", "create new film", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
1353         { wxCMD_LINE_OPTION, "c", "content", "add content file / directory", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1354         { wxCMD_LINE_OPTION, "d", "dcp", "add content DCP", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1355         { wxCMD_LINE_PARAM, 0, 0, "film to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1356         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
1357 };
1358
1359 /** @class App
1360  *  @brief The magic App class for wxWidgets.
1361  */
1362 class App : public wxApp
1363 {
1364 public:
1365         App ()
1366                 : wxApp ()
1367                 , _frame (0)
1368         {}
1369
1370 private:
1371
1372         bool OnInit ()
1373         try
1374         {
1375                 wxInitAllImageHandlers ();
1376
1377                 Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
1378                 Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
1379
1380                 wxSplashScreen* splash = maybe_show_splash ();
1381
1382                 SetAppName (_("DCP-o-matic"));
1383
1384                 if (!wxApp::OnInit()) {
1385                         return false;
1386                 }
1387
1388 #ifdef DCPOMATIC_LINUX
1389                 unsetenv ("UBUNTU_MENUPROXY");
1390 #endif
1391
1392 #ifdef __WXOSX__
1393                 ProcessSerialNumber serial;
1394                 GetCurrentProcess (&serial);
1395                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
1396 #endif
1397
1398                 dcpomatic_setup_path_encoding ();
1399
1400                 /* Enable i18n; this will create a Config object
1401                    to look for a force-configured language.  This Config
1402                    object will be wrong, however, because dcpomatic_setup
1403                    hasn't yet been called and there aren't any filters etc.
1404                    set up yet.
1405                 */
1406                 dcpomatic_setup_i18n ();
1407
1408                 /* Set things up, including filters etc.
1409                    which will now be internationalised correctly.
1410                 */
1411                 dcpomatic_setup ();
1412
1413                 /* Force the configuration to be re-loaded correctly next
1414                    time it is needed.
1415                 */
1416                 Config::drop ();
1417
1418                 Config::BadSignerChain.connect (boost::bind (&App::config_bad_signer_chain, this));
1419
1420                 _frame = new DOMFrame (_("DCP-o-matic"));
1421                 SetTopWindow (_frame);
1422                 _frame->Maximize ();
1423                 if (splash) {
1424                         splash->Destroy ();
1425                 }
1426
1427                 if (!Config::instance()->nagged(Config::NAG_INITIAL_SETUP)) {
1428                         InitialSetupDialog* d = new InitialSetupDialog ();
1429                         d->ShowModal ();
1430                         d->Destroy ();
1431                         Config::instance()->set_nagged(Config::NAG_INITIAL_SETUP, true);
1432                 }
1433
1434                 _frame->Show ();
1435
1436                 if (!_film_to_load.empty() && boost::filesystem::is_directory (_film_to_load)) {
1437                         try {
1438                                 _frame->load_film (_film_to_load);
1439                         } catch (exception& e) {
1440                                 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()));
1441                         }
1442                 }
1443
1444                 if (!_film_to_create.empty ()) {
1445                         _frame->new_film (_film_to_create, optional<string> ());
1446                         if (!_content_to_add.empty ()) {
1447                                 BOOST_FOREACH (shared_ptr<Content> i, content_factory (_frame->film(), _content_to_add)) {
1448                                         _frame->film()->examine_and_add_content (i);
1449                                 }
1450                         }
1451                         if (!_dcp_to_add.empty ()) {
1452                                 _frame->film()->examine_and_add_content (shared_ptr<DCPContent> (new DCPContent (_frame->film(), _dcp_to_add)));
1453                         }
1454                 }
1455
1456                 signal_manager = new wxSignalManager (this);
1457                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
1458
1459                 Bind (wxEVT_TIMER, boost::bind (&App::check, this));
1460                 _timer.reset (new wxTimer (this));
1461                 _timer->Start (1000);
1462
1463                 if (Config::instance()->check_for_updates ()) {
1464                         UpdateChecker::instance()->run ();
1465                 }
1466
1467                 return true;
1468         }
1469         catch (exception& e)
1470         {
1471                 error_dialog (0, wxString::Format ("DCP-o-matic could not start."), std_to_wx(e.what()));
1472                 return true;
1473         }
1474
1475         void OnInitCmdLine (wxCmdLineParser& parser)
1476         {
1477                 parser.SetDesc (command_line_description);
1478                 parser.SetSwitchChars (wxT ("-"));
1479         }
1480
1481         bool OnCmdLineParsed (wxCmdLineParser& parser)
1482         {
1483                 if (parser.GetParamCount() > 0) {
1484                         if (parser.Found (wxT ("new"))) {
1485                                 _film_to_create = wx_to_std (parser.GetParam (0));
1486                         } else {
1487                                 _film_to_load = wx_to_std (parser.GetParam (0));
1488                         }
1489                 }
1490
1491                 wxString content;
1492                 if (parser.Found (wxT ("content"), &content)) {
1493                         _content_to_add = wx_to_std (content);
1494                 }
1495
1496                 wxString dcp;
1497                 if (parser.Found (wxT ("dcp"), &dcp)) {
1498                         _dcp_to_add = wx_to_std (dcp);
1499                 }
1500
1501                 return true;
1502         }
1503
1504         void report_exception ()
1505         {
1506                 try {
1507                         throw;
1508                 } catch (FileError& e) {
1509                         error_dialog (
1510                                 0,
1511                                 wxString::Format (
1512                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
1513                                         std_to_wx (e.what()),
1514                                         std_to_wx (e.file().string().c_str ())
1515                                         )
1516                                 );
1517                 } catch (exception& e) {
1518                         error_dialog (
1519                                 0,
1520                                 wxString::Format (
1521                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
1522                                         std_to_wx (e.what ())
1523                                         )
1524                                 );
1525                 } catch (...) {
1526                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
1527                 }
1528         }
1529
1530         /* An unhandled exception has occurred inside the main event loop */
1531         bool OnExceptionInMainLoop ()
1532         {
1533                 report_exception ();
1534                 /* This will terminate the program */
1535                 return false;
1536         }
1537
1538         void OnUnhandledException ()
1539         {
1540                 report_exception ();
1541         }
1542
1543         void idle ()
1544         {
1545                 signal_manager->ui_idle ();
1546         }
1547
1548         void check ()
1549         {
1550                 try {
1551                         EncodeServerFinder::instance()->rethrow ();
1552                 } catch (exception& e) {
1553                         error_dialog (0, std_to_wx (e.what ()));
1554                 }
1555         }
1556
1557         void config_failed_to_load ()
1558         {
1559                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
1560         }
1561
1562         void config_warning (string m)
1563         {
1564                 message_dialog (_frame, std_to_wx (m));
1565         }
1566
1567         bool config_bad_signer_chain ()
1568         {
1569                 if (Config::instance()->nagged(Config::NAG_BAD_SIGNER_CHAIN)) {
1570                         return false;
1571                 }
1572
1573                 RecreateChainDialog* d = new RecreateChainDialog (_frame);
1574                 int const r = d->ShowModal ();
1575                 d->Destroy ();
1576                 return r == wxID_OK;
1577         }
1578
1579         DOMFrame* _frame;
1580         shared_ptr<wxTimer> _timer;
1581         string _film_to_load;
1582         string _film_to_create;
1583         string _content_to_add;
1584         string _dcp_to_add;
1585 };
1586
1587 IMPLEMENT_APP (App)