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