Don't add DKDMs twice (#2545).
[dcpomatic.git] / src / tools / dcpomatic_kdm.cc
1 /*
2     Copyright (C) 2015-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 #include "wx/about_dialog.h"
23 #include "wx/dcpomatic_button.h"
24 #include "wx/editable_list.h"
25 #include "wx/file_dialog.h"
26 #include "wx/file_picker_ctrl.h"
27 #include "wx/full_config_dialog.h"
28 #include "wx/job_view_dialog.h"
29 #include "wx/kdm_output_panel.h"
30 #include "wx/kdm_timing_panel.h"
31 #include "wx/nag_dialog.h"
32 #include "wx/new_dkdm_folder_dialog.h"
33 #include "wx/report_problem_dialog.h"
34 #include "wx/screens_panel.h"
35 #include "wx/static_text.h"
36 #include "wx/wx_signal_manager.h"
37 #include "wx/wx_util.h"
38 #include "lib/cinema.h"
39 #include "lib/collator.h"
40 #include "lib/compose.hpp"
41 #include "lib/constants.h"
42 #include "lib/config.h"
43 #include "lib/cross.h"
44 #include "lib/dcpomatic_log.h"
45 #include "lib/dkdm_wrapper.h"
46 #include "lib/exceptions.h"
47 #include "lib/file_log.h"
48 #include "lib/job_manager.h"
49 #include "lib/kdm_util.h"
50 #include "lib/kdm_with_metadata.h"
51 #include "lib/screen.h"
52 #include "lib/send_kdm_email_job.h"
53 #include <dcp/encrypted_kdm.h>
54 #include <dcp/decrypted_kdm.h>
55 #include <dcp/exceptions.h>
56 #include <dcp/warnings.h>
57 LIBDCP_DISABLE_WARNINGS
58 #include <wx/dnd.h>
59 #include <wx/filepicker.h>
60 #include <wx/preferences.h>
61 #include <wx/splash.h>
62 #include <wx/srchctrl.h>
63 #include <wx/treectrl.h>
64 #include <wx/wx.h>
65 LIBDCP_ENABLE_WARNINGS
66 #ifdef __WXOSX__
67 #include <ApplicationServices/ApplicationServices.h>
68 #endif
69 #include <boost/bind/bind.hpp>
70 #include <unordered_set>
71
72 #ifdef check
73 #undef check
74 #endif
75
76
77 using std::dynamic_pointer_cast;
78 using std::exception;
79 using std::list;
80 using std::make_shared;
81 using std::map;
82 using std::pair;
83 using std::shared_ptr;
84 using std::string;
85 using std::unordered_set;
86 using std::vector;
87 using boost::bind;
88 using boost::optional;
89 using boost::ref;
90 #if BOOST_VERSION >= 106100
91 using namespace boost::placeholders;
92 #endif
93 using namespace dcpomatic;
94
95
96 enum {
97         ID_help_report_a_problem = 1,
98 };
99
100
101 class DOMFrame : public wxFrame
102 {
103 public:
104         explicit DOMFrame (wxString const & title)
105                 : wxFrame (nullptr, -1, title)
106                 , _config_dialog (nullptr)
107                 , _job_view (nullptr)
108         {
109 #if defined(DCPOMATIC_WINDOWS)
110                 if (Config::instance()->win32_console ()) {
111                         AllocConsole();
112
113                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
114                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
115                         FILE* hf_out = _fdopen(hCrt, "w");
116                         setvbuf(hf_out, NULL, _IONBF, 1);
117                         *stdout = *hf_out;
118
119                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
120                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
121                         FILE* hf_in = _fdopen(hCrt, "r");
122                         setvbuf(hf_in, NULL, _IONBF, 128);
123                         *stdin = *hf_in;
124
125                         std::cout << "DCP-o-matic KDM creator is starting." << "\n";
126                 }
127 #endif
128
129                 auto bar = new wxMenuBar;
130                 setup_menu (bar);
131                 SetMenuBar (bar);
132
133                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this),             wxID_EXIT);
134                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this),      wxID_PREFERENCES);
135                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this),            wxID_ABOUT);
136                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
137
138                 /* Use a panel as the only child of the Frame so that we avoid
139                    the dark-grey background on Windows.
140                 */
141                 auto overall_panel = new wxPanel (this, wxID_ANY);
142                 auto main_sizer = new wxBoxSizer (wxHORIZONTAL);
143
144                 auto horizontal = new wxBoxSizer (wxHORIZONTAL);
145                 auto left = new wxBoxSizer (wxVERTICAL);
146                 auto right = new wxBoxSizer (wxVERTICAL);
147
148                 horizontal->Add (left, 1, wxEXPAND | wxRIGHT, DCPOMATIC_SIZER_X_GAP * 2);
149                 horizontal->Add (right, 1, wxEXPAND);
150
151                 wxFont subheading_font (*wxNORMAL_FONT);
152                 subheading_font.SetWeight (wxFONTWEIGHT_BOLD);
153
154                 auto h = new StaticText (overall_panel, _("Screens"));
155                 h->SetFont (subheading_font);
156                 left->Add (h, 0, wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
157                 _screens = new ScreensPanel (overall_panel);
158                 left->Add (_screens, 1, wxEXPAND | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
159
160                 /// TRANSLATORS: translate the word "Timing" here; do not include the "KDM|" prefix
161                 h = new StaticText (overall_panel, S_("KDM|Timing"));
162                 h->SetFont (subheading_font);
163                 right->Add (h);
164                 _timing = new KDMTimingPanel (overall_panel);
165                 right->Add (_timing, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
166
167                 h = new StaticText (overall_panel, _("DKDM"));
168                 h->SetFont (subheading_font);
169                 right->Add(h, 0, wxTOP, DCPOMATIC_SUBHEADING_TOP_PAD);
170
171                 _dkdm_search = new wxSearchCtrl(overall_panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(200, search_ctrl_height()));
172 #ifndef __WXGTK3__
173                 /* The cancel button seems to be strangely broken in GTK3; clicking on it twice sometimes works */
174                 _dkdm_search->ShowCancelButton (true);
175 #endif
176
177                 right->Add(_dkdm_search, 0, wxTOP | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
178
179                 class DKDMDropTarget : public wxFileDropTarget
180                 {
181                 public:
182                         DKDMDropTarget(DOMFrame* frame)
183                                 : _frame(frame)
184                         {}
185
186                         bool OnDropFiles(wxCoord, wxCoord, wxArrayString const& filenames) override
187                         {
188                                 for (size_t i = 0; i < filenames.GetCount(); ++i) {
189                                         _frame->add_dkdm(boost::filesystem::path(wx_to_std(filenames[0])));
190                                 }
191
192                                 return true;
193                         }
194
195                 private:
196                         DOMFrame* _frame;
197                 };
198
199                 auto dkdm_sizer = new wxBoxSizer (wxHORIZONTAL);
200                 _dkdm = new wxTreeCtrl (
201                         overall_panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_HIDE_ROOT | wxTR_HAS_BUTTONS | wxTR_LINES_AT_ROOT
202                 );
203                 _dkdm->SetDropTarget(new DKDMDropTarget(this));
204                 dkdm_sizer->Add(_dkdm, 1, wxEXPAND | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
205                 auto dkdm_buttons = new wxBoxSizer(wxVERTICAL);
206                 _add_dkdm = new Button (overall_panel, _("Add..."));
207                 dkdm_buttons->Add (_add_dkdm, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
208                 _add_dkdm_folder = new Button (overall_panel, _("Add folder..."));
209                 dkdm_buttons->Add (_add_dkdm_folder, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
210                 _remove_dkdm = new Button (overall_panel, _("Remove"));
211                 dkdm_buttons->Add (_remove_dkdm, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
212                 _export_dkdm = new Button (overall_panel, _("Export..."));
213                 dkdm_buttons->Add (_export_dkdm, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
214                 dkdm_sizer->Add (dkdm_buttons, 0, wxEXPAND | wxALL, DCPOMATIC_SIZER_GAP);
215                 right->Add (dkdm_sizer, 1, wxEXPAND | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
216
217                 update_dkdm_view();
218
219                 h = new StaticText (overall_panel, _("Output"));
220                 h->SetFont (subheading_font);
221                 right->Add(h, 0, wxTOP, DCPOMATIC_SUBHEADING_TOP_PAD);
222                 _output = new KDMOutputPanel (overall_panel);
223                 right->Add (_output, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
224
225                 _create = new Button (overall_panel, _("Create KDMs"));
226                 right->Add (_create, 0, wxALL, DCPOMATIC_SIZER_GAP);
227
228                 main_sizer->Add (horizontal, 1, wxALL | wxEXPAND, DCPOMATIC_DIALOG_BORDER);
229                 overall_panel->SetSizer (main_sizer);
230
231                 /* Instantly save any config changes when using a DCP-o-matic GUI */
232                 Config::instance()->Changed.connect (boost::bind (&Config::write, Config::instance ()));
233
234                 _screens->ScreensChanged.connect (boost::bind (&DOMFrame::setup_sensitivity, this));
235                 _create->Bind (wxEVT_BUTTON, bind (&DOMFrame::create_kdms, this));
236                 _dkdm->Bind(wxEVT_TREE_SEL_CHANGED, boost::bind(&DOMFrame::dkdm_selection_changed, this));
237                 _dkdm->Bind (wxEVT_TREE_BEGIN_DRAG, boost::bind (&DOMFrame::dkdm_begin_drag, this, _1));
238                 _dkdm->Bind (wxEVT_TREE_END_DRAG, boost::bind (&DOMFrame::dkdm_end_drag, this, _1));
239                 _dkdm->Bind(wxEVT_TREE_ITEM_EXPANDED, boost::bind(&DOMFrame::dkdm_expanded, this, _1));
240                 _dkdm->Bind(wxEVT_TREE_ITEM_COLLAPSED, boost::bind(&DOMFrame::dkdm_collapsed, this, _1));
241                 _add_dkdm->Bind (wxEVT_BUTTON, bind (&DOMFrame::add_dkdm_clicked, this));
242                 _add_dkdm_folder->Bind (wxEVT_BUTTON, bind (&DOMFrame::add_dkdm_folder_clicked, this));
243                 _remove_dkdm->Bind (wxEVT_BUTTON, bind (&DOMFrame::remove_dkdm_clicked, this));
244                 _export_dkdm->Bind (wxEVT_BUTTON, bind (&DOMFrame::export_dkdm_clicked, this));
245                 _dkdm_search->Bind(wxEVT_TEXT, boost::bind(&DOMFrame::dkdm_search_changed, this));
246
247                 setup_sensitivity ();
248
249                 dcpomatic_log = make_shared<FileLog>(State::write_path("kdm.log"));
250         }
251
252 private:
253         void file_exit ()
254         {
255                 /* false here allows the close handler to veto the close request */
256                 Close (false);
257         }
258
259         void edit_preferences ()
260         {
261                 if (!_config_dialog) {
262                         _config_dialog = create_full_config_dialog ();
263                 }
264                 _config_dialog->Show (this);
265         }
266
267         void help_about ()
268         {
269                 AboutDialog dialog(this);
270                 dialog.ShowModal();
271         }
272
273         void help_report_a_problem ()
274         {
275                 ReportProblemDialog dialog(this, shared_ptr<Film>());
276                 if (dialog.ShowModal() == wxID_OK) {
277                         dialog.report();
278                 }
279         }
280
281         void setup_menu (wxMenuBar* m)
282         {
283                 auto file = new wxMenu;
284
285 #ifdef __WXOSX__
286                 file->Append (wxID_EXIT, _("&Exit"));
287 #else
288                 file->Append (wxID_EXIT, _("&Quit"));
289 #endif
290
291 #ifdef __WXOSX__
292                 file->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
293 #else
294                 wxMenu* edit = new wxMenu;
295                 edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
296 #endif
297
298                 wxMenu* help = new wxMenu;
299 #ifdef __WXOSX__
300                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
301 #else
302                 help->Append (wxID_ABOUT, _("About"));
303 #endif
304                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
305
306                 m->Append (file, _("&File"));
307 #ifndef __WXOSX__
308                 m->Append (edit, _("&Edit"));
309 #endif
310                 m->Append (help, _("&Help"));
311         }
312
313         bool confirm_overwrite (boost::filesystem::path path)
314         {
315                 if (boost::filesystem::is_directory(path)) {
316                         return confirm_dialog (
317                                 this,
318                                 wxString::Format(_("Folder %s already exists.  Do you want to overwrite it?"), std_to_wx(path.string()).data())
319                                 );
320                 } else {
321                         return confirm_dialog (
322                                 this,
323                                 wxString::Format(_("File %s already exists.  Do you want to overwrite it?"), std_to_wx(path.string()).data())
324                                 );
325                 }
326         }
327
328         /** @id if not nullptr this is filled in with the wxTreeItemId of the selection */
329         shared_ptr<DKDMBase> selected_dkdm (wxTreeItemId* id = nullptr) const
330         {
331                 wxArrayTreeItemIds selections;
332                 _dkdm->GetSelections (selections);
333                 if (selections.GetCount() != 1) {
334                         if (id) {
335                                 *id = 0;
336                         }
337                         return {};
338                 }
339
340                 if (id) {
341                         *id = selections[0];
342                 }
343
344                 auto i = _dkdm_id.find (selections[0]);
345                 if (i == _dkdm_id.end()) {
346                         return {};
347                 }
348
349                 return i->second;
350         }
351
352         void create_kdms ()
353         {
354                 try {
355                         auto dkdm_base = selected_dkdm ();
356                         if (!dkdm_base) {
357                                 return;
358                         }
359
360                         list<KDMWithMetadataPtr> kdms;
361                         string title;
362
363                         auto dkdm = std::dynamic_pointer_cast<DKDM>(dkdm_base);
364                         if (!dkdm) {
365                                 return;
366                         }
367
368                         /* Decrypt the DKDM */
369                         dcp::DecryptedKDM decrypted (dkdm->dkdm(), Config::instance()->decryption_chain()->key().get());
370                         title = decrypted.content_title_text ();
371
372                         /* This is the signer for our new KDMs */
373                         auto signer = Config::instance()->signer_chain ();
374                         if (!signer->valid ()) {
375                                 throw InvalidSignerError ();
376                         }
377
378                         vector<KDMCertificatePeriod> period_checks;
379
380                         std::function<dcp::DecryptedKDM (dcp::LocalTime, dcp::LocalTime)> make_kdm = [decrypted, title](dcp::LocalTime begin, dcp::LocalTime end) {
381                                 /* Make an empty KDM */
382                                 dcp::DecryptedKDM kdm (
383                                         begin,
384                                         end,
385                                         decrypted.annotation_text().get_value_or(""),
386                                         title,
387                                         dcp::LocalTime().as_string()
388                                         );
389
390                                 /* Add keys from the DKDM */
391                                 for (auto const& j: decrypted.keys()) {
392                                         kdm.add_key(j);
393                                 }
394
395                                 return kdm;
396                         };
397
398                         for (auto i: _screens->screens()) {
399
400                                 auto kdm = kdm_for_screen(
401                                         make_kdm,
402                                         i,
403                                         _timing->from(),
404                                         _timing->until(),
405                                         _output->formulation(),
406                                         !_output->forensic_mark_video(),
407                                         _output->forensic_mark_audio() ? boost::optional<int>() : 0,
408                                         period_checks
409                                         );
410
411                                 if (kdm) {
412                                         kdms.push_back(kdm);
413                                 }
414                         }
415
416                         if (kdms.empty()) {
417                                 return;
418                         }
419
420                         if (find(period_checks.begin(), period_checks.end(), KDMCertificatePeriod::KDM_OUTSIDE_CERTIFICATE) != period_checks.end()) {
421                                 error_dialog(
422                                         this,
423                                         _("Some KDMs would have validity periods which are completely outside the recipient certificate periods.  Such KDMs are very unlikely to work, so will not be created.")
424                                         );
425                                 return;
426                         }
427
428                         if (find(period_checks.begin(), period_checks.end(), KDMCertificatePeriod::KDM_OVERLAPS_CERTIFICATE) != period_checks.end()) {
429                                 message_dialog(
430                                         this,
431                                         _("For some of these KDMs the recipient certificate's validity period will not cover the whole of the KDM validity period.  This might cause problems with the KDMs.")
432                                         );
433                         }
434
435                         auto result = _output->make (
436                                 kdms, title, bind (&DOMFrame::confirm_overwrite, this, _1)
437                                 );
438
439                         if (result.first) {
440                                 JobManager::instance()->add (result.first);
441                                 if (_job_view) {
442                                         _job_view->Destroy ();
443                                         _job_view = 0;
444                                 }
445                                 _job_view = new JobViewDialog (this, _("Send KDM emails"), result.first);
446                                 _job_view->ShowModal ();
447                         }
448
449                         if (result.second > 0) {
450                                 /* XXX: proper plural form support in wxWidgets? */
451                                 wxString s = result.second == 1 ? _("%d KDM written to %s") : _("%d KDMs written to %s");
452                                 message_dialog (
453                                         this,
454                                         wxString::Format (s, result.second, std_to_wx(_output->directory().string()).data())
455                                         );
456                         }
457                 } catch (dcp::BadKDMDateError& e) {
458                         if (e.starts_too_early()) {
459                                 error_dialog(this, _("The KDM start period is before (or close to) the start of the signing certificate's validity period.  Use a later start time for this KDM."));
460                         } else {
461                                 error_dialog(this, _("The KDM end period is after (or close to) the end of the signing certificates' validity period.  Either use an earlier end time for this KDM or re-create your signing certificates in the DCP-o-matic preferences window."));
462                         }
463                         return;
464                 } catch (dcp::NotEncryptedError& e) {
465                         error_dialog (this, _("CPL's content is not encrypted."));
466                 } catch (exception& e) {
467                         error_dialog (this, std_to_wx(e.what()));
468                 } catch (...) {
469                         error_dialog (this, _("An unknown exception occurred."));
470                 }
471         }
472
473         void setup_sensitivity ()
474         {
475                 _screens->setup_sensitivity ();
476                 _output->setup_sensitivity ();
477                 wxArrayTreeItemIds sel;
478                 _dkdm->GetSelections (sel);
479                 auto group = dynamic_pointer_cast<DKDMGroup>(selected_dkdm());
480                 auto dkdm = dynamic_pointer_cast<DKDM>(selected_dkdm());
481                 _create->Enable (!_screens->screens().empty() && sel.GetCount() > 0 && dkdm);
482                 _remove_dkdm->Enable (sel.GetCount() > 0 && (!group || group->name() != "root"));
483                 _export_dkdm->Enable (sel.GetCount() > 0 && dkdm);
484         }
485
486         void dkdm_selection_changed()
487         {
488                 _selected_dkdm = selected_dkdm();
489                 setup_sensitivity();
490         }
491
492         void dkdm_expanded(wxTreeEvent& ev)
493         {
494                 if (_ignore_expand) {
495                         return;
496                 }
497
498                 auto iter = _dkdm_id.find(ev.GetItem());
499                 if (iter != _dkdm_id.end()) {
500                         _expanded_dkdm_groups.insert(iter->second);
501                 }
502         }
503
504         void dkdm_collapsed(wxTreeEvent& ev)
505         {
506                 auto iter = _dkdm_id.find(ev.GetItem());
507                 if (iter != _dkdm_id.end()) {
508                         _expanded_dkdm_groups.erase(iter->second);
509                 }
510         }
511
512         void dkdm_begin_drag (wxTreeEvent& ev)
513         {
514                 ev.Allow ();
515         }
516
517         void dkdm_end_drag (wxTreeEvent& ev)
518         {
519                 auto from = _dkdm_id.find (_dkdm->GetSelection ());
520                 auto to = _dkdm_id.find (ev.GetItem ());
521                 if (from == _dkdm_id.end() || to == _dkdm_id.end() || from->first == to->first) {
522                         return;
523                 }
524
525                 auto group = dynamic_pointer_cast<DKDMGroup> (to->second);
526                 if (!group) {
527                         group = to->second->parent();
528                 }
529
530                 /* Check we're not adding a group to one of its children */
531                 auto to_parent = group;
532                 while (to_parent) {
533                         if (from->second == to_parent) {
534                                 return;
535                         }
536                         to_parent = to_parent->parent();
537                 }
538
539                 DCPOMATIC_ASSERT (group);
540                 DCPOMATIC_ASSERT (from->second->parent ());
541
542                 from->second->parent()->remove (from->second);
543                 add_dkdm(from->second, group, dynamic_pointer_cast<DKDM>(to->second));
544
545                 update_dkdm_view();
546         }
547
548         void add_dkdm_clicked ()
549         {
550                 FileDialog dialog(this, _("Select DKDM file"), wxT("XML files|*.xml|All files|*.*"), wxFD_MULTIPLE, "AddDKDMPath");
551                 if (!dialog.show()) {
552                         return;
553                 }
554
555                 for (auto path: dialog.paths()) {
556                         add_dkdm(path);
557                 }
558         }
559
560         void add_dkdm(boost::filesystem::path path)
561         {
562                 auto chain = Config::instance()->decryption_chain();
563                 DCPOMATIC_ASSERT (chain->key());
564
565                 try {
566                         dcp::EncryptedKDM ekdm(dcp::file_to_string(path, MAX_KDM_SIZE));
567                         /* Decrypt the DKDM to make sure that we can */
568                         dcp::DecryptedKDM dkdm(ekdm, chain->key().get());
569
570                         auto new_dkdm = make_shared<DKDM>(ekdm);
571
572                         if (Config::instance()->dkdms()->contains(new_dkdm->dkdm().id())) {
573                                 error_dialog(
574                                         this,
575                                         wxString::Format(_("DKDM %s is already in the DKDM list and will not be added again."), std_to_wx(new_dkdm->dkdm().id()))
576                                         );
577                                 return;
578                         }
579
580                         auto group = dynamic_pointer_cast<DKDMGroup> (selected_dkdm());
581                         if (!group) {
582                                 group = Config::instance()->dkdms ();
583                         }
584                         add_dkdm(new_dkdm, group);
585                 } catch (dcp::KDMFormatError& e) {
586                         error_dialog (
587                                 this,
588                                 _("Could not read file as a KDM.  Perhaps it is badly formatted, or not a KDM at all."),
589                                 std_to_wx(e.what())
590                                 );
591                         return;
592                 } catch (dcp::KDMDecryptionError &) {
593                         error_dialog (
594                                 this,
595                                 _("Could not decrypt the DKDM.  Perhaps it was not created with the correct certificate.")
596                                 );
597                 } catch (dcp::MiscError& e) {
598                         error_dialog (
599                                 this,
600                                 _("Could not read file as a KDM.  It is much too large.  Make sure you are loading a DKDM (XML) file."),
601                                 std_to_wx(e.what())
602                                 );
603                 }
604
605                 update_dkdm_view();
606         }
607
608         void add_dkdm_folder_clicked ()
609         {
610                 NewDKDMFolderDialog dialog(this);
611                 if (dialog.ShowModal() != wxID_OK) {
612                         return;
613                 }
614
615                 auto new_dkdm = make_shared<DKDMGroup>(wx_to_std(dialog.get()));
616                 auto parent = dynamic_pointer_cast<DKDMGroup>(selected_dkdm());
617                 if (!parent) {
618                         parent = Config::instance()->dkdms ();
619                 }
620                 add_dkdm(new_dkdm, parent);
621                 update_dkdm_view();
622         }
623
624         void update_dkdm_view()
625         {
626                 _dkdm->DeleteAllItems();
627                 _dkdm_id.clear();
628                 add_dkdm_to_view(Config::instance()->dkdms());
629                 if (_selected_dkdm) {
630                         auto selection_in_id_map = std::find_if(_dkdm_id.begin(), _dkdm_id.end(), [this](pair<wxTreeItemId, shared_ptr<DKDMBase>> const& entry) {
631                                 return entry.second == _selected_dkdm;
632                         });
633                         if (selection_in_id_map != _dkdm_id.end()) {
634                                 _dkdm->SelectItem(selection_in_id_map->first);
635                         }
636                 }
637         }
638
639         /** @return true if this thing or any of its children match a search string */
640         bool matches(shared_ptr<DKDMBase> base, string const& search)
641         {
642                 if (search.empty()) {
643                         return true;
644                 }
645
646                 auto name = base->name();
647                 transform(name.begin(), name.end(), name.begin(), ::tolower);
648                 if (name.find(search) != string::npos) {
649                         return true;
650                 }
651
652                 auto group = dynamic_pointer_cast<DKDMGroup>(base);
653                 if (!group) {
654                         return false;
655                 }
656
657                 auto const children = group->children();
658                 return std::any_of(children.begin(), children.end(), [this, search](shared_ptr<DKDMBase> child) {
659                         return matches(child, search);
660                 });
661         }
662
663         /** Add DKDMs to the view that match the current search */
664         void add_dkdm_to_view(shared_ptr<DKDMBase> base)
665         {
666                 auto search = wx_to_std(_dkdm_search->GetValue());
667                 transform(search.begin(), search.end(), search.begin(), ::tolower);
668
669                 optional<wxTreeItemId> group_to_expand;
670
671                 if (!base->parent()) {
672                         /* This is the root group */
673                         _dkdm_id[_dkdm->AddRoot("root")] = base;
674                 } else {
675                         /* Add base to the view */
676                         wxTreeItemId added;
677                         auto parent_id = dkdm_to_id(base->parent());
678                         added = _dkdm->AppendItem(parent_id, std_to_wx(base->name()));
679                         /* Expand the group (later) if it matches the search or it was manually expanded */
680                         if (!search.empty() || _expanded_dkdm_groups.find(base) != _expanded_dkdm_groups.end()) {
681                                 group_to_expand = added;
682                         }
683                         _dkdm_id[added] = base;
684                 }
685
686                 /* Add children */
687                 auto group = dynamic_pointer_cast<DKDMGroup>(base);
688                 if (group) {
689                         auto children = group->children();
690                         children.sort(
691                                 [this](shared_ptr<DKDMBase> a, shared_ptr<DKDMBase> b) { return _collator.compare(a->name(), b->name()) < 0; }
692                         );
693
694                         for (auto i: children) {
695                                 if (matches(i, search)) {
696                                         add_dkdm_to_view(i);
697                                 }
698                         }
699                 }
700
701                 if (group_to_expand) {
702                         _ignore_expand = true;
703                         _dkdm->Expand(*group_to_expand);
704                         _ignore_expand = false;
705                 }
706         }
707
708         /** @param group Group to add dkdm to */
709         void add_dkdm(shared_ptr<DKDMBase> dkdm, shared_ptr<DKDMGroup> group, shared_ptr<DKDM> previous = shared_ptr<DKDM>())
710         {
711                 group->add (dkdm, previous);
712                 /* We're messing with a Config-owned object here, so tell it that something has changed.
713                    This isn't nice.
714                 */
715                 Config::instance()->changed ();
716         }
717
718         wxTreeItemId dkdm_to_id (shared_ptr<DKDMBase> dkdm)
719         {
720                 for (auto const& i: _dkdm_id) {
721                         if (i.second == dkdm) {
722                                 return i.first;
723                         }
724                 }
725                 DCPOMATIC_ASSERT (false);
726         }
727
728         void remove_dkdm_clicked ()
729         {
730                 auto removed = selected_dkdm ();
731                 if (!removed) {
732                         return;
733                 }
734
735                 if (NagDialog::maybe_nag (
736                             this, Config::NAG_DELETE_DKDM,
737                             _("You are about to remove a DKDM.  This will make it impossible to decrypt the DCP that the DKDM was made for, and it cannot be undone.  "
738                               "Are you sure?"),
739                             true)) {
740                         return;
741                 }
742
743                 _dkdm->Delete (dkdm_to_id (removed));
744                 auto dkdms = Config::instance()->dkdms ();
745                 dkdms->remove (removed);
746                 Config::instance()->changed ();
747         }
748
749         void export_dkdm_clicked ()
750         {
751                 auto removed = selected_dkdm ();
752                 if (!removed) {
753                         return;
754                 }
755
756                 auto dkdm = dynamic_pointer_cast<DKDM>(removed);
757                 if (!dkdm) {
758                         return;
759                 }
760
761                 wxFileDialog dialog(
762                         this, _("Select DKDM File"), wxEmptyString, wxEmptyString, wxT("XML files (*.xml)|*.xml"),
763                         wxFD_SAVE | wxFD_OVERWRITE_PROMPT
764                         );
765
766                 if (dialog.ShowModal() == wxID_OK) {
767                         dkdm->dkdm().as_xml(wx_to_std(dialog.GetPath()));
768                 }
769         }
770
771         void dkdm_search_changed()
772         {
773                 update_dkdm_view();
774         }
775
776         wxPreferencesEditor* _config_dialog;
777         ScreensPanel* _screens;
778         KDMTimingPanel* _timing;
779         wxTreeCtrl* _dkdm;
780         wxSearchCtrl* _dkdm_search;
781         typedef std::map<wxTreeItemId, std::shared_ptr<DKDMBase>> DKDMMap;
782         DKDMMap _dkdm_id;
783         /* Keep a separate track of the selected DKDM so that when a search happens, and some things
784          * get removed from the view, we can restore the selection when they are re-added.
785          */
786         shared_ptr<DKDMBase> _selected_dkdm;
787         /* Keep expanded groups for the same reason */
788         unordered_set<shared_ptr<DKDMBase>> _expanded_dkdm_groups;
789         /* true if we are "artificially" expanding a group because it contains something found
790          * in a search.
791          */
792         bool _ignore_expand = false;
793         wxButton* _add_dkdm;
794         wxButton* _add_dkdm_folder;
795         wxButton* _remove_dkdm;
796         wxButton* _export_dkdm;
797         wxButton* _create;
798         KDMOutputPanel* _output;
799         JobViewDialog* _job_view;
800         Collator _collator;
801 };
802
803
804 /** @class App
805  *  @brief The magic App class for wxWidgets.
806  */
807 class App : public wxApp
808 {
809 public:
810         App ()
811                 : wxApp ()
812                 , _frame (nullptr)
813         {}
814
815 private:
816
817         bool OnInit () override
818         {
819                 wxSplashScreen* splash;
820
821                 try {
822                         wxInitAllImageHandlers ();
823
824                         Config::FailedToLoad.connect(boost::bind(&App::config_failed_to_load, this, _1));
825                         Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
826
827                         splash = maybe_show_splash ();
828
829                         SetAppName (_("DCP-o-matic KDM Creator"));
830
831                         if (!wxApp::OnInit()) {
832                                 return false;
833                         }
834
835 #ifdef DCPOMATIC_LINUX
836                         unsetenv ("UBUNTU_MENUPROXY");
837 #endif
838
839 #ifdef DCPOMATIC_OSX
840                         make_foreground_application ();
841 #endif
842
843                         dcpomatic_setup_path_encoding ();
844
845                         /* Enable i18n; this will create a Config object
846                            to look for a force-configured language.  This Config
847                            object will be wrong, however, because dcpomatic_setup
848                            hasn't yet been called and there aren't any filters etc.
849                            set up yet.
850                         */
851                         dcpomatic_setup_i18n ();
852
853                         /* Set things up, including filters etc.
854                            which will now be internationalised correctly.
855                         */
856                         dcpomatic_setup ();
857
858                         /* Force the configuration to be re-loaded correctly next
859                            time it is needed.
860                         */
861                         Config::drop ();
862
863                         _frame = new DOMFrame (_("DCP-o-matic KDM Creator"));
864                         SetTopWindow (_frame);
865                         _frame->Maximize ();
866                         if (splash) {
867                                 splash->Destroy ();
868                                 splash = nullptr;
869                         }
870                         _frame->Show ();
871
872                         signal_manager = new wxSignalManager (this);
873                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
874                 }
875                 catch (exception& e)
876                 {
877                         if (splash) {
878                                 splash->Destroy ();
879                         }
880                         error_dialog (0, _("DCP-o-matic could not start"), std_to_wx(e.what()));
881                 }
882
883                 return true;
884         }
885
886         /* An unhandled exception has occurred inside the main event loop */
887         bool OnExceptionInMainLoop () override
888         {
889                 try {
890                         throw;
891                 } catch (FileError& e) {
892                         error_dialog (
893                                 0,
894                                 wxString::Format (
895                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
896                                         std_to_wx (e.what()),
897                                         std_to_wx (e.file().string().c_str ())
898                                         )
899                                 );
900                 } catch (exception& e) {
901                         error_dialog (
902                                 nullptr,
903                                 wxString::Format (
904                                         _("An exception occurred: %s.\n\n") + " " + REPORT_PROBLEM,
905                                         std_to_wx(e.what())
906                                         )
907                                 );
908                 } catch (...) {
909                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
910                 }
911
912                 /* This will terminate the program */
913                 return false;
914         }
915
916         void OnUnhandledException () override
917         {
918                 error_dialog (nullptr, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
919         }
920
921         void idle ()
922         {
923                 signal_manager->ui_idle ();
924         }
925
926         void config_failed_to_load(Config::LoadFailure what)
927         {
928                 report_config_load_failure(_frame, what);
929         }
930
931         void config_warning (string m)
932         {
933                 message_dialog (_frame, std_to_wx(m));
934         }
935
936         DOMFrame* _frame;
937 };
938
939 IMPLEMENT_APP (App)