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