874573ce282582d0cc82fcf118f901d12d9f942e
[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 #include <dcp/encrypted_kdm.h>
49 #include <dcp/decrypted_kdm.h>
50 #include <dcp/exceptions.h>
51 #include "lib/warnings.h"
52 DCPOMATIC_DISABLE_WARNINGS
53 #include <wx/wx.h>
54 #include <wx/preferences.h>
55 #include <wx/splash.h>
56 #include <wx/filepicker.h>
57 DCPOMATIC_ENABLE_WARNINGS
58 #ifdef __WXOSX__
59 #include <ApplicationServices/ApplicationServices.h>
60 #endif
61 #include <boost/bind/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 std::shared_ptr;
75 using boost::bind;
76 using boost::optional;
77 using boost::ref;
78 using std::dynamic_pointer_cast;
79 #if BOOST_VERSION >= 106100
80 using namespace boost::placeholders;
81 #endif
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                         shared_ptr<DKDM> dkdm = std::dynamic_pointer_cast<DKDM> (dkdm_base);
312                         if (dkdm) {
313
314                                 /* Decrypt the DKDM */
315                                 dcp::DecryptedKDM decrypted (dkdm->dkdm(), Config::instance()->decryption_chain()->key().get());
316                                 title = decrypted.content_title_text ();
317
318                                 /* This is the signer for our new KDMs */
319                                 shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
320                                 if (!signer->valid ()) {
321                                         throw InvalidSignerError ();
322                                 }
323
324                                 BOOST_FOREACH (shared_ptr<Screen> i, _screens->screens()) {
325
326                                         if (!i->recipient) {
327                                                 continue;
328                                         }
329
330                                         dcp::LocalTime begin(_timing->from(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
331                                         dcp::LocalTime end(_timing->until(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute());
332
333                                         /* Make an empty KDM */
334                                         dcp::DecryptedKDM kdm (
335                                                 begin,
336                                                 end,
337                                                 decrypted.annotation_text().get_value_or (""),
338                                                 decrypted.content_title_text(),
339                                                 dcp::LocalTime().as_string()
340                                                 );
341
342                                         /* Add keys from the DKDM */
343                                         BOOST_FOREACH (dcp::DecryptedKDMKey const & j, decrypted.keys()) {
344                                                 kdm.add_key (j);
345                                         }
346
347                                         dcp::EncryptedKDM const encrypted = kdm.encrypt(
348                                                         signer, i->recipient.get(), i->trusted_device_thumbprints(), _output->formulation(),
349                                                         !_output->forensic_mark_video(), _output->forensic_mark_audio() ? boost::optional<int>() : 0
350                                                         );
351
352                                         dcp::NameFormat::Map name_values;
353                                         name_values['c'] = i->cinema->name;
354                                         name_values['s'] = i->name;
355                                         name_values['f'] = title;
356                                         name_values['b'] = begin.date() + " " + begin.time_of_day(true, false);
357                                         name_values['e'] = end.date() + " " + end.time_of_day(true, false);
358                                         name_values['i'] = encrypted.cpl_id ();
359
360                                         /* Encrypt */
361                                         kdms.push_back (
362                                                 KDMWithMetadataPtr(
363                                                         new KDMWithMetadata(name_values, i->cinema.get(), i->cinema->emails, encrypted)
364                                                         )
365                                                 );
366                                 }
367                         }
368
369                         if (kdms.empty()) {
370                                 return;
371                         }
372
373                         pair<shared_ptr<Job>, int> result = _output->make (
374                                 kdms, title, bind (&DOMFrame::confirm_overwrite, this, _1)
375                                 );
376
377                         if (result.first) {
378                                 JobManager::instance()->add (result.first);
379                                 if (_job_view) {
380                                         _job_view->Destroy ();
381                                         _job_view = 0;
382                                 }
383                                 _job_view = new JobViewDialog (this, _("Send KDM emails"), result.first);
384                                 _job_view->ShowModal ();
385                         }
386
387                         if (result.second > 0) {
388                                 /* XXX: proper plural form support in wxWidgets? */
389                                 wxString s = result.second == 1 ? _("%d KDM written to %s") : _("%d KDMs written to %s");
390                                 message_dialog (
391                                         this,
392                                         wxString::Format (s, result.second, std_to_wx(_output->directory().string()).data())
393                                         );
394                         }
395                 } catch (dcp::NotEncryptedError& e) {
396                         error_dialog (this, _("CPL's content is not encrypted."));
397                 } catch (exception& e) {
398                         error_dialog (this, std_to_wx(e.what()));
399                 } catch (...) {
400                         error_dialog (this, _("An unknown exception occurred."));
401                 }
402         }
403
404         void setup_sensitivity ()
405         {
406                 _screens->setup_sensitivity ();
407                 _output->setup_sensitivity ();
408                 wxArrayTreeItemIds sel;
409                 _dkdm->GetSelections (sel);
410                 shared_ptr<DKDMGroup> group = dynamic_pointer_cast<DKDMGroup>(selected_dkdm());
411                 shared_ptr<DKDM> dkdm = dynamic_pointer_cast<DKDM>(selected_dkdm());
412                 _create->Enable (!_screens->screens().empty() && sel.GetCount() > 0);
413                 _remove_dkdm->Enable (sel.GetCount() > 0 && (!group || group->name() != "root"));
414                 _export_dkdm->Enable (sel.GetCount() > 0 && dkdm);
415         }
416
417         void dkdm_begin_drag (wxTreeEvent& ev)
418         {
419                 ev.Allow ();
420         }
421
422         void dkdm_end_drag (wxTreeEvent& ev)
423         {
424                 DKDMMap::iterator from = _dkdm_id.find (_dkdm->GetSelection ());
425                 DKDMMap::iterator to = _dkdm_id.find (ev.GetItem ());
426                 if (from == _dkdm_id.end() || to == _dkdm_id.end() || from->first == to->first) {
427                         return;
428                 }
429
430                 shared_ptr<DKDMGroup> group = dynamic_pointer_cast<DKDMGroup> (to->second);
431                 if (!group) {
432                         group = to->second->parent();
433                 }
434
435                 DCPOMATIC_ASSERT (group);
436                 DCPOMATIC_ASSERT (from->second->parent ());
437
438                 from->second->parent()->remove (from->second);
439                 add_dkdm_model (from->second, group, dynamic_pointer_cast<DKDM>(to->second));
440
441                 _dkdm->Delete (from->first);
442                 _dkdm_id.erase (from->first);
443                 add_dkdm_view (from->second, dynamic_pointer_cast<DKDM>(to->second) ? to->first : optional<wxTreeItemId>());
444         }
445
446         void add_dkdm_clicked ()
447         {
448                 wxFileDialog* d = new wxFileDialog (this, _("Select DKDM file"));
449                 if (d->ShowModal() == wxID_OK) {
450                         shared_ptr<const dcp::CertificateChain> chain = Config::instance()->decryption_chain();
451                         DCPOMATIC_ASSERT (chain->key());
452
453                         try {
454                                 dcp::EncryptedKDM ekdm(dcp::file_to_string (wx_to_std (d->GetPath ()), MAX_KDM_SIZE));
455                                 /* Decrypt the DKDM to make sure that we can */
456                                 dcp::DecryptedKDM dkdm(ekdm, chain->key().get());
457
458                                 shared_ptr<DKDMBase> new_dkdm(new DKDM(ekdm));
459                                 shared_ptr<DKDMGroup> group = dynamic_pointer_cast<DKDMGroup> (selected_dkdm ());
460                                 if (!group) {
461                                         group = Config::instance()->dkdms ();
462                                 }
463                                 add_dkdm_model (new_dkdm, group);
464                                 add_dkdm_view (new_dkdm);
465                         } catch (dcp::KDMFormatError& e) {
466                                 error_dialog (
467                                         this,
468                                         _("Could not read file as a KDM.  Perhaps it is badly formatted, or not a KDM at all."),
469                                         std_to_wx(e.what())
470                                         );
471                                 return;
472                         } catch (dcp::KDMDecryptionError &) {
473                                 error_dialog (
474                                         this,
475                                         _("Could not decrypt the DKDM.  Perhaps it was not created with the correct certificate.")
476                                         );
477                         } catch (dcp::MiscError& e) {
478                                 error_dialog (
479                                         this,
480                                         _("Could not read file as a KDM.  It is much too large.  Make sure you are loading a DKDM (XML) file."),
481                                         std_to_wx(e.what())
482                                         );
483                         }
484                 }
485                 d->Destroy ();
486         }
487
488         void add_dkdm_folder_clicked ()
489         {
490                 NewDKDMFolderDialog* d = new NewDKDMFolderDialog (this);
491                 if (d->ShowModal() == wxID_OK) {
492                         shared_ptr<DKDMBase> new_dkdm (new DKDMGroup (wx_to_std (d->get ())));
493                         shared_ptr<DKDMGroup> parent = dynamic_pointer_cast<DKDMGroup> (selected_dkdm ());
494                         if (!parent) {
495                                 parent = Config::instance()->dkdms ();
496                         }
497                         add_dkdm_model (new_dkdm, parent);
498                         add_dkdm_view (new_dkdm);
499                 }
500                 d->Destroy ();
501         }
502
503         /** @param dkdm Thing to add.
504          *  @param parent Parent group, or 0.
505          */
506         void add_dkdm_view (shared_ptr<DKDMBase> base, optional<wxTreeItemId> previous = optional<wxTreeItemId>())
507         {
508                 if (!base->parent()) {
509                         /* This is the root group */
510                         _dkdm_id[_dkdm->AddRoot("root")] = base;
511                 } else {
512                         /* Add base to the view */
513                         wxTreeItemId added;
514                         if (previous) {
515                                 added = _dkdm->InsertItem(dkdm_to_id(base->parent()), *previous, std_to_wx(base->name()));
516                         } else {
517                                 added = _dkdm->AppendItem(dkdm_to_id(base->parent()), std_to_wx(base->name()));
518                         }
519                         _dkdm_id[added] = base;
520                 }
521
522                 /* Add children */
523                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup> (base);
524                 if (g) {
525                         BOOST_FOREACH (shared_ptr<DKDMBase> i, g->children()) {
526                                 add_dkdm_view (i);
527                         }
528                 }
529         }
530
531         /** @param group Group to add dkdm to */
532         void add_dkdm_model (shared_ptr<DKDMBase> dkdm, shared_ptr<DKDMGroup> group, shared_ptr<DKDM> previous = shared_ptr<DKDM> ())
533         {
534                 group->add (dkdm, previous);
535                 /* We're messing with a Config-owned object here, so tell it that something has changed.
536                    This isn't nice.
537                 */
538                 Config::instance()->changed ();
539         }
540
541         wxTreeItemId dkdm_to_id (shared_ptr<DKDMBase> dkdm)
542         {
543                 for (DKDMMap::iterator i = _dkdm_id.begin(); i != _dkdm_id.end(); ++i) {
544                         if (i->second == dkdm) {
545                                 return i->first;
546                         }
547                 }
548                 DCPOMATIC_ASSERT (false);
549         }
550
551         void remove_dkdm_clicked ()
552         {
553                 shared_ptr<DKDMBase> removed = selected_dkdm ();
554                 if (!removed) {
555                         return;
556                 }
557
558                 if (NagDialog::maybe_nag (
559                             this, Config::NAG_DELETE_DKDM,
560                             _("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.  "
561                               "Are you sure?"),
562                             true)) {
563                         return;
564                 }
565
566                 _dkdm->Delete (dkdm_to_id (removed));
567                 shared_ptr<DKDMGroup> dkdms = Config::instance()->dkdms ();
568                 dkdms->remove (removed);
569                 Config::instance()->changed ();
570         }
571
572         void export_dkdm_clicked ()
573         {
574                 shared_ptr<DKDMBase> removed = selected_dkdm ();
575                 if (!removed) {
576                         return;
577                 }
578
579                 shared_ptr<DKDM> dkdm = dynamic_pointer_cast<DKDM>(removed);
580                 if (!dkdm) {
581                         return;
582                 }
583
584                 wxFileDialog* d = new wxFileDialog (
585                         this, _("Select DKDM File"), wxEmptyString, wxEmptyString, wxT("XML files (*.xml)|*.xml"),
586                         wxFD_SAVE | wxFD_OVERWRITE_PROMPT
587                         );
588
589                 if (d->ShowModal() == wxID_OK) {
590                         dkdm->dkdm().as_xml(wx_to_std(d->GetPath()));
591                 }
592                 d->Destroy ();
593         }
594
595         wxPreferencesEditor* _config_dialog;
596         ScreensPanel* _screens;
597         KDMTimingPanel* _timing;
598         wxTreeCtrl* _dkdm;
599         typedef std::map<wxTreeItemId, std::shared_ptr<DKDMBase> > DKDMMap;
600         DKDMMap _dkdm_id;
601         wxButton* _add_dkdm;
602         wxButton* _add_dkdm_folder;
603         wxButton* _remove_dkdm;
604         wxButton* _export_dkdm;
605         wxButton* _create;
606         KDMOutputPanel* _output;
607         JobViewDialog* _job_view;
608 };
609
610 /** @class App
611  *  @brief The magic App class for wxWidgets.
612  */
613 class App : public wxApp
614 {
615 public:
616         App ()
617                 : wxApp ()
618                 , _frame (0)
619         {}
620
621 private:
622
623         bool OnInit ()
624         {
625                 wxSplashScreen* splash = 0;
626
627                 try {
628                         wxInitAllImageHandlers ();
629
630                         Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
631                         Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
632
633                         splash = maybe_show_splash ();
634
635                         SetAppName (_("DCP-o-matic KDM Creator"));
636
637                         if (!wxApp::OnInit()) {
638                                 return false;
639                         }
640
641 #ifdef DCPOMATIC_LINUX
642                         unsetenv ("UBUNTU_MENUPROXY");
643 #endif
644
645 #ifdef DCPOMATIC_OSX
646                         make_foreground_application ();
647 #endif
648
649                         dcpomatic_setup_path_encoding ();
650
651                         /* Enable i18n; this will create a Config object
652                            to look for a force-configured language.  This Config
653                            object will be wrong, however, because dcpomatic_setup
654                            hasn't yet been called and there aren't any filters etc.
655                            set up yet.
656                         */
657                         dcpomatic_setup_i18n ();
658
659                         /* Set things up, including filters etc.
660                            which will now be internationalised correctly.
661                         */
662                         dcpomatic_setup ();
663
664                         /* Force the configuration to be re-loaded correctly next
665                            time it is needed.
666                         */
667                         Config::drop ();
668
669                         _frame = new DOMFrame (_("DCP-o-matic KDM Creator"));
670                         SetTopWindow (_frame);
671                         _frame->Maximize ();
672                         if (splash) {
673                                 splash->Destroy ();
674                                 splash = 0;
675                         }
676                         _frame->Show ();
677
678                         signal_manager = new wxSignalManager (this);
679                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
680                 }
681                 catch (exception& e)
682                 {
683                         if (splash) {
684                                 splash->Destroy ();
685                         }
686                         error_dialog (0, _("DCP-o-matic could not start"), std_to_wx(e.what()));
687                 }
688
689                 return true;
690         }
691
692         /* An unhandled exception has occurred inside the main event loop */
693         bool OnExceptionInMainLoop ()
694         {
695                 try {
696                         throw;
697                 } catch (FileError& e) {
698                         error_dialog (
699                                 0,
700                                 wxString::Format (
701                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
702                                         std_to_wx (e.what()),
703                                         std_to_wx (e.file().string().c_str ())
704                                         )
705                                 );
706                 } catch (exception& e) {
707                         error_dialog (
708                                 0,
709                                 wxString::Format (
710                                         _("An exception occurred: %s.\n\n") + " " + REPORT_PROBLEM,
711                                         std_to_wx (e.what ())
712                                         )
713                                 );
714                 } catch (...) {
715                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
716                 }
717
718                 /* This will terminate the program */
719                 return false;
720         }
721
722         void OnUnhandledException ()
723         {
724                 error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
725         }
726
727         void idle ()
728         {
729                 signal_manager->ui_idle ();
730         }
731
732         void config_failed_to_load ()
733         {
734                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
735         }
736
737         void config_warning (string m)
738         {
739                 message_dialog (_frame, std_to_wx (m));
740         }
741
742         DOMFrame* _frame;
743 };
744
745 IMPLEMENT_APP (App)