84573797e996b1b043a8569a389edee626962707
[dcpomatic.git] / src / tools / dcpomatic_kdm.cc
1 /*
2     Copyright (C) 2015-2019 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 #include "wx/full_config_dialog.h"
22 #include "wx/about_dialog.h"
23 #include "wx/report_problem_dialog.h"
24 #include "wx/file_picker_ctrl.h"
25 #include "wx/wx_util.h"
26 #include "wx/wx_signal_manager.h"
27 #include "wx/screens_panel.h"
28 #include "wx/kdm_timing_panel.h"
29 #include "wx/kdm_output_panel.h"
30 #include "wx/job_view_dialog.h"
31 #include "wx/file_dialog_wrapper.h"
32 #include "wx/new_dkdm_folder_dialog.h"
33 #include "wx/editable_list.h"
34 #include "wx/static_text.h"
35 #include "wx/dcpomatic_button.h"
36 #include "wx/nag_dialog.h"
37 #include "lib/config.h"
38 #include "lib/util.h"
39 #include "lib/screen.h"
40 #include "lib/job_manager.h"
41 #include "lib/kdm_with_metadata.h"
42 #include "lib/exceptions.h"
43 #include "lib/send_kdm_email_job.h"
44 #include "lib/compose.hpp"
45 #include "lib/cinema.h"
46 #include "lib/dkdm_wrapper.h"
47 #include "lib/cross.h"
48 #ifdef DCPOMATIC_VARIANT_SWAROOP
49 #include "lib/decrypted_ecinema_kdm.h"
50 #endif
51 #include <dcp/encrypted_kdm.h>
52 #include <dcp/decrypted_kdm.h>
53 #include <dcp/exceptions.h>
54 #include <wx/wx.h>
55 #include <wx/preferences.h>
56 #include <wx/splash.h>
57 #include <wx/filepicker.h>
58 #ifdef __WXOSX__
59 #include <ApplicationServices/ApplicationServices.h>
60 #endif
61 #include <boost/bind.hpp>
62 #include <boost/foreach.hpp>
63
64 #ifdef check
65 #undef check
66 #endif
67
68 using std::exception;
69 using std::list;
70 using std::string;
71 using std::vector;
72 using std::pair;
73 using std::map;
74 using boost::shared_ptr;
75 using boost::bind;
76 using boost::optional;
77 using boost::ref;
78 using boost::dynamic_pointer_cast;
79 using namespace dcpomatic;
80
81 enum {
82         ID_help_report_a_problem = 1,
83 };
84
85 class DOMFrame : public wxFrame
86 {
87 public:
88         explicit DOMFrame (wxString const & title)
89                 : wxFrame (0, -1, title)
90                 , _config_dialog (0)
91                 , _job_view (0)
92         {
93 #if defined(DCPOMATIC_WINDOWS)
94                 if (Config::instance()->win32_console ()) {
95                         AllocConsole();
96
97                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
98                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
99                         FILE* hf_out = _fdopen(hCrt, "w");
100                         setvbuf(hf_out, NULL, _IONBF, 1);
101                         *stdout = *hf_out;
102
103                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
104                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
105                         FILE* hf_in = _fdopen(hCrt, "r");
106                         setvbuf(hf_in, NULL, _IONBF, 128);
107                         *stdin = *hf_in;
108
109                         std::cout << "DCP-o-matic KDM creator is starting." << "\n";
110                 }
111 #endif
112
113                 wxMenuBar* bar = new wxMenuBar;
114                 setup_menu (bar);
115                 SetMenuBar (bar);
116
117                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this),             wxID_EXIT);
118                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this),      wxID_PREFERENCES);
119                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this),            wxID_ABOUT);
120                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
121
122                 /* Use a panel as the only child of the Frame so that we avoid
123                    the dark-grey background on Windows.
124                 */
125                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
126                 wxBoxSizer* main_sizer = new wxBoxSizer (wxHORIZONTAL);
127
128                 wxBoxSizer* horizontal = new wxBoxSizer (wxHORIZONTAL);
129                 wxBoxSizer* left = new wxBoxSizer (wxVERTICAL);
130                 wxBoxSizer* right = new wxBoxSizer (wxVERTICAL);
131
132                 horizontal->Add (left, 1, wxEXPAND | wxRIGHT, DCPOMATIC_SIZER_X_GAP * 2);
133                 horizontal->Add (right, 1, wxEXPAND);
134
135                 wxFont subheading_font (*wxNORMAL_FONT);
136                 subheading_font.SetWeight (wxFONTWEIGHT_BOLD);
137
138                 wxStaticText* h = new StaticText (overall_panel, _("Screens"));
139                 h->SetFont (subheading_font);
140                 left->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
141                 _screens = new ScreensPanel (overall_panel);
142                 left->Add (_screens, 1, wxEXPAND | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
143
144                 /// TRANSLATORS: translate the word "Timing" here; do not include the "KDM|" prefix
145                 h = new StaticText (overall_panel, S_("KDM|Timing"));
146                 h->SetFont (subheading_font);
147                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_Y_GAP * 2);
148                 _timing = new KDMTimingPanel (overall_panel);
149                 right->Add (_timing, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
150
151                 h = new StaticText (overall_panel, _("DKDM"));
152                 h->SetFont (subheading_font);
153                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxTOP, DCPOMATIC_SIZER_Y_GAP * 2);
154                 wxBoxSizer* dkdm_sizer = new wxBoxSizer (wxHORIZONTAL);
155                 _dkdm = new wxTreeCtrl (
156                         overall_panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_HIDE_ROOT | wxTR_HAS_BUTTONS | wxTR_LINES_AT_ROOT
157                 );
158                 dkdm_sizer->Add (_dkdm, 1, wxEXPAND | wxALL, DCPOMATIC_SIZER_Y_GAP);
159                 wxBoxSizer* dkdm_buttons = new wxBoxSizer(wxVERTICAL);
160                 _add_dkdm = new Button (overall_panel, _("Add..."));
161                 dkdm_buttons->Add (_add_dkdm, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
162                 _add_dkdm_folder = new Button (overall_panel, _("Add folder..."));
163                 dkdm_buttons->Add (_add_dkdm_folder, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
164                 _remove_dkdm = new Button (overall_panel, _("Remove"));
165                 dkdm_buttons->Add (_remove_dkdm, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
166                 _export_dkdm = new Button (overall_panel, _("Export..."));
167                 dkdm_buttons->Add (_export_dkdm, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
168                 dkdm_sizer->Add (dkdm_buttons, 0, wxEXPAND | wxALL, DCPOMATIC_SIZER_GAP);
169                 right->Add (dkdm_sizer, 1, wxEXPAND | wxALL, DCPOMATIC_SIZER_Y_GAP);
170
171                 add_dkdm_view (Config::instance()->dkdms());
172
173                 h = new StaticText (overall_panel, _("Output"));
174                 h->SetFont (subheading_font);
175                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxTOP, DCPOMATIC_SIZER_Y_GAP * 2);
176                 /* XXX: hard-coded non-interop here */
177                 _output = new KDMOutputPanel (overall_panel, false);
178                 right->Add (_output, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
179
180                 _create = new Button (overall_panel, _("Create KDMs"));
181                 right->Add (_create, 0, wxALL, DCPOMATIC_SIZER_GAP);
182
183                 main_sizer->Add (horizontal, 1, wxALL | wxEXPAND, DCPOMATIC_DIALOG_BORDER);
184                 overall_panel->SetSizer (main_sizer);
185
186                 /* Instantly save any config changes when using a DCP-o-matic GUI */
187                 Config::instance()->Changed.connect (boost::bind (&Config::write, Config::instance ()));
188
189                 _screens->ScreensChanged.connect (boost::bind (&DOMFrame::setup_sensitivity, this));
190                 _create->Bind (wxEVT_BUTTON, bind (&DOMFrame::create_kdms, this));
191                 _dkdm->Bind (wxEVT_TREE_SEL_CHANGED, boost::bind (&DOMFrame::setup_sensitivity, this));
192                 _dkdm->Bind (wxEVT_TREE_BEGIN_DRAG, boost::bind (&DOMFrame::dkdm_begin_drag, this, _1));
193                 _dkdm->Bind (wxEVT_TREE_END_DRAG, boost::bind (&DOMFrame::dkdm_end_drag, this, _1));
194                 _add_dkdm->Bind (wxEVT_BUTTON, bind (&DOMFrame::add_dkdm_clicked, this));
195                 _add_dkdm_folder->Bind (wxEVT_BUTTON, bind (&DOMFrame::add_dkdm_folder_clicked, this));
196                 _remove_dkdm->Bind (wxEVT_BUTTON, bind (&DOMFrame::remove_dkdm_clicked, this));
197                 _export_dkdm->Bind (wxEVT_BUTTON, bind (&DOMFrame::export_dkdm_clicked, this));
198
199                 setup_sensitivity ();
200         }
201
202 private:
203         void file_exit ()
204         {
205                 /* false here allows the close handler to veto the close request */
206                 Close (false);
207         }
208
209         void edit_preferences ()
210         {
211                 if (!_config_dialog) {
212                         _config_dialog = create_full_config_dialog ();
213                 }
214                 _config_dialog->Show (this);
215         }
216
217         void help_about ()
218         {
219                 AboutDialog* d = new AboutDialog (this);
220                 d->ShowModal ();
221                 d->Destroy ();
222         }
223
224         void help_report_a_problem ()
225         {
226                 ReportProblemDialog* d = new ReportProblemDialog (this, shared_ptr<Film> ());
227                 if (d->ShowModal () == wxID_OK) {
228                         d->report ();
229                 }
230                 d->Destroy ();
231         }
232
233         void setup_menu (wxMenuBar* m)
234         {
235                 wxMenu* file = new wxMenu;
236
237 #ifdef __WXOSX__
238                 file->Append (wxID_EXIT, _("&Exit"));
239 #else
240                 file->Append (wxID_EXIT, _("&Quit"));
241 #endif
242
243 #ifdef __WXOSX__
244                 file->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
245 #else
246                 wxMenu* edit = new wxMenu;
247                 edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
248 #endif
249
250                 wxMenu* help = new wxMenu;
251 #ifdef __WXOSX__
252                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
253 #else
254                 help->Append (wxID_ABOUT, _("About"));
255 #endif
256                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
257
258                 m->Append (file, _("&File"));
259 #ifndef __WXOSX__
260                 m->Append (edit, _("&Edit"));
261 #endif
262                 m->Append (help, _("&Help"));
263         }
264
265         bool confirm_overwrite (boost::filesystem::path path)
266         {
267                 return confirm_dialog (
268                         this,
269                         wxString::Format (_("File %s already exists.  Do you want to overwrite it?"), std_to_wx(path.string()).data())
270                         );
271         }
272
273         /** @id if not 0 this is filled in with the wxTreeItemId of the selection */
274         shared_ptr<DKDMBase> selected_dkdm (wxTreeItemId* id = 0) const
275         {
276                 wxArrayTreeItemIds selections;
277                 _dkdm->GetSelections (selections);
278                 if (selections.GetCount() != 1) {
279                         if (id) {
280                                 *id = 0;
281                         }
282                         return shared_ptr<DKDMBase> ();
283                 }
284
285                 if (id) {
286                         *id = selections[0];
287                 }
288
289                 DKDMMap::const_iterator i = _dkdm_id.find (selections[0]);
290                 if (i == _dkdm_id.end()) {
291                         return shared_ptr<DKDMBase> ();
292                 }
293
294                 return i->second;
295         }
296
297         void create_kdms ()
298         {
299                 try {
300                         shared_ptr<DKDMBase> dkdm_base = selected_dkdm ();
301                         if (!dkdm_base) {
302                                 return;
303                         }
304
305                         list<KDMWithMetadataPtr> kdms;
306                         string title;
307
308 #ifdef DCPOMATIC_VARIANT_SWAROOP
309                         shared_ptr<ECinemaDKDM> ecinema_dkdm = boost::dynamic_pointer_cast<ECinemaDKDM> (dkdm_base);
310                         if (ecinema_dkdm) {
311                                 DecryptedECinemaKDM decrypted (ecinema_dkdm->dkdm(), Config::instance()->decryption_chain()->key().get());
312                                 title = decrypted.name ();
313
314                                 BOOST_FOREACH (shared_ptr<Screen> i, _screens->screens()) {
315
316                                         if (!i->recipient) {
317                                                 continue;
318                                         }
319
320                                         dcp::LocalTime begin(_timing->from(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
321                                         dcp::LocalTime end(_timing->until(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
322
323                                         DecryptedECinemaKDM kdm (
324                                                 decrypted.id(),
325                                                 decrypted.name(),
326                                                 decrypted.key(),
327                                                 begin,
328                                                 end
329                                                 );
330
331                                         dcp::NameFormat::Map name_values;
332                                         name_values['c'] = i->cinema->name;
333                                         name_values['s'] = i->name;
334                                         name_values['f'] = title;
335                                         name_values['b'] = begin.date() + " " + begin.time_of_day(true, false);
336                                         name_values['e'] = end.date() + " " + end.time_of_day(true, false);
337                                         name_values['i'] = kdm.id();
338
339                                         /* Encrypt */
340                                         kdms.push_back (
341                                                 KDMWithMetadataPtr(
342                                                         new ECinemaKDMWithMetadata(name_values, i->cinema, kdm.encrypt(i->recipient.get()))
343                                                         )
344                                                 );
345                                 }
346                         }
347 #endif
348
349                         shared_ptr<DKDM> dkdm = boost::dynamic_pointer_cast<DKDM> (dkdm_base);
350                         if (dkdm) {
351
352                                 /* Decrypt the DKDM */
353                                 dcp::DecryptedKDM decrypted (dkdm->dkdm(), Config::instance()->decryption_chain()->key().get());
354                                 title = decrypted.content_title_text ();
355
356                                 /* This is the signer for our new KDMs */
357                                 shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
358                                 if (!signer->valid ()) {
359                                         throw InvalidSignerError ();
360                                 }
361
362                                 BOOST_FOREACH (shared_ptr<Screen> i, _screens->screens()) {
363
364                                         if (!i->recipient) {
365                                                 continue;
366                                         }
367
368                                         dcp::LocalTime begin(_timing->from(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
369                                         dcp::LocalTime end(_timing->until(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
370
371                                         /* Make an empty KDM */
372                                         dcp::DecryptedKDM kdm (
373                                                 begin,
374                                                 end,
375                                                 decrypted.annotation_text().get_value_or (""),
376                                                 decrypted.content_title_text(),
377                                                 dcp::LocalTime().as_string()
378                                                 );
379
380                                         /* Add keys from the DKDM */
381                                         BOOST_FOREACH (dcp::DecryptedKDMKey const & j, decrypted.keys()) {
382                                                 kdm.add_key (j);
383                                         }
384
385                                         dcp::EncryptedKDM const encrypted = kdm.encrypt(
386                                                         signer, i->recipient.get(), i->trusted_device_thumbprints(), _output->formulation(),
387                                                         !_output->forensic_mark_video(), _output->forensic_mark_audio() ? boost::optional<int>() : 0
388                                                         );
389
390                                         dcp::NameFormat::Map name_values;
391                                         name_values['c'] = i->cinema->name;
392                                         name_values['s'] = i->name;
393                                         name_values['f'] = title;
394                                         name_values['b'] = begin.date() + " " + begin.time_of_day(true, false);
395                                         name_values['e'] = end.date() + " " + end.time_of_day(true, false);
396                                         name_values['i'] = encrypted.cpl_id ();
397
398                                         /* Encrypt */
399                                         kdms.push_back (
400                                                 KDMWithMetadataPtr(
401                                                         new DCPKDMWithMetadata(name_values, i->cinema.get(), i->cinema->emails, encrypted)
402                                                         )
403                                                 );
404                                 }
405                         }
406
407                         if (kdms.empty()) {
408                                 return;
409                         }
410
411                         pair<shared_ptr<Job>, int> result = _output->make (
412                                 kdms, title, bind (&DOMFrame::confirm_overwrite, this, _1)
413                                 );
414
415                         if (result.first) {
416                                 JobManager::instance()->add (result.first);
417                                 if (_job_view) {
418                                         _job_view->Destroy ();
419                                         _job_view = 0;
420                                 }
421                                 _job_view = new JobViewDialog (this, _("Send KDM emails"), result.first);
422                                 _job_view->ShowModal ();
423                         }
424
425                         if (result.second > 0) {
426                                 /* XXX: proper plural form support in wxWidgets? */
427                                 wxString s = result.second == 1 ? _("%d KDM written to %s") : _("%d KDMs written to %s");
428                                 message_dialog (
429                                         this,
430                                         wxString::Format (s, result.second, std_to_wx(_output->directory().string()).data())
431                                         );
432                         }
433                 } catch (dcp::NotEncryptedError& e) {
434                         error_dialog (this, _("CPL's content is not encrypted."));
435                 } catch (exception& e) {
436                         error_dialog (this, std_to_wx(e.what()));
437                 } catch (...) {
438                         error_dialog (this, _("An unknown exception occurred."));
439                 }
440         }
441
442         void setup_sensitivity ()
443         {
444                 _screens->setup_sensitivity ();
445                 _output->setup_sensitivity ();
446                 wxArrayTreeItemIds sel;
447                 _dkdm->GetSelections (sel);
448                 shared_ptr<DKDMGroup> group = dynamic_pointer_cast<DKDMGroup>(selected_dkdm());
449                 shared_ptr<DKDM> dkdm = dynamic_pointer_cast<DKDM>(selected_dkdm());
450                 _create->Enable (!_screens->screens().empty() && sel.GetCount() > 0);
451                 _remove_dkdm->Enable (sel.GetCount() > 0 && (!group || group->name() != "root"));
452                 _export_dkdm->Enable (sel.GetCount() > 0 && dkdm);
453         }
454
455         void dkdm_begin_drag (wxTreeEvent& ev)
456         {
457                 ev.Allow ();
458         }
459
460         void dkdm_end_drag (wxTreeEvent& ev)
461         {
462                 DKDMMap::iterator from = _dkdm_id.find (_dkdm->GetSelection ());
463                 DKDMMap::iterator to = _dkdm_id.find (ev.GetItem ());
464                 if (from == _dkdm_id.end() || to == _dkdm_id.end() || from->first == to->first) {
465                         return;
466                 }
467
468                 shared_ptr<DKDMGroup> group = dynamic_pointer_cast<DKDMGroup> (to->second);
469                 if (!group) {
470                         group = to->second->parent();
471                 }
472
473                 DCPOMATIC_ASSERT (group);
474                 DCPOMATIC_ASSERT (from->second->parent ());
475
476                 from->second->parent()->remove (from->second);
477                 add_dkdm_model (from->second, group, dynamic_pointer_cast<DKDM>(to->second));
478
479                 _dkdm->Delete (from->first);
480                 _dkdm_id.erase (from->first);
481                 add_dkdm_view (from->second, dynamic_pointer_cast<DKDM>(to->second) ? to->first : optional<wxTreeItemId>());
482         }
483
484         void add_dkdm_clicked ()
485         {
486                 wxFileDialog* d = new wxFileDialog (this, _("Select DKDM file"));
487                 if (d->ShowModal() == wxID_OK) {
488                         shared_ptr<const dcp::CertificateChain> chain = Config::instance()->decryption_chain();
489                         DCPOMATIC_ASSERT (chain->key());
490
491 #ifdef DCPOMATIC_VARIANT_SWAROOP
492                         try {
493                                 cxml::Document test_doc;
494                                 string const xml_string = dcp::file_to_string (wx_to_std(d->GetPath()), MAX_KDM_SIZE);
495                                 test_doc.read_string (xml_string);
496                                 if (test_doc.root_name() == "ECinemaSecurityMessage") {
497                                         EncryptedECinemaKDM ekdm(xml_string);
498                                         /* Decrypt the DKDM to make sure that we can */
499                                         DecryptedECinemaKDM dkdm(ekdm, chain->key().get());
500
501                                         shared_ptr<DKDMBase> new_dkdm(new ECinemaDKDM(ekdm));
502                                         shared_ptr<DKDMGroup> group = dynamic_pointer_cast<DKDMGroup> (selected_dkdm());
503                                         if (!group) {
504                                                 group = Config::instance()->dkdms();
505                                         }
506                                         add_dkdm_model (new_dkdm, group);
507                                         add_dkdm_view (new_dkdm);
508                                         d->Destroy ();
509                                         return;
510                                 }
511                         } catch (KDMError& e) {
512                                 error_dialog (
513                                         this, "Could not read file as a KDM.  Perhaps it is badly formatted, created with the wrong certificate, or not a KDM at all.",
514                                         std_to_wx(e.what())
515                                         );
516                                 d->Destroy ();
517                                 return;
518                         } catch (dcp::MiscError& e) {
519                                 error_dialog (
520                                         this,
521                                         _("Could not read file as a KDM.  It is much too large.  Make sure you are loading a DKDM (XML) file."),
522                                         std_to_wx(e.what())
523                                         );
524                                 d->Destroy ();
525                                 return;
526                         }
527 #endif
528
529                         try {
530                                 dcp::EncryptedKDM ekdm(dcp::file_to_string (wx_to_std (d->GetPath ()), MAX_KDM_SIZE));
531                                 /* Decrypt the DKDM to make sure that we can */
532                                 dcp::DecryptedKDM dkdm(ekdm, chain->key().get());
533
534                                 shared_ptr<DKDMBase> new_dkdm(new DKDM(ekdm));
535                                 shared_ptr<DKDMGroup> group = dynamic_pointer_cast<DKDMGroup> (selected_dkdm ());
536                                 if (!group) {
537                                         group = Config::instance()->dkdms ();
538                                 }
539                                 add_dkdm_model (new_dkdm, group);
540                                 add_dkdm_view (new_dkdm);
541                         } catch (dcp::KDMFormatError& e) {
542                                 error_dialog (
543                                         this,
544                                         _("Could not read file as a KDM.  Perhaps it is badly formatted, or not a KDM at all."),
545                                         std_to_wx(e.what())
546                                         );
547                                 return;
548                         } catch (dcp::KDMDecryptionError &) {
549                                 error_dialog (
550                                         this,
551                                         _("Could not decrypt the DKDM.  Perhaps it was not created with the correct certificate.")
552                                         );
553                         } catch (dcp::MiscError& e) {
554                                 error_dialog (
555                                         this,
556                                         _("Could not read file as a KDM.  It is much too large.  Make sure you are loading a DKDM (XML) file."),
557                                         std_to_wx(e.what())
558                                         );
559                         }
560                 }
561                 d->Destroy ();
562         }
563
564         void add_dkdm_folder_clicked ()
565         {
566                 NewDKDMFolderDialog* d = new NewDKDMFolderDialog (this);
567                 if (d->ShowModal() == wxID_OK) {
568                         shared_ptr<DKDMBase> new_dkdm (new DKDMGroup (wx_to_std (d->get ())));
569                         shared_ptr<DKDMGroup> parent = dynamic_pointer_cast<DKDMGroup> (selected_dkdm ());
570                         if (!parent) {
571                                 parent = Config::instance()->dkdms ();
572                         }
573                         add_dkdm_model (new_dkdm, parent);
574                         add_dkdm_view (new_dkdm);
575                 }
576                 d->Destroy ();
577         }
578
579         /** @param dkdm Thing to add.
580          *  @param parent Parent group, or 0.
581          */
582         void add_dkdm_view (shared_ptr<DKDMBase> base, optional<wxTreeItemId> previous = optional<wxTreeItemId>())
583         {
584                 if (!base->parent()) {
585                         /* This is the root group */
586                         _dkdm_id[_dkdm->AddRoot("root")] = base;
587                 } else {
588                         /* Add base to the view */
589                         wxTreeItemId added;
590                         if (previous) {
591                                 added = _dkdm->InsertItem(dkdm_to_id(base->parent()), *previous, std_to_wx(base->name()));
592                         } else {
593                                 added = _dkdm->AppendItem(dkdm_to_id(base->parent()), std_to_wx(base->name()));
594                         }
595                         _dkdm_id[added] = base;
596                 }
597
598                 /* Add children */
599                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup> (base);
600                 if (g) {
601                         BOOST_FOREACH (shared_ptr<DKDMBase> i, g->children()) {
602                                 add_dkdm_view (i);
603                         }
604                 }
605         }
606
607         /** @param group Group to add dkdm to */
608         void add_dkdm_model (shared_ptr<DKDMBase> dkdm, shared_ptr<DKDMGroup> group, shared_ptr<DKDM> previous = shared_ptr<DKDM> ())
609         {
610                 group->add (dkdm, previous);
611                 /* We're messing with a Config-owned object here, so tell it that something has changed.
612                    This isn't nice.
613                 */
614                 Config::instance()->changed ();
615         }
616
617         wxTreeItemId dkdm_to_id (shared_ptr<DKDMBase> dkdm)
618         {
619                 for (DKDMMap::iterator i = _dkdm_id.begin(); i != _dkdm_id.end(); ++i) {
620                         if (i->second == dkdm) {
621                                 return i->first;
622                         }
623                 }
624                 DCPOMATIC_ASSERT (false);
625         }
626
627         void remove_dkdm_clicked ()
628         {
629                 shared_ptr<DKDMBase> removed = selected_dkdm ();
630                 if (!removed) {
631                         return;
632                 }
633
634                 if (NagDialog::maybe_nag (
635                             this, Config::NAG_DELETE_DKDM,
636                             _("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.  "
637                               "Are you sure?"),
638                             true)) {
639                         return;
640                 }
641
642                 _dkdm->Delete (dkdm_to_id (removed));
643                 shared_ptr<DKDMGroup> dkdms = Config::instance()->dkdms ();
644                 dkdms->remove (removed);
645                 Config::instance()->changed ();
646         }
647
648         void export_dkdm_clicked ()
649         {
650                 shared_ptr<DKDMBase> removed = selected_dkdm ();
651                 if (!removed) {
652                         return;
653                 }
654
655                 shared_ptr<DKDM> dkdm = dynamic_pointer_cast<DKDM>(removed);
656                 if (!dkdm) {
657                         return;
658                 }
659
660                 wxFileDialog* d = new wxFileDialog (
661                         this, _("Select DKDM File"), wxEmptyString, wxEmptyString, wxT("XML files (*.xml)|*.xml"),
662                         wxFD_SAVE | wxFD_OVERWRITE_PROMPT
663                         );
664
665                 if (d->ShowModal() == wxID_OK) {
666                         dkdm->dkdm().as_xml(wx_to_std(d->GetPath()));
667                 }
668                 d->Destroy ();
669         }
670
671         wxPreferencesEditor* _config_dialog;
672         ScreensPanel* _screens;
673         KDMTimingPanel* _timing;
674         wxTreeCtrl* _dkdm;
675         typedef std::map<wxTreeItemId, boost::shared_ptr<DKDMBase> > DKDMMap;
676         DKDMMap _dkdm_id;
677         wxButton* _add_dkdm;
678         wxButton* _add_dkdm_folder;
679         wxButton* _remove_dkdm;
680         wxButton* _export_dkdm;
681         wxButton* _create;
682         KDMOutputPanel* _output;
683         JobViewDialog* _job_view;
684 };
685
686 /** @class App
687  *  @brief The magic App class for wxWidgets.
688  */
689 class App : public wxApp
690 {
691 public:
692         App ()
693                 : wxApp ()
694                 , _frame (0)
695         {}
696
697 private:
698
699         bool OnInit ()
700         {
701                 wxSplashScreen* splash = 0;
702
703                 try {
704                         wxInitAllImageHandlers ();
705
706                         Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
707                         Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
708
709                         splash = maybe_show_splash ();
710
711                         SetAppName (_("DCP-o-matic KDM Creator"));
712
713                         if (!wxApp::OnInit()) {
714                                 return false;
715                         }
716
717 #ifdef DCPOMATIC_LINUX
718                         unsetenv ("UBUNTU_MENUPROXY");
719 #endif
720
721 #ifdef DCPOMATIC_OSX
722                         make_foreground_application ();
723 #endif
724
725                         dcpomatic_setup_path_encoding ();
726
727                         /* Enable i18n; this will create a Config object
728                            to look for a force-configured language.  This Config
729                            object will be wrong, however, because dcpomatic_setup
730                            hasn't yet been called and there aren't any filters etc.
731                            set up yet.
732                         */
733                         dcpomatic_setup_i18n ();
734
735                         /* Set things up, including filters etc.
736                            which will now be internationalised correctly.
737                         */
738                         dcpomatic_setup ();
739
740                         /* Force the configuration to be re-loaded correctly next
741                            time it is needed.
742                         */
743                         Config::drop ();
744
745                         _frame = new DOMFrame (_("DCP-o-matic KDM Creator"));
746                         SetTopWindow (_frame);
747                         _frame->Maximize ();
748                         if (splash) {
749                                 splash->Destroy ();
750                                 splash = 0;
751                         }
752                         _frame->Show ();
753
754                         signal_manager = new wxSignalManager (this);
755                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
756                 }
757                 catch (exception& e)
758                 {
759                         if (splash) {
760                                 splash->Destroy ();
761                         }
762                         error_dialog (0, _("DCP-o-matic could not start"), std_to_wx(e.what()));
763                 }
764
765                 return true;
766         }
767
768         /* An unhandled exception has occurred inside the main event loop */
769         bool OnExceptionInMainLoop ()
770         {
771                 try {
772                         throw;
773                 } catch (FileError& e) {
774                         error_dialog (
775                                 0,
776                                 wxString::Format (
777                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
778                                         std_to_wx (e.what()),
779                                         std_to_wx (e.file().string().c_str ())
780                                         )
781                                 );
782                 } catch (exception& e) {
783                         error_dialog (
784                                 0,
785                                 wxString::Format (
786                                         _("An exception occurred: %s.\n\n") + " " + REPORT_PROBLEM,
787                                         std_to_wx (e.what ())
788                                         )
789                                 );
790                 } catch (...) {
791                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
792                 }
793
794                 /* This will terminate the program */
795                 return false;
796         }
797
798         void OnUnhandledException ()
799         {
800                 error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
801         }
802
803         void idle ()
804         {
805                 signal_manager->ui_idle ();
806         }
807
808         void config_failed_to_load ()
809         {
810                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
811         }
812
813         void config_warning (string m)
814         {
815                 message_dialog (_frame, std_to_wx (m));
816         }
817
818         DOMFrame* _frame;
819 };
820
821 IMPLEMENT_APP (App)