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