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