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