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