04b37b2c6bb1005b5c3fb03c1a1e3947c7dca71f
[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_with_metadata.h"
50 #include "lib/scope_guard.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::exception;
78 using std::list;
79 using std::make_shared;
80 using std::map;
81 using std::pair;
82 using std::shared_ptr;
83 using std::string;
84 using std::unordered_set;
85 using std::vector;
86 using boost::bind;
87 using boost::optional;
88 using boost::ref;
89 using std::dynamic_pointer_cast;
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_SIZER_Y_GAP * 2);
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_SIZER_Y_GAP * 2);
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                 auto d = new AboutDialog (this);
270                 d->ShowModal ();
271                 d->Destroy ();
272         }
273
274         void help_report_a_problem ()
275         {
276                 auto d = new ReportProblemDialog (this, shared_ptr<Film>());
277                 if (d->ShowModal () == wxID_OK) {
278                         d->report ();
279                 }
280                 d->Destroy ();
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                 return confirm_dialog (
318                         this,
319                         wxString::Format (_("File %s already exists.  Do you want to overwrite it?"), std_to_wx(path.string()).data())
320                         );
321         }
322
323         /** @id if not nullptr this is filled in with the wxTreeItemId of the selection */
324         shared_ptr<DKDMBase> selected_dkdm (wxTreeItemId* id = nullptr) const
325         {
326                 wxArrayTreeItemIds selections;
327                 _dkdm->GetSelections (selections);
328                 if (selections.GetCount() != 1) {
329                         if (id) {
330                                 *id = 0;
331                         }
332                         return {};
333                 }
334
335                 if (id) {
336                         *id = selections[0];
337                 }
338
339                 auto i = _dkdm_id.find (selections[0]);
340                 if (i == _dkdm_id.end()) {
341                         return {};
342                 }
343
344                 return i->second;
345         }
346
347         void create_kdms ()
348         {
349                 try {
350                         auto dkdm_base = selected_dkdm ();
351                         if (!dkdm_base) {
352                                 return;
353                         }
354
355                         list<KDMWithMetadataPtr> kdms;
356                         string title;
357
358                         auto dkdm = std::dynamic_pointer_cast<DKDM>(dkdm_base);
359                         if (dkdm) {
360
361                                 /* Decrypt the DKDM */
362                                 dcp::DecryptedKDM decrypted (dkdm->dkdm(), Config::instance()->decryption_chain()->key().get());
363                                 title = decrypted.content_title_text ();
364
365                                 /* This is the signer for our new KDMs */
366                                 auto signer = Config::instance()->signer_chain ();
367                                 if (!signer->valid ()) {
368                                         throw InvalidSignerError ();
369                                 }
370
371                                 for (auto i: _screens->screens()) {
372
373                                         if (!i->recipient) {
374                                                 continue;
375                                         }
376
377                                         dcp::LocalTime begin(_timing->from(), dcp::UTCOffset(i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()));
378                                         dcp::LocalTime end(_timing->until(), dcp::UTCOffset(i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()));
379
380                                         /* Make an empty KDM */
381                                         dcp::DecryptedKDM kdm (
382                                                 begin,
383                                                 end,
384                                                 decrypted.annotation_text().get_value_or (""),
385                                                 title,
386                                                 dcp::LocalTime().as_string()
387                                                 );
388
389                                         /* Add keys from the DKDM */
390                                         for (auto const& j: decrypted.keys()) {
391                                                 kdm.add_key (j);
392                                         }
393
394                                         auto const encrypted = kdm.encrypt(
395                                                         signer, i->recipient.get(), i->trusted_device_thumbprints(), _output->formulation(),
396                                                         !_output->forensic_mark_video(), _output->forensic_mark_audio() ? boost::optional<int>() : 0
397                                                         );
398
399                                         dcp::NameFormat::Map name_values;
400                                         name_values['c'] = i->cinema->name;
401                                         name_values['s'] = i->name;
402                                         name_values['f'] = title;
403                                         name_values['b'] = begin.date() + " " + begin.time_of_day(true, false);
404                                         name_values['e'] = end.date() + " " + end.time_of_day(true, false);
405                                         name_values['i'] = encrypted.cpl_id ();
406
407                                         /* Encrypt */
408                                         kdms.push_back (make_shared<KDMWithMetadata>(name_values, i->cinema.get(), i->cinema->emails, encrypted));
409                                 }
410                         }
411
412                         if (kdms.empty()) {
413                                 return;
414                         }
415
416                         auto result = _output->make (
417                                 kdms, title, bind (&DOMFrame::confirm_overwrite, this, _1)
418                                 );
419
420                         if (result.first) {
421                                 JobManager::instance()->add (result.first);
422                                 if (_job_view) {
423                                         _job_view->Destroy ();
424                                         _job_view = 0;
425                                 }
426                                 _job_view = new JobViewDialog (this, _("Send KDM emails"), result.first);
427                                 _job_view->ShowModal ();
428                         }
429
430                         if (result.second > 0) {
431                                 /* XXX: proper plural form support in wxWidgets? */
432                                 wxString s = result.second == 1 ? _("%d KDM written to %s") : _("%d KDMs written to %s");
433                                 message_dialog (
434                                         this,
435                                         wxString::Format (s, result.second, std_to_wx(_output->directory().string()).data())
436                                         );
437                         }
438                 } catch (dcp::NotEncryptedError& e) {
439                         error_dialog (this, _("CPL's content is not encrypted."));
440                 } catch (exception& e) {
441                         error_dialog (this, std_to_wx(e.what()));
442                 } catch (...) {
443                         error_dialog (this, _("An unknown exception occurred."));
444                 }
445         }
446
447         void setup_sensitivity ()
448         {
449                 _screens->setup_sensitivity ();
450                 _output->setup_sensitivity ();
451                 wxArrayTreeItemIds sel;
452                 _dkdm->GetSelections (sel);
453                 auto group = dynamic_pointer_cast<DKDMGroup>(selected_dkdm());
454                 auto dkdm = dynamic_pointer_cast<DKDM>(selected_dkdm());
455                 _create->Enable (!_screens->screens().empty() && sel.GetCount() > 0 && dkdm);
456                 _remove_dkdm->Enable (sel.GetCount() > 0 && (!group || group->name() != "root"));
457                 _export_dkdm->Enable (sel.GetCount() > 0 && dkdm);
458         }
459
460         void dkdm_selection_changed()
461         {
462                 _selected_dkdm = selected_dkdm();
463                 setup_sensitivity();
464         }
465
466         void dkdm_expanded(wxTreeEvent& ev)
467         {
468                 if (_ignore_expand) {
469                         return;
470                 }
471
472                 auto iter = _dkdm_id.find(ev.GetItem());
473                 if (iter != _dkdm_id.end()) {
474                         _expanded_dkdm_groups.insert(iter->second);
475                 }
476         }
477
478         void dkdm_collapsed(wxTreeEvent& ev)
479         {
480                 auto iter = _dkdm_id.find(ev.GetItem());
481                 if (iter != _dkdm_id.end()) {
482                         _expanded_dkdm_groups.erase(iter->second);
483                 }
484         }
485
486         void dkdm_begin_drag (wxTreeEvent& ev)
487         {
488                 ev.Allow ();
489         }
490
491         void dkdm_end_drag (wxTreeEvent& ev)
492         {
493                 auto from = _dkdm_id.find (_dkdm->GetSelection ());
494                 auto to = _dkdm_id.find (ev.GetItem ());
495                 if (from == _dkdm_id.end() || to == _dkdm_id.end() || from->first == to->first) {
496                         return;
497                 }
498
499                 auto group = dynamic_pointer_cast<DKDMGroup> (to->second);
500                 if (!group) {
501                         group = to->second->parent();
502                 }
503
504                 DCPOMATIC_ASSERT (group);
505                 DCPOMATIC_ASSERT (from->second->parent ());
506
507                 from->second->parent()->remove (from->second);
508                 add_dkdm(from->second, group, dynamic_pointer_cast<DKDM>(to->second));
509
510                 update_dkdm_view();
511         }
512
513         void add_dkdm_clicked ()
514         {
515                 auto dialog = new FileDialog(this, _("Select DKDM file"), wxT("XML files|*.xml|All files|*.*"), wxFD_MULTIPLE, "AddDKDMPath");
516
517                 ScopeGuard sg = [dialog]() { dialog->Destroy(); };
518
519                 if (!dialog->show()) {
520                         return;
521                 }
522
523                 for (auto path: dialog->paths()) {
524                         add_dkdm(path);
525                 }
526         }
527
528         void add_dkdm(boost::filesystem::path path)
529         {
530                 auto chain = Config::instance()->decryption_chain();
531                 DCPOMATIC_ASSERT (chain->key());
532
533                 try {
534                         dcp::EncryptedKDM ekdm(dcp::file_to_string(path, MAX_KDM_SIZE));
535                         /* Decrypt the DKDM to make sure that we can */
536                         dcp::DecryptedKDM dkdm(ekdm, chain->key().get());
537
538                         auto new_dkdm = make_shared<DKDM>(ekdm);
539                         auto group = dynamic_pointer_cast<DKDMGroup> (selected_dkdm());
540                         if (!group) {
541                                 group = Config::instance()->dkdms ();
542                         }
543                         add_dkdm(new_dkdm, group);
544                 } catch (dcp::KDMFormatError& e) {
545                         error_dialog (
546                                 this,
547                                 _("Could not read file as a KDM.  Perhaps it is badly formatted, or not a KDM at all."),
548                                 std_to_wx(e.what())
549                                 );
550                         return;
551                 } catch (dcp::KDMDecryptionError &) {
552                         error_dialog (
553                                 this,
554                                 _("Could not decrypt the DKDM.  Perhaps it was not created with the correct certificate.")
555                                 );
556                 } catch (dcp::MiscError& e) {
557                         error_dialog (
558                                 this,
559                                 _("Could not read file as a KDM.  It is much too large.  Make sure you are loading a DKDM (XML) file."),
560                                 std_to_wx(e.what())
561                                 );
562                 }
563
564                 update_dkdm_view();
565         }
566
567         void add_dkdm_folder_clicked ()
568         {
569                 auto d = new NewDKDMFolderDialog (this);
570                 if (d->ShowModal() == wxID_OK) {
571                         auto new_dkdm = make_shared<DKDMGroup>(wx_to_std(d->get()));
572                         auto parent = dynamic_pointer_cast<DKDMGroup>(selected_dkdm());
573                         if (!parent) {
574                                 parent = Config::instance()->dkdms ();
575                         }
576                         add_dkdm(new_dkdm, parent);
577                         update_dkdm_view();
578                 }
579                 d->Destroy ();
580         }
581
582         void update_dkdm_view()
583         {
584                 _dkdm->DeleteAllItems();
585                 _dkdm_id.clear();
586                 add_dkdm_to_view(Config::instance()->dkdms());
587                 if (_selected_dkdm) {
588                         auto selection_in_id_map = std::find_if(_dkdm_id.begin(), _dkdm_id.end(), [this](pair<wxTreeItemId, shared_ptr<DKDMBase>> const& entry) {
589                                 return entry.second == _selected_dkdm;
590                         });
591                         if (selection_in_id_map != _dkdm_id.end()) {
592                                 _dkdm->SelectItem(selection_in_id_map->first);
593                         }
594                 }
595         }
596
597         /** @return true if this thing or any of its children match a search string */
598         bool matches(shared_ptr<DKDMBase> base, string const& search)
599         {
600                 if (search.empty()) {
601                         return true;
602                 }
603
604                 auto name = base->name();
605                 transform(name.begin(), name.end(), name.begin(), ::tolower);
606                 if (name.find(search) != string::npos) {
607                         return true;
608                 }
609
610                 auto group = dynamic_pointer_cast<DKDMGroup>(base);
611                 if (!group) {
612                         return false;
613                 }
614
615                 auto const children = group->children();
616                 return std::any_of(children.begin(), children.end(), [this, search](shared_ptr<DKDMBase> child) {
617                         return matches(child, search);
618                 });
619         }
620
621         /** Add DKDMs to the view that match the current search */
622         void add_dkdm_to_view(shared_ptr<DKDMBase> base)
623         {
624                 auto search = wx_to_std(_dkdm_search->GetValue());
625                 transform(search.begin(), search.end(), search.begin(), ::tolower);
626
627                 optional<wxTreeItemId> group_to_expand;
628
629                 if (!base->parent()) {
630                         /* This is the root group */
631                         _dkdm_id[_dkdm->AddRoot("root")] = base;
632                 } else {
633                         /* Add base to the view */
634                         wxTreeItemId added;
635                         auto parent_id = dkdm_to_id(base->parent());
636                         added = _dkdm->AppendItem(parent_id, std_to_wx(base->name()));
637                         /* Expand the group (later) if it matches the search or it was manually expanded */
638                         if (!search.empty() || _expanded_dkdm_groups.find(base) != _expanded_dkdm_groups.end()) {
639                                 group_to_expand = added;
640                         }
641                         _dkdm_id[added] = base;
642                 }
643
644                 /* Add children */
645                 auto group = dynamic_pointer_cast<DKDMGroup>(base);
646                 if (group) {
647                         auto children = group->children();
648                         children.sort(
649                                 [this](shared_ptr<DKDMBase> a, shared_ptr<DKDMBase> b) { return _collator.compare(a->name(), b->name()) < 0; }
650                         );
651
652                         for (auto i: children) {
653                                 if (matches(i, search)) {
654                                         add_dkdm_to_view(i);
655                                 }
656                         }
657                 }
658
659                 if (group_to_expand) {
660                         _ignore_expand = true;
661                         _dkdm->Expand(*group_to_expand);
662                         _ignore_expand = false;
663                 }
664         }
665
666         /** @param group Group to add dkdm to */
667         void add_dkdm(shared_ptr<DKDMBase> dkdm, shared_ptr<DKDMGroup> group, shared_ptr<DKDM> previous = shared_ptr<DKDM>())
668         {
669                 group->add (dkdm, previous);
670                 /* We're messing with a Config-owned object here, so tell it that something has changed.
671                    This isn't nice.
672                 */
673                 Config::instance()->changed ();
674         }
675
676         wxTreeItemId dkdm_to_id (shared_ptr<DKDMBase> dkdm)
677         {
678                 for (auto const& i: _dkdm_id) {
679                         if (i.second == dkdm) {
680                                 return i.first;
681                         }
682                 }
683                 DCPOMATIC_ASSERT (false);
684         }
685
686         void remove_dkdm_clicked ()
687         {
688                 auto removed = selected_dkdm ();
689                 if (!removed) {
690                         return;
691                 }
692
693                 if (NagDialog::maybe_nag (
694                             this, Config::NAG_DELETE_DKDM,
695                             _("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.  "
696                               "Are you sure?"),
697                             true)) {
698                         return;
699                 }
700
701                 _dkdm->Delete (dkdm_to_id (removed));
702                 auto dkdms = Config::instance()->dkdms ();
703                 dkdms->remove (removed);
704                 Config::instance()->changed ();
705         }
706
707         void export_dkdm_clicked ()
708         {
709                 auto removed = selected_dkdm ();
710                 if (!removed) {
711                         return;
712                 }
713
714                 auto dkdm = dynamic_pointer_cast<DKDM>(removed);
715                 if (!dkdm) {
716                         return;
717                 }
718
719                 auto d = new wxFileDialog (
720                         this, _("Select DKDM File"), wxEmptyString, wxEmptyString, wxT("XML files (*.xml)|*.xml"),
721                         wxFD_SAVE | wxFD_OVERWRITE_PROMPT
722                         );
723
724                 if (d->ShowModal() == wxID_OK) {
725                         dkdm->dkdm().as_xml(wx_to_std(d->GetPath()));
726                 }
727                 d->Destroy ();
728         }
729
730         void dkdm_search_changed()
731         {
732                 update_dkdm_view();
733         }
734
735         wxPreferencesEditor* _config_dialog;
736         ScreensPanel* _screens;
737         KDMTimingPanel* _timing;
738         wxTreeCtrl* _dkdm;
739         wxSearchCtrl* _dkdm_search;
740         typedef std::map<wxTreeItemId, std::shared_ptr<DKDMBase>> DKDMMap;
741         DKDMMap _dkdm_id;
742         /* Keep a separate track of the selected DKDM so that when a search happens, and some things
743          * get removed from the view, we can restore the selection when they are re-added.
744          */
745         shared_ptr<DKDMBase> _selected_dkdm;
746         /* Keep expanded groups for the same reason */
747         unordered_set<shared_ptr<DKDMBase>> _expanded_dkdm_groups;
748         /* true if we are "artificially" expanding a group because it contains something found
749          * in a search.
750          */
751         bool _ignore_expand = false;
752         wxButton* _add_dkdm;
753         wxButton* _add_dkdm_folder;
754         wxButton* _remove_dkdm;
755         wxButton* _export_dkdm;
756         wxButton* _create;
757         KDMOutputPanel* _output;
758         JobViewDialog* _job_view;
759         Collator _collator;
760 };
761
762
763 /** @class App
764  *  @brief The magic App class for wxWidgets.
765  */
766 class App : public wxApp
767 {
768 public:
769         App ()
770                 : wxApp ()
771                 , _frame (nullptr)
772         {}
773
774 private:
775
776         bool OnInit () override
777         {
778                 wxSplashScreen* splash = nullptr;
779
780                 try {
781                         wxInitAllImageHandlers ();
782
783                         Config::FailedToLoad.connect(boost::bind(&App::config_failed_to_load, this, _1));
784                         Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
785
786                         splash = maybe_show_splash ();
787
788                         SetAppName (_("DCP-o-matic KDM Creator"));
789
790                         if (!wxApp::OnInit()) {
791                                 return false;
792                         }
793
794 #ifdef DCPOMATIC_LINUX
795                         unsetenv ("UBUNTU_MENUPROXY");
796 #endif
797
798 #ifdef DCPOMATIC_OSX
799                         make_foreground_application ();
800 #endif
801
802                         dcpomatic_setup_path_encoding ();
803
804                         /* Enable i18n; this will create a Config object
805                            to look for a force-configured language.  This Config
806                            object will be wrong, however, because dcpomatic_setup
807                            hasn't yet been called and there aren't any filters etc.
808                            set up yet.
809                         */
810                         dcpomatic_setup_i18n ();
811
812                         /* Set things up, including filters etc.
813                            which will now be internationalised correctly.
814                         */
815                         dcpomatic_setup ();
816
817                         /* Force the configuration to be re-loaded correctly next
818                            time it is needed.
819                         */
820                         Config::drop ();
821
822                         _frame = new DOMFrame (_("DCP-o-matic KDM Creator"));
823                         SetTopWindow (_frame);
824                         _frame->Maximize ();
825                         if (splash) {
826                                 splash->Destroy ();
827                                 splash = nullptr;
828                         }
829                         _frame->Show ();
830
831                         signal_manager = new wxSignalManager (this);
832                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
833                 }
834                 catch (exception& e)
835                 {
836                         if (splash) {
837                                 splash->Destroy ();
838                         }
839                         error_dialog (0, _("DCP-o-matic could not start"), std_to_wx(e.what()));
840                 }
841
842                 return true;
843         }
844
845         /* An unhandled exception has occurred inside the main event loop */
846         bool OnExceptionInMainLoop () override
847         {
848                 try {
849                         throw;
850                 } catch (FileError& e) {
851                         error_dialog (
852                                 0,
853                                 wxString::Format (
854                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
855                                         std_to_wx (e.what()),
856                                         std_to_wx (e.file().string().c_str ())
857                                         )
858                                 );
859                 } catch (exception& e) {
860                         error_dialog (
861                                 nullptr,
862                                 wxString::Format (
863                                         _("An exception occurred: %s.\n\n") + " " + REPORT_PROBLEM,
864                                         std_to_wx(e.what())
865                                         )
866                                 );
867                 } catch (...) {
868                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
869                 }
870
871                 /* This will terminate the program */
872                 return false;
873         }
874
875         void OnUnhandledException () override
876         {
877                 error_dialog (nullptr, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
878         }
879
880         void idle ()
881         {
882                 signal_manager->ui_idle ();
883         }
884
885         void config_failed_to_load(Config::LoadFailure what)
886         {
887                 report_config_load_failure(_frame, what);
888         }
889
890         void config_warning (string m)
891         {
892                 message_dialog (_frame, std_to_wx(m));
893         }
894
895         DOMFrame* _frame;
896 };
897
898 IMPLEMENT_APP (App)