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