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