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