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