Supporters update.
[dcpomatic.git] / src / tools / dcpomatic.cc
1 /*
2     Copyright (C) 2012-2021 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
22 /** @file  src/tools/dcpomatic.cc
23  *  @brief The main DCP-o-matic GUI.
24  */
25
26
27 #include "wx/about_dialog.h"
28 #include "wx/content_panel.h"
29 #include "wx/dkdm_dialog.h"
30 #include "wx/export_subtitles_dialog.h"
31 #include "wx/export_video_file_dialog.h"
32 #include "wx/film_editor.h"
33 #include "wx/film_name_location_dialog.h"
34 #include "wx/film_viewer.h"
35 #include "wx/focus_manager.h"
36 #include "wx/full_config_dialog.h"
37 #include "wx/hints_dialog.h"
38 #include "wx/html_dialog.h"
39 #include "wx/file_dialog.h"
40 #include "wx/i18n_hook.h"
41 #include "wx/id.h"
42 #include "wx/job_manager_view.h"
43 #include "wx/kdm_dialog.h"
44 #include "wx/nag_dialog.h"
45 #include "wx/paste_dialog.h"
46 #include "wx/recreate_chain_dialog.h"
47 #include "wx/report_problem_dialog.h"
48 #include "wx/save_template_dialog.h"
49 #include "wx/self_dkdm_dialog.h"
50 #include "wx/send_i18n_dialog.h"
51 #include "wx/servers_list_dialog.h"
52 #include "wx/standard_controls.h"
53 #include "wx/system_information_dialog.h"
54 #include "wx/templates_dialog.h"
55 #include "wx/update_dialog.h"
56 #include "wx/video_waveform_dialog.h"
57 #include "wx/wx_signal_manager.h"
58 #include "wx/wx_util.h"
59 #include "lib/analytics.h"
60 #include "lib/audio_content.h"
61 #include "lib/check_content_job.h"
62 #include "lib/cinema.h"
63 #include "lib/compose.hpp"
64 #include "lib/config.h"
65 #include "lib/constants.h"
66 #include "lib/content.h"
67 #include "lib/content_factory.h"
68 #include "lib/cross.h"
69 #include "lib/cross.h"
70 #include "lib/dcp_content.h"
71 #include "lib/dcpomatic_log.h"
72 #include "lib/dcpomatic_socket.h"
73 #include "lib/dkdm_wrapper.h"
74 #include "lib/email.h"
75 #include "lib/encode_server_finder.h"
76 #include "lib/exceptions.h"
77 #include "lib/ffmpeg_encoder.h"
78 #include "lib/film.h"
79 #include "lib/font_config.h"
80 #include "lib/hints.h"
81 #include "lib/job_manager.h"
82 #include "lib/kdm_with_metadata.h"
83 #include "lib/log.h"
84 #include "lib/make_dcp.h"
85 #include "lib/release_notes.h"
86 #include "lib/screen.h"
87 #include "lib/send_kdm_email_job.h"
88 #include "lib/signal_manager.h"
89 #include "lib/subtitle_encoder.h"
90 #include "lib/text_content.h"
91 #include "lib/transcode_job.h"
92 #include "lib/update_checker.h"
93 #include "lib/version.h"
94 #include "lib/video_content.h"
95 #include <dcp/exceptions.h>
96 #include <dcp/filesystem.h>
97 #include <dcp/raw_convert.h>
98 #include <dcp/warnings.h>
99 LIBDCP_DISABLE_WARNINGS
100 #include <wx/cmdline.h>
101 #include <wx/generic/aboutdlgg.h>
102 #include <wx/preferences.h>
103 #include <wx/splash.h>
104 #include <wx/stdpaths.h>
105 #include <wx/wxhtml.h>
106 LIBDCP_ENABLE_WARNINGS
107 #ifdef __WXGTK__
108 #include <X11/Xlib.h>
109 #endif
110 #ifdef __WXMSW__
111 #include <shellapi.h>
112 #endif
113 #include <boost/algorithm/string.hpp>
114 #include <boost/filesystem.hpp>
115 #include <iostream>
116 #include <fstream>
117 /* This is OK as it's only used with DCPOMATIC_WINDOWS */
118 #include <sstream>
119
120 #ifdef check
121 #undef check
122 #endif
123
124
125 using std::cout;
126 using std::dynamic_pointer_cast;
127 using std::exception;
128 using std::function;
129 using std::list;
130 using std::make_pair;
131 using std::make_shared;
132 using std::map;
133 using std::shared_ptr;
134 using std::string;
135 using std::vector;
136 using std::wcout;
137 using boost::optional;
138 using boost::is_any_of;
139 using boost::algorithm::find;
140 #if BOOST_VERSION >= 106100
141 using namespace boost::placeholders;
142 #endif
143 using dcp::raw_convert;
144
145
146 class FilmChangedClosingDialog
147 {
148 public:
149         explicit FilmChangedClosingDialog (string name)
150                 : _dialog(
151                         nullptr,
152                         wxString::Format(_("Save changes to film \"%s\" before closing?"), std_to_wx (name).data()),
153                         /// TRANSLATORS: this is the heading for a dialog box, which tells the user that the current
154                         /// project (Film) has been changed since it was last saved.
155                         _("Film changed"),
156                         wxYES_NO | wxCANCEL | wxYES_DEFAULT | wxICON_QUESTION
157                         )
158         {
159                 _dialog.SetYesNoCancelLabels(
160                         _("Save film and close"), _("Close without saving film"), _("Don't close")
161                         );
162         }
163
164         int run ()
165         {
166                 return _dialog.ShowModal();
167         }
168
169 private:
170         wxMessageDialog _dialog;
171 };
172
173
174 class FilmChangedDuplicatingDialog
175 {
176 public:
177         explicit FilmChangedDuplicatingDialog (string name)
178                 : _dialog(
179                         nullptr,
180                         wxString::Format(_("Save changes to film \"%s\" before duplicating?"), std_to_wx (name).data()),
181                         /// TRANSLATORS: this is the heading for a dialog box, which tells the user that the current
182                         /// project (Film) has been changed since it was last saved.
183                         _("Film changed"),
184                         wxYES_NO | wxCANCEL | wxYES_DEFAULT | wxICON_QUESTION
185                         )
186         {
187                 _dialog.SetYesNoCancelLabels(
188                         _("Save film and duplicate"), _("Duplicate without saving film"), _("Don't duplicate")
189                         );
190         }
191
192         int run ()
193         {
194                 return _dialog.ShowModal();
195         }
196
197 private:
198         wxMessageDialog _dialog;
199 };
200
201
202 #define ALWAYS                        0x0
203 #define NEEDS_FILM                    0x1
204 #define NOT_DURING_DCP_CREATION       0x2
205 #define NEEDS_CPL                     0x4
206 #define NEEDS_SINGLE_SELECTED_CONTENT 0x8
207 #define NEEDS_SELECTED_CONTENT        0x10
208 #define NEEDS_SELECTED_VIDEO_CONTENT  0x20
209 #define NEEDS_CLIPBOARD               0x40
210 #define NEEDS_ENCRYPTION              0x80
211
212
213 map<wxMenuItem*, int> menu_items;
214
215 enum {
216         ID_file_new = DCPOMATIC_MAIN_MENU,
217         ID_file_open,
218         ID_file_save,
219         ID_file_save_as_template,
220         ID_file_duplicate,
221         ID_file_duplicate_and_open,
222         ID_file_history,
223         /* Allow spare IDs after _history for the recent files list */
224         ID_file_close = DCPOMATIC_MAIN_MENU + 100,
225         ID_edit_copy,
226         ID_edit_paste,
227         ID_edit_select_all,
228         ID_jobs_make_dcp,
229         ID_jobs_make_dcp_batch,
230         ID_jobs_make_kdms,
231         ID_jobs_make_dkdms,
232         ID_jobs_make_self_dkdm,
233         ID_jobs_export_video_file,
234         ID_jobs_export_subtitles,
235         ID_jobs_send_dcp_to_tms,
236         ID_jobs_show_dcp,
237         ID_jobs_open_dcp_in_player,
238         ID_view_closed_captions,
239         ID_view_video_waveform,
240         ID_tools_hints,
241         ID_tools_encoding_servers,
242         ID_tools_manage_templates,
243         ID_tools_check_for_updates,
244         ID_tools_send_translations,
245         ID_tools_system_information,
246         ID_tools_restore_default_preferences,
247         ID_tools_export_preferences,
248         ID_tools_import_preferences,
249         ID_help_report_a_problem,
250         /* IDs for shortcuts (with no associated menu item) */
251         ID_add_file,
252         ID_remove,
253         ID_start_stop,
254         ID_timeline,
255         ID_back_frame,
256         ID_forward_frame
257 };
258
259
260 class LimitedFrameSplitter : public wxSplitterWindow
261 {
262 public:
263         LimitedFrameSplitter(wxWindow* parent)
264                 : wxSplitterWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_NOBORDER | wxSP_3DSASH | wxSP_LIVE_UPDATE)
265         {
266                 /* This value doesn't really mean much but we just want to stop double-click on the
267                    divider from shrinking the left panel.
268                    */
269                 SetMinimumPaneSize(64);
270
271                 Bind(wxEVT_SIZE, boost::bind(&LimitedFrameSplitter::sized, this, _1));
272         }
273
274         bool OnSashPositionChange(int new_position) override
275         {
276                 /* Try to stop the left bit of the splitter getting too small */
277                 auto const ok = new_position > _left_panel_minimum_size;
278                 if (ok) {
279                         Config::instance()->set_main_divider_sash_position(new_position);
280                 }
281                 return ok;
282         }
283
284 private:
285         void sized(wxSizeEvent& ev)
286         {
287                 if (GetSize().GetWidth() > _left_panel_minimum_size && GetSashPosition() < _left_panel_minimum_size) {
288                         /* The window is now fairly big but the left panel is small; this happens when the DCP-o-matic window
289                          * is shrunk and then made larger again.  Try to set a sensible left panel size in this case.
290                          */
291                         SetSashPosition(Config::instance()->main_divider_sash_position().get_value_or(_left_panel_minimum_size));
292                 }
293
294                 ev.Skip();
295         }
296
297         int const _left_panel_minimum_size = 200;
298 };
299
300
301 class DOMFrame : public wxFrame
302 {
303 public:
304         explicit DOMFrame (wxString const& title)
305                 : wxFrame (nullptr, -1, title)
306                 /* Use a panel as the only child of the Frame so that we avoid
307                    the dark-grey background on Windows.
308                 */
309                 , _splitter(new LimitedFrameSplitter(this))
310                 , _right_panel(new wxPanel(_splitter, wxID_ANY))
311                 , _film_viewer(_right_panel)
312         {
313
314                 auto bar = new wxMenuBar;
315                 setup_menu (bar);
316                 SetMenuBar (bar);
317
318 #ifdef DCPOMATIC_WINDOWS
319                 SetIcon (wxIcon (std_to_wx ("id")));
320 #endif
321
322                 _config_changed_connection = Config::instance()->Changed.connect(boost::bind(&DOMFrame::config_changed, this, _1));
323                 config_changed (Config::OTHER);
324
325                 _analytics_message_connection = Analytics::instance()->Message.connect(boost::bind(&DOMFrame::analytics_message, this, _1, _2));
326
327                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_new, this),                ID_file_new);
328                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_open, this),               ID_file_open);
329                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_save, this),               ID_file_save);
330                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_save_as_template, this),   ID_file_save_as_template);
331                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_duplicate, this),          ID_file_duplicate);
332                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_duplicate_and_open, this), ID_file_duplicate_and_open);
333                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_close, this),              ID_file_close);
334                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_history, this, _1),        ID_file_history, ID_file_history + HISTORY_SIZE);
335                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this),               wxID_EXIT);
336                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_copy, this),               ID_edit_copy);
337                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_paste, this),              ID_edit_paste);
338                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_select_all, this),         ID_edit_select_all);
339                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this),        wxID_PREFERENCES);
340                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_dcp, this),           ID_jobs_make_dcp);
341                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_kdms, this),          ID_jobs_make_kdms);
342                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_dkdms, this),         ID_jobs_make_dkdms);
343                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_dcp_batch, this),     ID_jobs_make_dcp_batch);
344                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_make_self_dkdm, this),     ID_jobs_make_self_dkdm);
345                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_export_video_file, this),  ID_jobs_export_video_file);
346                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_export_subtitles, this),   ID_jobs_export_subtitles);
347                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_send_dcp_to_tms, this),    ID_jobs_send_dcp_to_tms);
348                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_show_dcp, this),           ID_jobs_show_dcp);
349                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::jobs_open_dcp_in_player, this), ID_jobs_open_dcp_in_player);
350                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_closed_captions, this),    ID_view_closed_captions);
351                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_video_waveform, this),     ID_view_video_waveform);
352                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_hints, this),             ID_tools_hints);
353                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_encoding_servers, this),  ID_tools_encoding_servers);
354                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_manage_templates, this),  ID_tools_manage_templates);
355                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_check_for_updates, this), ID_tools_check_for_updates);
356                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_send_translations, this), ID_tools_send_translations);
357                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_system_information, this),ID_tools_system_information);
358                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_restore_default_preferences, this), ID_tools_restore_default_preferences);
359                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_export_preferences, this), ID_tools_export_preferences);
360                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_import_preferences, this), ID_tools_import_preferences);
361                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this),              wxID_ABOUT);
362                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this),   ID_help_report_a_problem);
363
364                 Bind (wxEVT_CLOSE_WINDOW, boost::bind (&DOMFrame::close, this, _1));
365                 Bind (wxEVT_SHOW, boost::bind (&DOMFrame::show, this, _1));
366
367                 auto left_panel = new wxPanel(_splitter, wxID_ANY);
368
369                 _film_editor = new FilmEditor(left_panel, _film_viewer);
370
371                 auto left_sizer = new wxBoxSizer(wxHORIZONTAL);
372                 left_sizer->Add(_film_editor, 1, wxEXPAND);
373
374                 left_panel->SetSizerAndFit(left_sizer);
375
376                 _controls = new StandardControls(_right_panel, _film_viewer, true);
377                 _controls->set_film(_film_viewer.film());
378                 auto job_manager_view = new JobManagerView(_right_panel, false);
379
380                 auto right_sizer = new wxBoxSizer (wxVERTICAL);
381                 right_sizer->Add(_film_viewer.panel(), 2, wxEXPAND | wxALL, 6);
382                 right_sizer->Add (_controls, 0, wxEXPAND | wxALL, 6);
383                 right_sizer->Add (job_manager_view, 1, wxEXPAND | wxALL, 6);
384
385                 _right_panel->SetSizer(right_sizer);
386
387                 _splitter->SplitVertically(left_panel, _right_panel, Config::instance()->main_divider_sash_position().get_value_or(left_panel->GetSize().GetWidth() + 8));
388
389                 set_menu_sensitivity ();
390
391                 _film_editor->content_panel()->SelectionChanged.connect (boost::bind (&DOMFrame::set_menu_sensitivity, this));
392                 set_title ();
393
394                 JobManager::instance()->ActiveJobsChanged.connect(boost::bind(&DOMFrame::active_jobs_changed, this));
395
396                 UpdateChecker::instance()->StateChanged.connect(boost::bind(&DOMFrame::update_checker_state_changed, this));
397
398                 FocusManager::instance()->SetFocus.connect (boost::bind (&DOMFrame::remove_accelerators, this));
399                 FocusManager::instance()->KillFocus.connect (boost::bind (&DOMFrame::add_accelerators, this));
400                 add_accelerators ();
401         }
402
403         void add_accelerators ()
404         {
405 #ifdef __WXOSX__
406                 int accelerators = 7;
407 #else
408                 int accelerators = 6;
409 #endif
410                 std::vector<wxAcceleratorEntry> accel(accelerators);
411                 /* [Shortcut] Ctrl+A:Add file(s) to the film */
412                 accel[0].Set (wxACCEL_CTRL, static_cast<int>('A'), ID_add_file);
413                 /* [Shortcut] Delete:Remove selected content from film */
414                 accel[1].Set (wxACCEL_NORMAL, WXK_DELETE, ID_remove);
415                 /* [Shortcut] Space:Start/stop playback */
416                 accel[2].Set (wxACCEL_NORMAL, WXK_SPACE, ID_start_stop);
417                 /* [Shortcut] Ctrl+T:Open timeline window */
418                 accel[3].Set (wxACCEL_CTRL, static_cast<int>('T'), ID_timeline);
419                 /* [Shortcut] Left arrow:Move back one frame */
420                 accel[4].Set (wxACCEL_NORMAL, WXK_LEFT, ID_back_frame);
421                 /* [Shortcut] Right arrow:Move forward one frame */
422                 accel[5].Set (wxACCEL_NORMAL, WXK_RIGHT, ID_forward_frame);
423 #ifdef __WXOSX__
424                 accel[6].Set (wxACCEL_CTRL, static_cast<int>('W'), ID_file_close);
425 #endif
426                 Bind (wxEVT_MENU, boost::bind (&ContentPanel::add_file_clicked, _film_editor->content_panel()), ID_add_file);
427                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::remove_clicked, this, _1), ID_remove);
428                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::start_stop_pressed, this), ID_start_stop);
429                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::timeline_pressed, this), ID_timeline);
430                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::back_frame, this), ID_back_frame);
431                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::forward_frame, this), ID_forward_frame);
432                 wxAcceleratorTable accel_table (accelerators, accel.data());
433                 SetAcceleratorTable (accel_table);
434         }
435
436         void remove_accelerators ()
437         {
438                 SetAcceleratorTable (wxAcceleratorTable ());
439         }
440
441         void remove_clicked (wxCommandEvent& ev)
442         {
443                 if (_film_editor->content_panel()->remove_clicked (true)) {
444                         ev.Skip ();
445                 }
446         }
447
448         void new_film (boost::filesystem::path path, optional<string> template_name)
449         {
450                 auto film = make_shared<Film>(path);
451                 if (template_name) {
452                         film->use_template (template_name.get());
453                 }
454                 film->set_name (path.filename().generic_string());
455                 film->write_metadata ();
456                 set_film (film);
457         }
458
459         void load_film (boost::filesystem::path file)
460         try
461         {
462                 auto film = make_shared<Film>(file);
463                 auto const notes = film->read_metadata ();
464
465                 if (film->state_version() == 4) {
466                         error_dialog (
467                                 0,
468                                 _("This film was created with an old version of DVD-o-matic and may not load correctly "
469                                   "in this version.  Please check the film's settings carefully.")
470                                 );
471                 }
472
473                 for (auto i: notes) {
474                         error_dialog (0, std_to_wx(i));
475                 }
476
477                 set_film (film);
478
479                 JobManager::instance()->add(make_shared<CheckContentJob>(film));
480         }
481         catch (FileNotFoundError& e) {
482                 auto const dir = e.file().parent_path();
483                 if (dcp::filesystem::exists(dir / "ASSETMAP") || dcp::filesystem::exists(dir / "ASSETMAP.xml")) {
484                         error_dialog (
485                                 this, _("Could not open this folder as a DCP-o-matic project."),
486                                 _("It looks like you are trying to open a DCP.  File -> Open is for loading DCP-o-matic projects, not DCPs.  To import a DCP, create a new project with File -> New and then click the \"Add DCP...\" button.")
487                                 );
488                 } else {
489                         auto const p = std_to_wx(file.string ());
490                         error_dialog (this, wxString::Format(_("Could not open film at %s"), p.data()), std_to_wx(e.what()));
491                 }
492
493         } catch (std::exception& e) {
494                 auto const p = std_to_wx (file.string());
495                 error_dialog (this, wxString::Format(_("Could not open film at %s"), p.data()), std_to_wx(e.what()));
496         }
497
498         void set_film (shared_ptr<Film> film)
499         {
500                 _film = film;
501                 _film_viewer.set_film(_film);
502                 _film_editor->set_film(_film);
503                 _controls->set_film (_film);
504                 _video_waveform_dialog.reset();
505                 set_menu_sensitivity ();
506                 if (_film && _film->directory()) {
507                         Config::instance()->add_to_history (_film->directory().get());
508                 }
509                 if (_film) {
510                         _film->Change.connect (boost::bind (&DOMFrame::film_change, this, _1));
511                         _film->Message.connect (boost::bind(&DOMFrame::film_message, this, _1));
512                         _film->DirtyChange.connect (boost::bind(&DOMFrame::set_title, this));
513                         dcpomatic_log = _film->log ();
514                 }
515                 set_title ();
516         }
517
518         shared_ptr<Film> film () const {
519                 return _film;
520         }
521
522 private:
523
524         void show (wxShowEvent& ev)
525         {
526                 if (ev.IsShown() && !_first_shown_called) {
527                         _film_editor->first_shown ();
528                         _first_shown_called = true;
529                 }
530         }
531
532         void film_message (string m)
533         {
534                 message_dialog (this, std_to_wx(m));
535         }
536
537         void film_change (ChangeType type)
538         {
539                 if (type == ChangeType::DONE) {
540                         set_menu_sensitivity ();
541                 }
542         }
543
544         void file_new ()
545         {
546                 FilmNameLocationDialog dialog(this, _("New Film"), true);
547                 int const r = dialog.ShowModal();
548
549                 if (r != wxID_OK || !dialog.check_path() || !maybe_save_then_delete_film<FilmChangedClosingDialog>()) {
550                         return;
551                 }
552
553                 try {
554                         new_film(dialog.path(), dialog.template_name());
555                 } catch (boost::filesystem::filesystem_error& e) {
556 #ifdef DCPOMATIC_WINDOWS
557                         string bad_chars = "<>:\"/|?*";
558                         string const filename = dialog.path().filename().string();
559                         string found_bad_chars;
560                         for (size_t i = 0; i < bad_chars.length(); ++i) {
561                                 if (filename.find(bad_chars[i]) != string::npos && found_bad_chars.find(bad_chars[i]) == string::npos) {
562                                         found_bad_chars += bad_chars[i];
563                                 }
564                         }
565                         wxString message = _("Could not create folder to store film.");
566                         message += "  ";
567                         if (!found_bad_chars.empty()) {
568                                 message += wxString::Format (_("Try removing the %s characters from your folder name."), std_to_wx(found_bad_chars).data());
569                         } else {
570                                 message += _("Please check that you do not have Windows controlled folder access enabled for DCP-o-matic.");
571                         }
572                         error_dialog (this, message, std_to_wx(e.what()));
573 #else
574                         error_dialog (this, _("Could not create folder to store film."), std_to_wx(e.what()));
575 #endif
576                 }
577         }
578
579         void file_open ()
580         {
581                 wxDirDialog dialog(
582                         this,
583                         _("Select film to open"),
584                         std_to_wx (Config::instance()->default_directory_or (wx_to_std (wxStandardPaths::Get().GetDocumentsDir())).string ()),
585                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
586                         );
587
588                 int r;
589                 while (true) {
590                         r = dialog.ShowModal();
591                         if (r == wxID_OK && dialog.GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
592                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
593                         } else {
594                                 break;
595                         }
596                 }
597
598                 if (r == wxID_OK && maybe_save_then_delete_film<FilmChangedClosingDialog>()) {
599                         load_film(wx_to_std(dialog.GetPath()));
600                 }
601         }
602
603         void file_save ()
604         {
605                 try {
606                         _film->write_metadata ();
607                 } catch (exception& e) {
608                         error_dialog(this, _("Could not save project."), std_to_wx(e.what()));
609                 }
610         }
611
612         void file_save_as_template ()
613         {
614                 SaveTemplateDialog dialog(this);
615                 if (dialog.ShowModal() == wxID_OK) {
616                         try {
617                                 Config::instance()->save_template(_film, dialog.name());
618                         } catch (exception& e) {
619                                 error_dialog(this, _("Could not save template."), std_to_wx(e.what()));
620                         }
621                 }
622         }
623
624         void file_duplicate ()
625         {
626                 FilmNameLocationDialog dialog(this, _("Duplicate Film"), false);
627
628                 if (dialog.ShowModal() == wxID_OK && dialog.check_path() && maybe_save_film<FilmChangedDuplicatingDialog>()) {
629                         auto film = make_shared<Film>(dialog.path());
630                         film->copy_from (_film);
631                         film->set_name(dialog.path().filename().generic_string());
632                         try {
633                                 film->write_metadata();
634                         } catch (exception& e) {
635                                 error_dialog(this, _("Could not duplicate project."), std_to_wx(e.what()));
636                         }
637                 }
638         }
639
640         void file_duplicate_and_open ()
641         {
642                 FilmNameLocationDialog dialog(this, _("Duplicate Film"), false);
643
644                 if (dialog.ShowModal() == wxID_OK && dialog.check_path() && maybe_save_film<FilmChangedDuplicatingDialog>()) {
645                         auto film = make_shared<Film>(dialog.path());
646                         film->copy_from (_film);
647                         film->set_name(dialog.path().filename().generic_string());
648                         try {
649                                 film->write_metadata ();
650                                 set_film (film);
651                         } catch (exception& e) {
652                                 error_dialog(this, _("Could not duplicate project."), std_to_wx(e.what()));
653                         }
654                 }
655         }
656
657         void file_close ()
658         {
659                 if (_film && _film->dirty ()) {
660                         FilmChangedClosingDialog dialog(_film->name());
661                         switch (dialog.run()) {
662                         case wxID_NO:
663                                 /* Don't save and carry on to close */
664                                 break;
665                         case wxID_YES:
666                                 /* Save and carry on to close */
667                                 _film->write_metadata ();
668                                 break;
669                         case wxID_CANCEL:
670                                 /* Stop */
671                                 return;
672                         }
673                 }
674
675                 set_film (shared_ptr<Film>());
676         }
677
678         void file_history (wxCommandEvent& event)
679         {
680                 auto history = Config::instance()->history ();
681                 int n = event.GetId() - ID_file_history;
682                 if (n >= 0 && n < static_cast<int> (history.size ()) && maybe_save_then_delete_film<FilmChangedClosingDialog>()) {
683                         load_film (history[n]);
684                 }
685         }
686
687         void file_exit ()
688         {
689                 /* false here allows the close handler to veto the close request */
690                 Close (false);
691         }
692
693         void edit_copy ()
694         {
695                 auto const sel = _film_editor->content_panel()->selected();
696                 if (sel.size() == 1) {
697                         _clipboard = sel.front()->clone();
698                 }
699         }
700
701         void edit_paste ()
702         {
703                 if (!_clipboard) {
704                         return;
705                 }
706
707                 PasteDialog dialog(this, static_cast<bool>(_clipboard->video), static_cast<bool>(_clipboard->audio), !_clipboard->text.empty());
708                 if (dialog.ShowModal() != wxID_OK) {
709                         return;
710                 }
711
712                 for (auto i: _film_editor->content_panel()->selected()) {
713                         if (dialog.video() && i->video) {
714                                 DCPOMATIC_ASSERT (_clipboard->video);
715                                 i->video->take_settings_from (_clipboard->video);
716                         }
717                         if (dialog.audio() && i->audio) {
718                                 DCPOMATIC_ASSERT (_clipboard->audio);
719                                 i->audio->take_settings_from (_clipboard->audio);
720                         }
721
722                         if (dialog.text()) {
723                                 auto j = i->text.begin ();
724                                 auto k = _clipboard->text.begin ();
725                                 while (j != i->text.end() && k != _clipboard->text.end()) {
726                                         (*j)->take_settings_from (*k);
727                                         ++j;
728                                         ++k;
729                                 }
730                         }
731                 }
732         }
733
734         void edit_select_all ()
735         {
736                 _film_editor->content_panel()->select_all();
737         }
738
739         void edit_preferences ()
740         {
741                 if (!_config_dialog) {
742                         _config_dialog = create_full_config_dialog ();
743                 }
744                 _config_dialog->Show (this);
745         }
746
747         void tools_restore_default_preferences ()
748         {
749                 wxMessageDialog dialog(
750                         nullptr,
751                         _("Are you sure you want to restore preferences to their defaults?  This cannot be undone."),
752                         _("Restore default preferences"),
753                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
754                         );
755
756                 if (dialog.ShowModal() == wxID_YES) {
757                         Config::restore_defaults ();
758                 }
759         }
760
761         void tools_export_preferences ()
762         {
763                 FileDialog dialog(
764                         this, _("Specify ZIP file"), wxT("ZIP files (*.zip)|*.zip"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT, "Preferences", string("dcpomatic_config.zip")
765                         );
766
767                 if (dialog.ShowModal() == wxID_OK) {
768                         auto const path = boost::filesystem::path(wx_to_std(dialog.GetPath()));
769                         if (boost::filesystem::exists(path)) {
770                                 boost::system::error_code ec;
771                                 boost::filesystem::remove(path, ec);
772                                 if (ec) {
773                                         error_dialog(nullptr, _("Could not remove existing preferences file"), std_to_wx(path.string()));
774                                         return;
775                                 }
776                         }
777
778                         save_all_config_as_zip(path);
779                 }
780         }
781
782         void tools_import_preferences()
783         {
784                 FileDialog dialog(this, _("Specify ZIP file"), wxT("ZIP files (*.zip)|*.zip"), wxFD_OPEN, "Preferences");
785
786                 if (dialog.show()) {
787                         Config::instance()->load_from_zip(dialog.path());
788                 }
789         }
790
791         void jobs_make_dcp ()
792         {
793                 double required;
794                 double available;
795                 bool can_hard_link;
796
797                 if (!_film->should_be_enough_disk_space (required, available, can_hard_link)) {
798                         wxString message;
799                         if (can_hard_link) {
800                                 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);
801                         } else {
802                                 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);
803                         }
804                         if (!confirm_dialog (this, message)) {
805                                 return;
806                         }
807                 }
808
809                 if (Config::instance()->show_hints_before_make_dcp()) {
810                         HintsDialog hints(this, _film, false);
811                         if (hints.ShowModal() == wxID_CANCEL) {
812                                 return;
813                         }
814                 }
815
816                 if (_film->encrypted ()) {
817                         NagDialog::maybe_nag (
818                                 this,
819                                 Config::NAG_ENCRYPTED_METADATA,
820                                 _("You are making an encrypted DCP.  It will not be possible to make KDMs for this DCP unless you have copies of "
821                                   "the <tt>metadata.xml</tt> file within the film and the metadata files within the DCP.\n\n"
822                                   "You should ensure that these files are <span weight=\"bold\" size=\"larger\">BACKED UP</span> "
823                                   "if you want to make KDMs for this film.")
824                                 );
825                 }
826
827                 /* Remove any existing DCP if the user agrees */
828                 auto const dcp_dir = _film->dir (_film->dcp_name(), false);
829                 if (dcp::filesystem::exists(dcp_dir)) {
830                         if (!confirm_dialog (this, wxString::Format (_("Do you want to overwrite the existing DCP %s?"), std_to_wx(dcp_dir.string()).data()))) {
831                                 return;
832                         }
833                         dcp::filesystem::remove_all(dcp_dir);
834                 }
835
836                 try {
837                         /* It seems to make sense to auto-save metadata here, since the make DCP may last
838                            a long time, and crashes/power failures are moderately likely.
839                         */
840                         _film->write_metadata ();
841                         make_dcp (_film, TranscodeJob::ChangedBehaviour::EXAMINE_THEN_STOP);
842                 } catch (BadSettingError& e) {
843                         error_dialog (this, wxString::Format (_("Bad setting for %s."), std_to_wx(e.setting()).data()), std_to_wx(e.what()));
844                 } catch (std::exception& e) {
845                         error_dialog (this, wxString::Format (_("Could not make DCP.")), std_to_wx(e.what()));
846                 }
847         }
848
849         void jobs_make_kdms ()
850         {
851                 if (!_film) {
852                         return;
853                 }
854
855                 _kdm_dialog.reset(this, _film);
856                 _kdm_dialog->Show ();
857         }
858
859         void jobs_make_dkdms ()
860         {
861                 if (!_film) {
862                         return;
863                 }
864
865                 _dkdm_dialog.reset(this, _film);
866                 _dkdm_dialog->Show ();
867         }
868
869         /** @return false if we succeeded, true if not */
870         bool send_to_other_tool (int port, function<void()> start, string message)
871         {
872                 /* i = 0; try to connect via socket
873                    i = 1; try again, and then try to start the tool
874                    i = 2 onwards; try again.
875                 */
876                 for (int i = 0; i < 8; ++i) {
877                         try {
878                                 boost::asio::io_service io_service;
879                                 boost::asio::ip::tcp::resolver resolver (io_service);
880                                 boost::asio::ip::tcp::resolver::query query ("127.0.0.1", raw_convert<string> (port));
881                                 boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query);
882                                 Socket socket (5);
883                                 socket.connect (*endpoint_iterator);
884                                 DCPOMATIC_ASSERT (_film->directory ());
885                                 socket.write (message.length() + 1);
886                                 socket.write ((uint8_t *) message.c_str(), message.length() + 1);
887                                 /* OK\0 */
888                                 uint8_t ok[3];
889                                 socket.read (ok, 3);
890                                 return false;
891                         } catch (exception& e) {
892
893                         }
894
895                         if (i == 1) {
896                                 start ();
897                         }
898
899                         dcpomatic_sleep_seconds (1);
900                 }
901
902                 return true;
903         }
904
905         void jobs_make_dcp_batch ()
906         {
907                 if (!_film) {
908                         return;
909                 }
910
911                 if (Config::instance()->show_hints_before_make_dcp()) {
912                         HintsDialog hints(this, _film, false);
913                         if (hints.ShowModal() == wxID_CANCEL) {
914                                 return;
915                         }
916                 }
917
918                 _film->write_metadata ();
919
920                 if (send_to_other_tool (BATCH_JOB_PORT, &start_batch_converter, _film->directory()->string())) {
921 #ifdef DCPOMATIC_OSX
922                         error_dialog (this, _("Could not start the batch converter.  You may need to download it from dcpomatic.com."));
923 #else
924                         error_dialog (this, _("Could not find batch converter."));
925 #endif
926                 }
927         }
928
929         void jobs_open_dcp_in_player ()
930         {
931                 if (!_film) {
932                         return;
933                 }
934
935                 if (send_to_other_tool (PLAYER_PLAY_PORT, &start_player, _film->dir(_film->dcp_name(false)).string())) {
936 #ifdef DCPOMATIC_OSX
937                         error_dialog (this, _("Could not start the player.  You may need to download it from dcpomatic.com."));
938 #else
939                         error_dialog (this, _("Could not find player."));
940 #endif
941                 }
942         }
943
944         void jobs_make_self_dkdm ()
945         {
946                 if (!_film) {
947                         return;
948                 }
949
950                 SelfDKDMDialog dialog(this, _film);
951                 if (dialog.ShowModal() != wxID_OK) {
952                         return;
953                 }
954
955                 NagDialog::maybe_nag (
956                         this,
957                         Config::NAG_DKDM_CONFIG,
958                         wxString::Format (
959                                 _("You are making a DKDM which is encrypted by a private key held in"
960                                   "\n\n<tt>%s</tt>\n\nIt is <span weight=\"bold\" size=\"larger\">VITALLY IMPORTANT</span> "
961                                   "that you <span weight=\"bold\" size=\"larger\">BACK UP THIS FILE</span> since if it is lost "
962                                   "your DKDMs (and the DCPs they protect) will become useless."), std_to_wx(Config::config_read_file().string()).data()
963                                 )
964                         );
965
966
967                 dcp::LocalTime from (Config::instance()->signer_chain()->leaf().not_before());
968                 from.add_days (1);
969                 dcp::LocalTime to (Config::instance()->signer_chain()->leaf().not_after());
970                 to.add_days (-1);
971
972                 auto signer = Config::instance()->signer_chain();
973                 if (!signer->valid()) {
974                         error_dialog(this, _("The certificate chain for signing is invalid"));
975                         return;
976                 }
977
978                 optional<dcp::EncryptedKDM> kdm;
979                 try {
980                         auto const decrypted_kdm = _film->make_kdm(dialog.cpl(), from, to);
981                         auto const kdm = decrypted_kdm.encrypt(signer, Config::instance()->decryption_chain()->leaf(), {}, dcp::Formulation::MODIFIED_TRANSITIONAL_1, true, 0);
982                         if (dialog.internal()) {
983                                 auto dkdms = Config::instance()->dkdms();
984                                 dkdms->add(make_shared<DKDM>(kdm));
985                                 Config::instance()->changed ();
986                         } else {
987                                 auto path = dialog.directory() / (_film->dcp_name(false) + "_DKDM.xml");
988                                 kdm.as_xml(path);
989                         }
990                 } catch (dcp::NotEncryptedError& e) {
991                         error_dialog (this, _("CPL's content is not encrypted."));
992                 } catch (exception& e) {
993                         error_dialog (this, e.what ());
994                 } catch (...) {
995                         error_dialog (this, _("An unknown exception occurred."));
996                 }
997         }
998
999
1000         void jobs_export_video_file ()
1001         {
1002                 ExportVideoFileDialog dialog(this, _film->isdcf_name(true));
1003                 if (dialog.ShowModal() != wxID_OK) {
1004                         return;
1005                 }
1006
1007                 if (dcp::filesystem::exists(dialog.path())) {
1008                         bool ok = confirm_dialog(
1009                                         this,
1010                                         wxString::Format(_("File %s already exists.  Do you want to overwrite it?"), std_to_wx(dialog.path().string()).data())
1011                                         );
1012
1013                         if (!ok) {
1014                                 return;
1015                         }
1016                 }
1017
1018                 auto job = make_shared<TranscodeJob>(_film, TranscodeJob::ChangedBehaviour::EXAMINE_THEN_STOP);
1019                 job->set_encoder (
1020                         make_shared<FFmpegEncoder> (
1021                                 _film, job, dialog.path(), dialog.format(), dialog.mixdown_to_stereo(), dialog.split_reels(), dialog.split_streams(), dialog.x264_crf())
1022                         );
1023                 JobManager::instance()->add (job);
1024         }
1025
1026
1027         void jobs_export_subtitles ()
1028         {
1029                 ExportSubtitlesDialog dialog(this, _film->reels().size(), _film->interop());
1030                 if (dialog.ShowModal() != wxID_OK) {
1031                         return;
1032                 }
1033                 auto job = make_shared<TranscodeJob>(_film, TranscodeJob::ChangedBehaviour::EXAMINE_THEN_STOP);
1034                 job->set_encoder(
1035                         make_shared<SubtitleEncoder>(_film, job, dialog.path(), _film->isdcf_name(true), dialog.split_reels(), dialog.include_font())
1036                         );
1037                 JobManager::instance()->add(job);
1038         }
1039
1040
1041         void jobs_send_dcp_to_tms ()
1042         {
1043                 _film->send_dcp_to_tms ();
1044         }
1045
1046         void jobs_show_dcp ()
1047         {
1048                 DCPOMATIC_ASSERT (_film->directory ());
1049                 if (show_in_file_manager(_film->directory().get(), _film->dir(_film->dcp_name(false)))) {
1050                         error_dialog (this, _("Could not show DCP."));
1051                 }
1052         }
1053
1054         void view_closed_captions ()
1055         {
1056                 _film_viewer.show_closed_captions ();
1057         }
1058
1059         void view_video_waveform ()
1060         {
1061                 if (!_video_waveform_dialog) {
1062                         _video_waveform_dialog.reset(this, _film, _film_viewer);
1063                 }
1064
1065                 _video_waveform_dialog->Show ();
1066         }
1067
1068         void tools_system_information ()
1069         {
1070                 if (!_system_information_dialog) {
1071                         _system_information_dialog = new SystemInformationDialog (this, _film_viewer);
1072                 }
1073
1074                 _system_information_dialog->Show ();
1075         }
1076
1077         void tools_hints ()
1078         {
1079                 if (!_hints_dialog) {
1080                         _hints_dialog = new HintsDialog (this, _film, true);
1081                 }
1082
1083                 _hints_dialog->Show ();
1084         }
1085
1086         void tools_encoding_servers ()
1087         {
1088                 if (!_servers_list_dialog) {
1089                         _servers_list_dialog = new ServersListDialog (this);
1090                 }
1091
1092                 _servers_list_dialog->Show ();
1093         }
1094
1095         void tools_manage_templates ()
1096         {
1097                 if (!_templates_dialog) {
1098                         _templates_dialog.reset(this);
1099                 }
1100
1101                 _templates_dialog->Show ();
1102         }
1103
1104         void tools_check_for_updates ()
1105         {
1106                 _update_news_requested = true;
1107                 UpdateChecker::instance()->run();
1108         }
1109
1110         void tools_send_translations ()
1111         {
1112                 SendI18NDialog dialog(this);
1113                 if (dialog.ShowModal() != wxID_OK) {
1114                         return;
1115                 }
1116
1117                 string body;
1118                 body += dialog.name() + "\n";
1119                 body += dialog.language() + "\n";
1120                 body += string(dcpomatic_version) + " " + string(dcpomatic_git_commit) + "\n";
1121                 body += "--\n";
1122                 auto translations = I18NHook::translations ();
1123                 for (auto i: translations) {
1124                         body += i.first + "\n" + i.second + "\n\n";
1125                 }
1126                 if (dialog.email().find("@") == string::npos) {
1127                         error_dialog (this, _("You must enter a valid email address when sending translations, "
1128                                               "otherwise the DCP-o-matic maintainers cannot credit you or contact you with questions."));
1129                 } else {
1130                         Email email(dialog.email(), { "carl@dcpomatic.com" }, "DCP-o-matic translations", body);
1131                         try {
1132                                 email.send("main.carlh.net", 2525, EmailProtocol::STARTTLS);
1133                         } catch (NetworkError& e) {
1134                                 error_dialog (this, _("Could not send translations"), std_to_wx(e.what()));
1135                         }
1136                 }
1137         }
1138
1139         void help_about ()
1140         {
1141                 AboutDialog dialog(this);
1142                 dialog.ShowModal();
1143         }
1144
1145         void help_report_a_problem ()
1146         {
1147                 ReportProblemDialog dialog(this, _film);
1148                 if (dialog.ShowModal() == wxID_OK) {
1149                         dialog.report();
1150                 }
1151         }
1152
1153         bool should_close ()
1154         {
1155                 if (!JobManager::instance()->work_to_do ()) {
1156                         return true;
1157                 }
1158
1159                 wxMessageDialog dialog(
1160                         nullptr,
1161                         _("There are unfinished jobs; are you sure you want to quit?"),
1162                         _("Unfinished jobs"),
1163                         wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION
1164                         );
1165
1166                 return dialog.ShowModal() == wxID_YES;
1167         }
1168
1169         void close (wxCloseEvent& ev)
1170         {
1171                 if (!should_close ()) {
1172                         ev.Veto ();
1173                         return;
1174                 }
1175
1176                 if (_film && _film->dirty ()) {
1177                         FilmChangedClosingDialog dialog(_film->name());
1178                         switch (dialog.run()) {
1179                         case wxID_NO:
1180                                 /* Don't save and carry on to close */
1181                                 break;
1182                         case wxID_YES:
1183                                 /* Save and carry on to close */
1184                                 _film->write_metadata ();
1185                                 break;
1186                         case wxID_CANCEL:
1187                                 /* Veto the event and stop */
1188                                 ev.Veto ();
1189                                 return;
1190                         }
1191                 }
1192
1193                 /* We don't want to hear about any more configuration changes, since they
1194                    cause the File menu to be altered, which itself will be deleted around
1195                    now (without, as far as I can see, any way for us to find out).
1196                 */
1197                 _config_changed_connection.disconnect ();
1198
1199                 /* Also stop hearing about analytics-related stuff */
1200                 _analytics_message_connection.disconnect ();
1201
1202                 FontConfig::drop();
1203
1204                 ev.Skip ();
1205         }
1206
1207         void active_jobs_changed()
1208         {
1209                 /* ActiveJobsChanged can be called while JobManager holds a lock on its mutex, making
1210                  * the call to JobManager::get() in set_menu_sensitivity() deadlock unless we work around
1211                  * it by using an idle callback.  This feels quite unpleasant.
1212                  */
1213                 signal_manager->when_idle(boost::bind(&DOMFrame::set_menu_sensitivity, this));
1214         }
1215
1216         void set_menu_sensitivity ()
1217         {
1218                 auto jobs = JobManager::instance()->get ();
1219                 auto i = jobs.begin();
1220                 while (i != jobs.end() && (*i)->json_name() != "transcode") {
1221                         ++i;
1222                 }
1223                 bool const dcp_creation = (i != jobs.end ()) && !(*i)->finished ();
1224                 bool const have_cpl = _film && !_film->cpls().empty ();
1225                 bool const have_single_selected_content = _film_editor->content_panel()->selected().size() == 1;
1226                 bool const have_selected_content = !_film_editor->content_panel()->selected().empty();
1227                 bool const have_selected_video_content = !_film_editor->content_panel()->selected_video().empty();
1228
1229                 for (auto j: menu_items) {
1230
1231                         bool enabled = true;
1232
1233                         if ((j.second & NEEDS_FILM) && !_film) {
1234                                 enabled = false;
1235                         }
1236
1237                         if ((j.second & NOT_DURING_DCP_CREATION) && dcp_creation) {
1238                                 enabled = false;
1239                         }
1240
1241                         if ((j.second & NEEDS_CPL) && !have_cpl) {
1242                                 enabled = false;
1243                         }
1244
1245                         if ((j.second & NEEDS_SELECTED_CONTENT) && !have_selected_content) {
1246                                 enabled = false;
1247                         }
1248
1249                         if ((j.second & NEEDS_SINGLE_SELECTED_CONTENT) && !have_single_selected_content) {
1250                                 enabled = false;
1251                         }
1252
1253                         if ((j.second & NEEDS_SELECTED_VIDEO_CONTENT) && !have_selected_video_content) {
1254                                 enabled = false;
1255                         }
1256
1257                         if ((j.second & NEEDS_CLIPBOARD) && !_clipboard) {
1258                                 enabled = false;
1259                         }
1260
1261                         if ((j.second & NEEDS_ENCRYPTION) && (!_film || !_film->encrypted())) {
1262                                 enabled = false;
1263                         }
1264
1265                         j.first->Enable (enabled);
1266                 }
1267         }
1268
1269         /** @return true if the operation that called this method
1270          *  should continue, false to abort it.
1271          */
1272         template <class T>
1273         bool maybe_save_film ()
1274         {
1275                 if (!_film) {
1276                         return true;
1277                 }
1278
1279                 while (_film->dirty()) {
1280                         T dialog(_film->name());
1281                         switch (dialog.run()) {
1282                         case wxID_NO:
1283                                 return true;
1284                         case wxID_YES:
1285                                 try {
1286                                         _film->write_metadata();
1287                                         return true;
1288                                 } catch (exception& e) {
1289                                         error_dialog(this, _("Could not save project."), std_to_wx(e.what()));
1290                                         /* Go round again for another try */
1291                                 }
1292                                 break;
1293                         case wxID_CANCEL:
1294                                 return false;
1295                         }
1296                 }
1297
1298                 return true;
1299         }
1300
1301         template <class T>
1302         bool maybe_save_then_delete_film ()
1303         {
1304                 bool const r = maybe_save_film<T> ();
1305                 if (r) {
1306                         _film.reset ();
1307                 }
1308                 return r;
1309         }
1310
1311         void add_item (wxMenu* menu, wxString text, int id, int sens)
1312         {
1313                 auto item = menu->Append (id, text);
1314                 menu_items.insert (make_pair (item, sens));
1315         }
1316
1317         void setup_menu (wxMenuBar* m)
1318         {
1319                 _file_menu = new wxMenu;
1320                 /* [Shortcut] Ctrl+N:New film */
1321                 add_item (_file_menu, _("New...\tCtrl-N"), ID_file_new, ALWAYS);
1322                 /* [Shortcut] Ctrl+O:Open existing film */
1323                 add_item (_file_menu, _("&Open...\tCtrl-O"), ID_file_open, ALWAYS);
1324                 _file_menu->AppendSeparator ();
1325                 /* [Shortcut] Ctrl+S:Save current film */
1326                 add_item (_file_menu, _("&Save\tCtrl-S"), ID_file_save, NEEDS_FILM);
1327                 _file_menu->AppendSeparator ();
1328                 add_item (_file_menu, _("Save as &template..."), ID_file_save_as_template, NEEDS_FILM);
1329                 add_item (_file_menu, _("Duplicate..."), ID_file_duplicate, NEEDS_FILM);
1330                 add_item (_file_menu, _("Duplicate and open..."), ID_file_duplicate_and_open, NEEDS_FILM);
1331
1332                 _history_position = _file_menu->GetMenuItems().GetCount();
1333
1334                 _file_menu->AppendSeparator ();
1335                 /* [Shortcut] Ctrl+W:Close current film */
1336                 add_item (_file_menu, _("&Close\tCtrl-W"), ID_file_close, NEEDS_FILM);
1337
1338 #ifndef __WXOSX__
1339                 _file_menu->AppendSeparator ();
1340 #endif
1341
1342 #ifdef __WXOSX__
1343                 add_item (_file_menu, _("&Exit"), wxID_EXIT, ALWAYS);
1344 #else
1345                 add_item (_file_menu, _("&Quit"), wxID_EXIT, ALWAYS);
1346 #endif
1347
1348                 auto edit = new wxMenu;
1349                 /* [Shortcut] Ctrl+C:Copy settings from currently selected content */
1350                 add_item (edit, _("Copy settings\tCtrl-C"), ID_edit_copy, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_SINGLE_SELECTED_CONTENT);
1351                 /* [Shortcut] Ctrl+V:Paste settings into currently selected content */
1352                 add_item (edit, _("Paste settings...\tCtrl-V"), ID_edit_paste, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_SELECTED_CONTENT | NEEDS_CLIPBOARD);
1353                 edit->AppendSeparator ();
1354                 /* [Shortcut] Shift+Ctrl+A:Select all content */
1355                 add_item (edit, _("Select all\tShift-Ctrl-A"), ID_edit_select_all, NEEDS_FILM);
1356
1357 #ifdef __WXOSX__
1358                 add_item(_file_menu, _("&Preferences...\tCtrl-,"), wxID_PREFERENCES, ALWAYS);
1359 #else
1360                 edit->AppendSeparator ();
1361                 /* [Shortcut] Ctrl+P:Open preferences window */
1362                 add_item (edit, _("&Preferences...\tCtrl-P"), wxID_PREFERENCES, ALWAYS);
1363 #endif
1364
1365                 auto jobs_menu = new wxMenu;
1366                 /* [Shortcut] Ctrl+M:Make DCP */
1367                 add_item (jobs_menu, _("&Make DCP\tCtrl-M"), ID_jobs_make_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION);
1368                 /* [Shortcut] Ctrl+B:Make DCP in the batch converter*/
1369                 add_item (jobs_menu, _("Make DCP in &batch converter\tCtrl-B"), ID_jobs_make_dcp_batch, NEEDS_FILM | NOT_DURING_DCP_CREATION);
1370                 jobs_menu->AppendSeparator ();
1371                 /* [Shortcut] Ctrl+K:Make KDMs */
1372                 add_item (jobs_menu, _("Make &KDMs...\tCtrl-K"), ID_jobs_make_kdms, NEEDS_FILM);
1373                 /* [Shortcut] Ctrl+D:Make DKDMs */
1374                 add_item (jobs_menu, _("Make &DKDMs...\tCtrl-D"), ID_jobs_make_dkdms, NEEDS_FILM);
1375                 add_item (jobs_menu, _("Make DKDM for DCP-o-matic..."), ID_jobs_make_self_dkdm, NEEDS_FILM | NEEDS_ENCRYPTION);
1376                 jobs_menu->AppendSeparator ();
1377                 /* [Shortcut] Ctrl+E:Export video file */
1378                 add_item (jobs_menu, _("Export video file...\tCtrl-E"), ID_jobs_export_video_file, NEEDS_FILM);
1379                 add_item (jobs_menu, _("Export subtitles..."), ID_jobs_export_subtitles, NEEDS_FILM);
1380                 jobs_menu->AppendSeparator ();
1381                 add_item (jobs_menu, _("&Send DCP to TMS"), ID_jobs_send_dcp_to_tms, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
1382
1383 #if defined(DCPOMATIC_OSX)
1384                 add_item (jobs_menu, _("S&how DCP in Finder"), ID_jobs_show_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
1385 #elif defined(DCPOMATIC_WINDOWS)
1386                 add_item (jobs_menu, _("S&how DCP in Explorer"), ID_jobs_show_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
1387 #else
1388                 add_item (jobs_menu, _("S&how DCP in Files"), ID_jobs_show_dcp, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
1389 #endif
1390
1391                 add_item (jobs_menu, _("Open DCP in &player"), ID_jobs_open_dcp_in_player, NEEDS_FILM | NOT_DURING_DCP_CREATION | NEEDS_CPL);
1392
1393                 auto view = new wxMenu;
1394                 add_item (view, _("Closed captions..."), ID_view_closed_captions, NEEDS_FILM);
1395                 add_item (view, _("Video waveform..."), ID_view_video_waveform, NEEDS_FILM);
1396
1397                 auto tools = new wxMenu;
1398                 add_item (tools, _("Hints..."), ID_tools_hints, NEEDS_FILM);
1399                 add_item (tools, _("Encoding servers..."), ID_tools_encoding_servers, 0);
1400                 add_item (tools, _("Manage templates..."), ID_tools_manage_templates, 0);
1401                 add_item (tools, _("Check for updates"), ID_tools_check_for_updates, 0);
1402                 add_item (tools, _("Send translations..."), ID_tools_send_translations, 0);
1403                 add_item (tools, _("System information..."), ID_tools_system_information, 0);
1404                 tools->AppendSeparator ();
1405                 add_item (tools, _("Restore default preferences"), ID_tools_restore_default_preferences, ALWAYS);
1406                 tools->AppendSeparator ();
1407                 add_item (tools, _("Export preferences..."), ID_tools_export_preferences, ALWAYS);
1408                 add_item (tools, _("Import preferences..."), ID_tools_import_preferences, ALWAYS);
1409
1410                 wxMenu* help = new wxMenu;
1411 #ifdef __WXOSX__
1412                 add_item (help, _("About DCP-o-matic"), wxID_ABOUT, ALWAYS);
1413 #else
1414                 add_item (help, _("About"), wxID_ABOUT, ALWAYS);
1415 #endif
1416                 add_item (help, _("Report a problem..."), ID_help_report_a_problem, NEEDS_FILM);
1417
1418                 m->Append (_file_menu, _("&File"));
1419                 m->Append (edit, _("&Edit"));
1420                 m->Append (jobs_menu, _("&Jobs"));
1421                 m->Append (view, _("&View"));
1422                 m->Append (tools, _("&Tools"));
1423                 m->Append (help, _("&Help"));
1424         }
1425
1426         void config_changed (Config::Property what)
1427         {
1428                 /* Instantly save any config changes when using the DCP-o-matic GUI */
1429                 switch (what) {
1430                 case Config::CINEMAS:
1431                         try {
1432                                 Config::instance()->write_cinemas();
1433                         } catch (exception& e) {
1434                                 error_dialog (
1435                                         this,
1436                                         wxString::Format (
1437                                                 _("Could not write to cinemas file at %s.  Your changes have not been saved."),
1438                                                 std_to_wx (Config::instance()->cinemas_file().string()).data()
1439                                                 )
1440                                         );
1441                         }
1442                         break;
1443                 case Config::DKDM_RECIPIENTS:
1444                         try {
1445                                 Config::instance()->write_dkdm_recipients();
1446                         } catch (exception& e) {
1447                                 error_dialog (
1448                                         this,
1449                                         wxString::Format (
1450                                                 _("Could not write to DKDM recipients file at %s.  Your changes have not been saved."),
1451                                                 std_to_wx(Config::instance()->dkdm_recipients_file().string()).data()
1452                                                 )
1453                                         );
1454                         }
1455                         break;
1456                 default:
1457                         try {
1458                                 Config::instance()->write_config();
1459                         } catch (exception& e) {
1460                                 error_dialog (
1461                                         this,
1462                                         wxString::Format (
1463                                                 _("Could not write to config file at %s.  Your changes have not been saved."),
1464                                                 std_to_wx (Config::instance()->cinemas_file().string()).data()
1465                                                 )
1466                                         );
1467                         }
1468                 }
1469
1470                 for (int i = 0; i < _history_items; ++i) {
1471                         delete _file_menu->Remove (ID_file_history + i);
1472                 }
1473
1474                 if (_history_separator) {
1475                         _file_menu->Remove (_history_separator);
1476                 }
1477                 delete _history_separator;
1478                 _history_separator = 0;
1479
1480                 int pos = _history_position;
1481
1482                 /* Clear out non-existent history items before we re-build the menu */
1483                 Config::instance()->clean_history ();
1484                 auto history = Config::instance()->history();
1485
1486                 if (!history.empty ()) {
1487                         _history_separator = _file_menu->InsertSeparator (pos++);
1488                 }
1489
1490                 for (size_t i = 0; i < history.size(); ++i) {
1491                         string s;
1492                         if (i < 9) {
1493                                 s = String::compose ("&%1 %2", i + 1, history[i].string());
1494                         } else {
1495                                 s = history[i].string();
1496                         }
1497                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s));
1498                 }
1499
1500                 _history_items = history.size ();
1501
1502                 dcpomatic_log->set_types (Config::instance()->log_types());
1503         }
1504
1505         void update_checker_state_changed ()
1506         {
1507                 auto uc = UpdateChecker::instance ();
1508
1509                 bool const announce =
1510                         _update_news_requested ||
1511                         (uc->stable() && Config::instance()->check_for_updates()) ||
1512                         (uc->test() && Config::instance()->check_for_updates() && Config::instance()->check_for_test_updates());
1513
1514                 _update_news_requested = false;
1515
1516                 if (!announce) {
1517                         return;
1518                 }
1519
1520                 if (uc->state() == UpdateChecker::State::YES) {
1521                         UpdateDialog dialog(this, uc->stable(), uc->test());
1522                         dialog.ShowModal();
1523                 } else if (uc->state() == UpdateChecker::State::FAILED) {
1524                         error_dialog (this, _("The DCP-o-matic download server could not be contacted."));
1525                 } else {
1526                         error_dialog (this, _("There are no new versions of DCP-o-matic available."));
1527                 }
1528
1529                 _update_news_requested = false;
1530         }
1531
1532         void start_stop_pressed ()
1533         {
1534                 if (_film_viewer.playing()) {
1535                         _film_viewer.stop();
1536                 } else {
1537                         _film_viewer.start();
1538                 }
1539         }
1540
1541         void timeline_pressed ()
1542         {
1543                 _film_editor->content_panel()->timeline_clicked ();
1544         }
1545
1546         void back_frame ()
1547         {
1548                 _film_viewer.seek_by(-_film_viewer.one_video_frame(), true);
1549         }
1550
1551         void forward_frame ()
1552         {
1553                 _film_viewer.seek_by(_film_viewer.one_video_frame(), true);
1554         }
1555
1556         void analytics_message (string title, string html)
1557         {
1558                 HTMLDialog dialog(this, std_to_wx(title), std_to_wx(html));
1559                 dialog.ShowModal();
1560         }
1561
1562         void set_title ()
1563         {
1564                 auto s = wx_to_std(_("DCP-o-matic"));
1565                 if (_film) {
1566                         if (_film->directory()) {
1567                                 s += " - " + _film->directory()->string();
1568                         }
1569                         if (_film->dirty()) {
1570                                 s += " *";
1571                         }
1572                 }
1573
1574                 SetTitle (std_to_wx(s));
1575         }
1576
1577         FilmEditor* _film_editor;
1578         LimitedFrameSplitter* _splitter;
1579         wxPanel* _right_panel;
1580         FilmViewer _film_viewer;
1581         StandardControls* _controls;
1582         wx_ptr<VideoWaveformDialog> _video_waveform_dialog;
1583         SystemInformationDialog* _system_information_dialog = nullptr;
1584         HintsDialog* _hints_dialog = nullptr;
1585         ServersListDialog* _servers_list_dialog = nullptr;
1586         wxPreferencesEditor* _config_dialog = nullptr;
1587         wx_ptr<KDMDialog> _kdm_dialog;
1588         wx_ptr<DKDMDialog> _dkdm_dialog;
1589         wx_ptr<TemplatesDialog> _templates_dialog;
1590         wxMenu* _file_menu = nullptr;
1591         shared_ptr<Film> _film;
1592         int _history_items = 0;
1593         int _history_position = 0;
1594         wxMenuItem* _history_separator = nullptr;
1595         boost::signals2::scoped_connection _config_changed_connection;
1596         boost::signals2::scoped_connection _analytics_message_connection;
1597         bool _update_news_requested = false;
1598         shared_ptr<Content> _clipboard;
1599         bool _first_shown_called = false;
1600 };
1601
1602
1603 static const wxCmdLineEntryDesc command_line_description[] = {
1604         { wxCMD_LINE_SWITCH, "n", "new", "create new film", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
1605         { wxCMD_LINE_OPTION, "c", "content", "add content file / directory", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1606         { wxCMD_LINE_OPTION, "d", "dcp", "add content DCP", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1607         { wxCMD_LINE_SWITCH, "v", "version", "show DCP-o-matic version", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
1608         { wxCMD_LINE_OPTION, "", "config", "directory containing config.xml and cinemas.xml", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1609         { wxCMD_LINE_PARAM, 0, 0, "film to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1610         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
1611 };
1612
1613
1614 /** @class App
1615  *  @brief The magic App class for wxWidgets.
1616  */
1617 class App : public wxApp
1618 {
1619 public:
1620         App ()
1621                 : wxApp ()
1622         {
1623                 dcpomatic_setup_path_encoding ();
1624 #ifdef DCPOMATIC_LINUX
1625                 XInitThreads ();
1626 #endif
1627         }
1628
1629 private:
1630
1631         bool OnInit () override
1632         {
1633                 try {
1634
1635 #if defined(DCPOMATIC_WINDOWS)
1636                 if (Config::instance()->win32_console()) {
1637                         AllocConsole();
1638
1639                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
1640                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
1641                         FILE* hf_out = _fdopen(hCrt, "w");
1642                         setvbuf(hf_out, NULL, _IONBF, 1);
1643                         *stdout = *hf_out;
1644
1645                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
1646                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
1647                         FILE* hf_in = _fdopen(hCrt, "r");
1648                         setvbuf(hf_in, NULL, _IONBF, 128);
1649                         *stdin = *hf_in;
1650
1651                         cout << "DCP-o-matic is starting." << "\n";
1652                 }
1653 #endif
1654                         wxInitAllImageHandlers ();
1655
1656                         Config::FailedToLoad.connect(boost::bind(&App::config_failed_to_load, this, _1));
1657                         Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
1658
1659                         _splash = maybe_show_splash ();
1660
1661                         SetAppName (_("DCP-o-matic"));
1662
1663                         if (!wxApp::OnInit()) {
1664                                 return false;
1665                         }
1666
1667 #ifdef DCPOMATIC_LINUX
1668                         unsetenv ("UBUNTU_MENUPROXY");
1669 #endif
1670
1671 #ifdef DCPOMATIC_OSX
1672                         dcpomatic_sleep_seconds (1);
1673                         make_foreground_application ();
1674 #endif
1675
1676                         /* Enable i18n; this will create a Config object
1677                            to look for a force-configured language.  This Config
1678                            object will be wrong, however, because dcpomatic_setup
1679                            hasn't yet been called and there aren't any filters etc.
1680                            set up yet.
1681                         */
1682                         dcpomatic_setup_i18n ();
1683
1684                         /* Set things up, including filters etc.
1685                            which will now be internationalised correctly.
1686                         */
1687                         dcpomatic_setup ();
1688
1689                         /* Force the configuration to be re-loaded correctly next
1690                            time it is needed.
1691                         */
1692                         Config::drop ();
1693
1694                         /* We only look out for bad configuration from here on, as before
1695                            dcpomatic_setup() we haven't got OpenSSL ready so there will be
1696                            incorrect certificate chain validity errors.
1697                         */
1698                         Config::Bad.connect (boost::bind(&App::config_bad, this, _1));
1699
1700                         _frame = new DOMFrame (_("DCP-o-matic"));
1701                         SetTopWindow (_frame);
1702                         _frame->Maximize ();
1703                         close_splash ();
1704
1705                         if (running_32_on_64 ()) {
1706                                 NagDialog::maybe_nag (
1707                                         _frame, Config::NAG_32_ON_64,
1708                                         _("You are running the 32-bit version of DCP-o-matic on a 64-bit version of Windows.  This will limit the memory available to DCP-o-matic and may cause errors.  You are strongly advised to install the 64-bit version of DCP-o-matic."),
1709                                         false);
1710                         }
1711
1712                         _frame->Show ();
1713
1714                         signal_manager = new wxSignalManager (this);
1715                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this, _1));
1716
1717                         if (!_film_to_load.empty() && dcp::filesystem::is_directory(_film_to_load)) {
1718                                 try {
1719                                         _frame->load_film (_film_to_load);
1720                                 } catch (exception& e) {
1721                                         error_dialog (nullptr, std_to_wx(String::compose(wx_to_std(_("Could not load film %1 (%2)")), _film_to_load)), std_to_wx(e.what()));
1722                                 }
1723                         }
1724
1725                         if (!_film_to_create.empty ()) {
1726                                 _frame->new_film (_film_to_create, optional<string>());
1727                                 if (!_content_to_add.empty()) {
1728                                         for (auto i: content_factory(_content_to_add)) {
1729                                                 _frame->film()->examine_and_add_content(i);
1730                                         }
1731                                 }
1732                                 if (!_dcp_to_add.empty ()) {
1733                                         _frame->film()->examine_and_add_content(make_shared<DCPContent>(_dcp_to_add));
1734                                 }
1735                         }
1736
1737                         Bind (wxEVT_TIMER, boost::bind (&App::check, this));
1738                         _timer.reset (new wxTimer (this));
1739                         _timer->Start (1000);
1740
1741                         if (Config::instance()->check_for_updates ()) {
1742                                 UpdateChecker::instance()->run ();
1743                         }
1744
1745                         auto release_notes = find_release_notes(gui_is_dark());
1746                         if (release_notes) {
1747                                 HTMLDialog notes(nullptr, _("Release notes"), std_to_wx(*release_notes), true);
1748                                 notes.Centre();
1749                                 notes.ShowModal();
1750                         }
1751                 }
1752                 catch (exception& e)
1753                 {
1754                         close_splash();
1755                         error_dialog (nullptr, wxString::Format ("DCP-o-matic could not start."), std_to_wx(e.what()));
1756                 }
1757
1758                 return true;
1759         }
1760
1761         void OnInitCmdLine (wxCmdLineParser& parser) override
1762         {
1763                 parser.SetDesc (command_line_description);
1764                 parser.SetSwitchChars (wxT ("-"));
1765         }
1766
1767         bool OnCmdLineParsed (wxCmdLineParser& parser) override
1768         {
1769                 if (parser.Found (wxT("version"))) {
1770                         cout << "dcpomatic version " << dcpomatic_version << " " << dcpomatic_git_commit << "\n";
1771                         exit (EXIT_SUCCESS);
1772                 }
1773
1774                 if (parser.GetParamCount() > 0) {
1775                         if (parser.Found (wxT ("new"))) {
1776                                 _film_to_create = wx_to_std (parser.GetParam (0));
1777                         } else {
1778                                 _film_to_load = wx_to_std (parser.GetParam (0));
1779                         }
1780                 }
1781
1782                 wxString content;
1783                 if (parser.Found (wxT ("content"), &content)) {
1784                         _content_to_add = wx_to_std (content);
1785                 }
1786
1787                 wxString dcp;
1788                 if (parser.Found (wxT ("dcp"), &dcp)) {
1789                         _dcp_to_add = wx_to_std (dcp);
1790                 }
1791
1792                 wxString config;
1793                 if (parser.Found (wxT("config"), &config)) {
1794                         State::override_path = wx_to_std (config);
1795                 }
1796
1797                 return true;
1798         }
1799
1800         void report_exception ()
1801         {
1802                 try {
1803                         throw;
1804                 } catch (FileError& e) {
1805                         error_dialog (
1806                                 nullptr,
1807                                 wxString::Format(
1808                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
1809                                         std_to_wx (e.what()),
1810                                         std_to_wx (e.file().string().c_str())
1811                                         )
1812                                 );
1813                 } catch (boost::filesystem::filesystem_error& e) {
1814                         error_dialog (
1815                                 nullptr,
1816                                 wxString::Format(
1817                                         _("An exception occurred: %s (%s) (%s)\n\n") + REPORT_PROBLEM,
1818                                         std_to_wx (e.what()),
1819                                         std_to_wx (e.path1().string()),
1820                                         std_to_wx (e.path2().string())
1821                                         )
1822                                 );
1823                 } catch (exception& e) {
1824                         error_dialog (
1825                                 nullptr,
1826                                 wxString::Format(
1827                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
1828                                         std_to_wx (e.what ())
1829                                         )
1830                                 );
1831                 } catch (...) {
1832                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
1833                 }
1834         }
1835
1836         /* An unhandled exception has occurred inside the main event loop */
1837         bool OnExceptionInMainLoop () override
1838         {
1839                 report_exception ();
1840                 /* This will terminate the program */
1841                 return false;
1842         }
1843
1844         void OnUnhandledException () override
1845         {
1846                 report_exception ();
1847         }
1848
1849         void idle (wxIdleEvent& ev)
1850         {
1851                 signal_manager->ui_idle ();
1852                 ev.Skip ();
1853         }
1854
1855         void check ()
1856         {
1857                 try {
1858                         EncodeServerFinder::instance()->rethrow ();
1859                 } catch (exception& e) {
1860                         error_dialog (0, std_to_wx (e.what ()));
1861                 }
1862         }
1863
1864         void close_splash ()
1865         {
1866                 if (_splash) {
1867                         _splash->Destroy();
1868                         _splash = nullptr;
1869                 }
1870         }
1871
1872         void config_failed_to_load (Config::LoadFailure what)
1873         {
1874                 report_config_load_failure(_frame, what);
1875         }
1876
1877         void config_warning (string m)
1878         {
1879                 message_dialog (_frame, std_to_wx(m));
1880         }
1881
1882         bool config_bad (Config::BadReason reason)
1883         {
1884                 /* Destroy the splash screen here, as otherwise bad things seem to happen (for reasons unknown)
1885                    when we open our recreate dialog, close it, *then* try to Destroy the splash (the Destroy fails).
1886                 */
1887                 close_splash();
1888
1889                 auto config = Config::instance();
1890                 switch (reason) {
1891                 case Config::BAD_SIGNER_UTF8_STRINGS:
1892                 {
1893                         if (config->nagged(Config::NAG_BAD_SIGNER_CHAIN_UTF8)) {
1894                                 return false;
1895                         }
1896                         RecreateChainDialog dialog(
1897                                 _frame, _("Recreate signing certificates"),
1898                                 _("The certificate chain that DCP-o-matic uses for signing DCPs and KDMs contains a small error\n"
1899                                   "which will prevent DCPs from being validated correctly on some systems.  Do you want to re-create\n"
1900                                   "the certificate chain for signing DCPs and KDMs?"),
1901                                 _("Do nothing"),
1902                                 Config::NAG_BAD_SIGNER_CHAIN_UTF8
1903                                 );
1904                         return dialog.ShowModal() == wxID_OK;
1905                 }
1906                 case Config::BAD_SIGNER_VALIDITY_TOO_LONG:
1907                 {
1908                         if (config->nagged(Config::NAG_BAD_SIGNER_CHAIN_VALIDITY)) {
1909                                 return false;
1910                         }
1911                         RecreateChainDialog dialog(
1912                                 _frame, _("Recreate signing certificates"),
1913                                 _("The certificate chain that DCP-o-matic uses for signing DCPs and KDMs has a validity period\n"
1914                                   "that is too long.  This will cause problems playing back DCPs on some systems.\n"
1915                                   "Do you want to re-create the certificate chain for signing DCPs and KDMs?"),
1916                                 _("Do nothing"),
1917                                 Config::NAG_BAD_SIGNER_CHAIN_VALIDITY
1918                                 );
1919                         return dialog.ShowModal() == wxID_OK;
1920                 }
1921                 case Config::BAD_SIGNER_INCONSISTENT:
1922                 {
1923                         RecreateChainDialog dialog(
1924                                 _frame, _("Recreate signing certificates"),
1925                                 _("The certificate chain that DCP-o-matic uses for signing DCPs and KDMs is inconsistent and\n"
1926                                   "cannot be used.  DCP-o-matic cannot start unless you re-create it.  Do you want to re-create\n"
1927                                   "the certificate chain for signing DCPs and KDMs?"),
1928                                 _("Close DCP-o-matic")
1929                                 );
1930                         if (dialog.ShowModal() != wxID_OK) {
1931                                 exit (EXIT_FAILURE);
1932                         }
1933                         return true;
1934                 }
1935                 case Config::BAD_DECRYPTION_INCONSISTENT:
1936                 {
1937                         RecreateChainDialog dialog(
1938                                 _frame, _("Recreate KDM decryption chain"),
1939                                 _("The certificate chain that DCP-o-matic uses for decrypting KDMs is inconsistent and\n"
1940                                   "cannot be used.  DCP-o-matic cannot start unless you re-create it.  Do you want to re-create\n"
1941                                   "the certificate chain for decrypting KDMs?  You may want to say \"No\" here and back up your\n"
1942                                   "configuration before continuing."),
1943                                 _("Close DCP-o-matic")
1944                                 );
1945                         if (dialog.ShowModal() != wxID_OK) {
1946                                 exit (EXIT_FAILURE);
1947                         }
1948                         return true;
1949                 }
1950                 case Config::BAD_SIGNER_DN_QUALIFIER:
1951                 {
1952                         RecreateChainDialog dialog(
1953                                 _frame, _("Recreate signing certificates"),
1954                                 _("The certificate chain that DCP-o-matic uses for signing DCPs and KDMs contains a small error\n"
1955                                   "which will prevent DCPs from being validated correctly on some systems.  This error was caused\n"
1956                                   "by a bug in DCP-o-matic which has now been fixed. Do you want to re-create the certificate chain\n"
1957                                   "for signing DCPs and KDMs?"),
1958                                 _("Do nothing"),
1959                                 Config::NAG_BAD_SIGNER_DN_QUALIFIER
1960                                 );
1961                         return dialog.ShowModal() == wxID_OK;
1962                 }
1963                 default:
1964                         DCPOMATIC_ASSERT (false);
1965                 }
1966         }
1967
1968         DOMFrame* _frame = nullptr;
1969         wxSplashScreen* _splash = nullptr;
1970         shared_ptr<wxTimer> _timer;
1971         string _film_to_load;
1972         string _film_to_create;
1973         string _content_to_add;
1974         string _dcp_to_add;
1975 };
1976
1977
1978 IMPLEMENT_APP (App)