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