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