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