072cc2b0ebc8afa70dacfe1cef2bf23143a45512
[dcpomatic.git] / src / tools / dcpomatic_kdm.cc
1 /*
2     Copyright (C) 2015-2017 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/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 "lib/config.h"
35 #include "lib/util.h"
36 #include "lib/screen.h"
37 #include "lib/job_manager.h"
38 #include "lib/screen_kdm.h"
39 #include "lib/exceptions.h"
40 #include "lib/cinema_kdms.h"
41 #include "lib/send_kdm_email_job.h"
42 #include "lib/compose.hpp"
43 #include "lib/cinema.h"
44 #include "lib/dkdm_wrapper.h"
45 #include <dcp/encrypted_kdm.h>
46 #include <dcp/decrypted_kdm.h>
47 #include <dcp/exceptions.h>
48 #include <wx/wx.h>
49 #include <wx/preferences.h>
50 #include <wx/filepicker.h>
51 #ifdef __WXOSX__
52 #include <ApplicationServices/ApplicationServices.h>
53 #endif
54 #include <boost/bind.hpp>
55 #include <boost/foreach.hpp>
56
57 #ifdef check
58 #undef check
59 #endif
60
61 using std::exception;
62 using std::list;
63 using std::string;
64 using std::vector;
65 using std::pair;
66 using std::map;
67 using boost::shared_ptr;
68 using boost::bind;
69 using boost::optional;
70 using boost::ref;
71 using boost::dynamic_pointer_cast;
72
73 enum {
74         ID_help_report_a_problem = 1,
75 };
76
77 class DOMFrame : public wxFrame
78 {
79 public:
80         DOMFrame (wxString const & title)
81                 : wxFrame (0, -1, title)
82                 , _config_dialog (0)
83                 , _job_view (0)
84         {
85 #if defined(DCPOMATIC_WINDOWS)
86                 if (Config::instance()->win32_console ()) {
87                         AllocConsole();
88
89                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
90                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
91                         FILE* hf_out = _fdopen(hCrt, "w");
92                         setvbuf(hf_out, NULL, _IONBF, 1);
93                         *stdout = *hf_out;
94
95                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
96                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
97                         FILE* hf_in = _fdopen(hCrt, "r");
98                         setvbuf(hf_in, NULL, _IONBF, 128);
99                         *stdin = *hf_in;
100
101                         std::cout << "DCP-o-matic KDM creator is starting." << "\n";
102                 }
103 #endif
104
105                 wxMenuBar* bar = new wxMenuBar;
106                 setup_menu (bar);
107                 SetMenuBar (bar);
108
109                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this),             wxID_EXIT);
110                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this),      wxID_PREFERENCES);
111                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this),            wxID_ABOUT);
112                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
113
114                 /* Use a panel as the only child of the Frame so that we avoid
115                    the dark-grey background on Windows.
116                 */
117                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
118                 wxBoxSizer* main_sizer = new wxBoxSizer (wxHORIZONTAL);
119
120                 wxBoxSizer* horizontal = new wxBoxSizer (wxHORIZONTAL);
121                 wxBoxSizer* left = new wxBoxSizer (wxVERTICAL);
122                 wxBoxSizer* right = new wxBoxSizer (wxVERTICAL);
123
124                 horizontal->Add (left, 1, wxEXPAND | wxRIGHT, DCPOMATIC_SIZER_X_GAP * 2);
125                 horizontal->Add (right, 1, wxEXPAND);
126
127                 wxFont subheading_font (*wxNORMAL_FONT);
128                 subheading_font.SetWeight (wxFONTWEIGHT_BOLD);
129
130                 wxStaticText* h = new wxStaticText (overall_panel, wxID_ANY, _("Screens"));
131                 h->SetFont (subheading_font);
132                 left->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
133                 _screens = new ScreensPanel (overall_panel);
134                 left->Add (_screens, 1, wxEXPAND | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
135
136                 /// TRANSLATORS: translate the word "Timing" here; do not include the "KDM|" prefix
137                 h = new wxStaticText (overall_panel, wxID_ANY, S_("KDM|Timing"));
138                 h->SetFont (subheading_font);
139                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_Y_GAP * 2);
140                 _timing = new KDMTimingPanel (overall_panel);
141                 right->Add (_timing, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
142
143                 h = new wxStaticText (overall_panel, wxID_ANY, _("DKDM"));
144                 h->SetFont (subheading_font);
145                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxTOP, DCPOMATIC_SIZER_Y_GAP * 2);
146                 wxBoxSizer* dkdm_sizer = new wxBoxSizer (wxHORIZONTAL);
147                 _dkdm = new wxTreeCtrl (
148                         overall_panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_HIDE_ROOT | wxTR_HAS_BUTTONS | wxTR_LINES_AT_ROOT
149                 );
150                 dkdm_sizer->Add (_dkdm, 1, wxEXPAND | wxALL, DCPOMATIC_SIZER_Y_GAP);
151                 wxBoxSizer* dkdm_buttons = new wxBoxSizer(wxVERTICAL);
152                 _add_dkdm = new wxButton (overall_panel, wxID_ANY, _("Add..."));
153                 dkdm_buttons->Add (_add_dkdm, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
154                 _add_dkdm_folder = new wxButton (overall_panel, wxID_ANY, _("Add folder..."));
155                 dkdm_buttons->Add (_add_dkdm_folder, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
156                 _remove_dkdm = new wxButton (overall_panel, wxID_ANY, _("Remove"));
157                 dkdm_buttons->Add (_remove_dkdm, 0, wxALL | wxEXPAND, DCPOMATIC_BUTTON_STACK_GAP);
158                 dkdm_sizer->Add (dkdm_buttons, 0, wxEXPAND | wxALL, DCPOMATIC_SIZER_GAP);
159                 right->Add (dkdm_sizer, 1, wxEXPAND | wxALL, DCPOMATIC_SIZER_Y_GAP);
160
161                 add_dkdm_view (Config::instance()->dkdms(), shared_ptr<DKDMGroup> ());
162
163                 h = new wxStaticText (overall_panel, wxID_ANY, _("Output"));
164                 h->SetFont (subheading_font);
165                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxTOP, DCPOMATIC_SIZER_Y_GAP * 2);
166                 /* XXX: hard-coded non-interop here */
167                 _output = new KDMOutputPanel (overall_panel, false);
168                 right->Add (_output, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
169
170                 _create = new wxButton (overall_panel, wxID_ANY, _("Create KDMs"));
171                 right->Add (_create, 0, wxALL, DCPOMATIC_SIZER_GAP);
172
173                 main_sizer->Add (horizontal, 1, wxALL | wxEXPAND, DCPOMATIC_DIALOG_BORDER);
174                 overall_panel->SetSizer (main_sizer);
175
176                 /* Instantly save any config changes when using a DCP-o-matic GUI */
177                 Config::instance()->Changed.connect (boost::bind (&Config::write, Config::instance ()));
178
179                 _screens->ScreensChanged.connect (boost::bind (&DOMFrame::setup_sensitivity, this));
180                 _create->Bind (wxEVT_BUTTON, bind (&DOMFrame::create_kdms, this));
181                 _dkdm->Bind (wxEVT_TREE_SEL_CHANGED, boost::bind (&DOMFrame::setup_sensitivity, this));
182                 _add_dkdm->Bind (wxEVT_BUTTON, bind (&DOMFrame::add_dkdm_clicked, this));
183                 _add_dkdm_folder->Bind (wxEVT_BUTTON, bind (&DOMFrame::add_dkdm_folder_clicked, this));
184                 _remove_dkdm->Bind (wxEVT_BUTTON, bind (&DOMFrame::remove_dkdm_clicked, this));
185
186                 setup_sensitivity ();
187         }
188
189 private:
190         void file_exit ()
191         {
192                 /* false here allows the close handler to veto the close request */
193                 Close (false);
194         }
195
196         void edit_preferences ()
197         {
198                 if (!_config_dialog) {
199                         _config_dialog = create_config_dialog ();
200                 }
201                 _config_dialog->Show (this);
202         }
203
204         void help_about ()
205         {
206                 AboutDialog* d = new AboutDialog (this);
207                 d->ShowModal ();
208                 d->Destroy ();
209         }
210
211         void help_report_a_problem ()
212         {
213                 ReportProblemDialog* d = new ReportProblemDialog (this, shared_ptr<Film> ());
214                 if (d->ShowModal () == wxID_OK) {
215                         d->report ();
216                 }
217                 d->Destroy ();
218         }
219
220         void setup_menu (wxMenuBar* m)
221         {
222                 wxMenu* file = new wxMenu;
223
224 #ifdef __WXOSX__
225                 file->Append (wxID_EXIT, _("&Exit"));
226 #else
227                 file->Append (wxID_EXIT, _("&Quit"));
228 #endif
229
230 #ifdef __WXOSX__
231                 file->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
232 #else
233                 wxMenu* edit = new wxMenu;
234                 edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
235 #endif
236
237                 wxMenu* help = new wxMenu;
238 #ifdef __WXOSX__
239                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
240 #else
241                 help->Append (wxID_ABOUT, _("About"));
242 #endif
243                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
244
245                 m->Append (file, _("&File"));
246 #ifndef __WXOSX__
247                 m->Append (edit, _("&Edit"));
248 #endif
249                 m->Append (help, _("&Help"));
250         }
251
252         bool confirm_overwrite (boost::filesystem::path path)
253         {
254                 return confirm_dialog (
255                         this,
256                         wxString::Format (_("File %s already exists.  Do you want to overwrite it?"), std_to_wx(path.string()).data())
257                         );
258         }
259
260         /** @id if not 0 this is filled in with the wxTreeItemId of the selection */
261         shared_ptr<DKDMBase> selected_dkdm (wxTreeItemId* id = 0) const
262         {
263                 wxArrayTreeItemIds selections;
264                 _dkdm->GetSelections (selections);
265                 if (selections.GetCount() != 1) {
266                         if (id) {
267                                 *id = 0;
268                         }
269                         return shared_ptr<DKDMBase> ();
270                 }
271
272                 if (id) {
273                         *id = selections[0];
274                 }
275
276                 DKDMMap::const_iterator i = _dkdm_id.find (selections[0]);
277                 if (i == _dkdm_id.end()) {
278                         return shared_ptr<DKDMBase> ();
279                 }
280
281                 return i->second;
282         }
283
284         void create_kdms ()
285         {
286                 try {
287                         shared_ptr<DKDMBase> dkdm_base = selected_dkdm ();
288                         if (!dkdm_base) {
289                                 return;
290                         }
291                         shared_ptr<DKDM> dkdm = boost::dynamic_pointer_cast<DKDM> (dkdm_base);
292                         if (!dkdm) {
293                                 return;
294                         }
295
296                         /* Decrypt the DKDM */
297                         dcp::DecryptedKDM decrypted (dkdm->dkdm(), Config::instance()->decryption_chain()->key().get());
298
299                         /* This is the signer for our new KDMs */
300                         shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
301                         if (!signer->valid ()) {
302                                 throw InvalidSignerError ();
303                         }
304
305                         list<ScreenKDM> screen_kdms;
306                         BOOST_FOREACH (shared_ptr<Screen> i, _screens->screens()) {
307
308                                 if (!i->recipient) {
309                                         continue;
310                                 }
311
312                                 /* Make an empty KDM */
313                                 dcp::DecryptedKDM kdm (
314                                         dcp::LocalTime (_timing->from(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
315                                         dcp::LocalTime (_timing->until(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
316                                         decrypted.annotation_text().get_value_or (""),
317                                         decrypted.content_title_text(),
318                                         dcp::LocalTime().as_string()
319                                         );
320
321                                 /* Add keys from the DKDM */
322                                 BOOST_FOREACH (dcp::DecryptedKDMKey const & j, decrypted.keys()) {
323                                         kdm.add_key (j);
324                                 }
325
326                                 /* Encrypt */
327                                 screen_kdms.push_back (ScreenKDM (i, kdm.encrypt (signer, i->recipient.get(), i->trusted_devices, _output->formulation())));
328                         }
329
330                         pair<shared_ptr<Job>, int> result = _output->make (
331                                 screen_kdms, decrypted.content_title_text(), _timing, bind (&DOMFrame::confirm_overwrite, this, _1), shared_ptr<Log> ()
332                                 );
333
334                         if (result.first) {
335                                 JobManager::instance()->add (result.first);
336                                 if (_job_view) {
337                                         _job_view->Destroy ();
338                                         _job_view = 0;
339                                 }
340                                 _job_view = new JobViewDialog (this, _("Send KDM emails"), result.first);
341                                 _job_view->ShowModal ();
342                         }
343
344                         if (result.second > 0) {
345                                 /* XXX: proper plural form support in wxWidgets? */
346                                 wxString s = result.second == 1 ? _("%d KDM written to %s") : _("%d KDMs written to %s");
347                                 message_dialog (
348                                         this,
349                                         wxString::Format (s, result.second, std_to_wx(_output->directory().string()).data())
350                                         );
351                         }
352                 } catch (dcp::NotEncryptedError& e) {
353                         error_dialog (this, _("CPL's content is not encrypted."));
354                 } catch (exception& e) {
355                         error_dialog (this, e.what ());
356                 } catch (...) {
357                         error_dialog (this, _("An unknown exception occurred."));
358                 }
359         }
360
361         void setup_sensitivity ()
362         {
363                 _screens->setup_sensitivity ();
364                 _output->setup_sensitivity ();
365                 wxArrayTreeItemIds sel;
366                 _dkdm->GetSelections (sel);
367                 _create->Enable (!_screens->screens().empty() && sel.GetCount() > 0);
368         }
369
370         void add_dkdm_clicked ()
371         {
372                 wxFileDialog* d = new wxFileDialog (this, _("Select DKDM file"));
373                 if (d->ShowModal() == wxID_OK) {
374                         shared_ptr<DKDMBase> new_dkdm;
375                         try {
376                                 new_dkdm.reset (
377                                         new DKDM (dcp::EncryptedKDM (dcp::file_to_string (wx_to_std (d->GetPath ()), MAX_KDM_SIZE)))
378                                         );
379                         } catch (dcp::KDMFormatError& e) {
380                                 error_dialog (
381                                         this,
382                                         wxString::Format (
383                                                 _("Could not read file as a KDM.  Perhaps it is badly formatted, or not a KDM at all.\n\n%s"),
384                                                 std_to_wx(e.what()).data()
385                                                 )
386                                         );
387                                 return;
388                         }
389
390                         shared_ptr<DKDMGroup> group = dynamic_pointer_cast<DKDMGroup> (selected_dkdm ());
391                         if (!group) {
392                                 group = Config::instance()->dkdms ();
393                         }
394                         add_dkdm_model (new_dkdm, group);
395                         add_dkdm_view (new_dkdm, group);
396                 }
397                 d->Destroy ();
398         }
399
400         void add_dkdm_folder_clicked ()
401         {
402                 NewDKDMFolderDialog* d = new NewDKDMFolderDialog (this);
403                 if (d->ShowModal() == wxID_OK) {
404                         shared_ptr<DKDMBase> new_dkdm (new DKDMGroup (wx_to_std (d->get ())));
405                         shared_ptr<DKDMGroup> parent = dynamic_pointer_cast<DKDMGroup> (selected_dkdm ());
406                         if (!parent) {
407                                 parent = Config::instance()->dkdms ();
408                         }
409                         add_dkdm_model (new_dkdm, parent);
410                         add_dkdm_view (new_dkdm, parent);
411                 }
412                 d->Destroy ();
413         }
414
415         /** @param dkdm Thing to add.
416          *  @param parent Parent group, or 0.
417          */
418         void add_dkdm_view (shared_ptr<DKDMBase> base, shared_ptr<DKDMGroup> parent)
419         {
420                 if (!parent) {
421                         /* This is the root group */
422                         _dkdm_id[_dkdm->AddRoot("root")] = base;
423                 } else {
424                         /* Add base to the view */
425                         _dkdm_id[_dkdm->AppendItem(dkdm_to_id(parent), std_to_wx(base->name()))] = base;
426                 }
427
428                 /* Add children */
429                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup> (base);
430                 if (g) {
431                         BOOST_FOREACH (shared_ptr<DKDMBase> i, g->children()) {
432                                 add_dkdm_view (i, g);
433                         }
434                 }
435         }
436
437         /** @param group Group to add dkdm to */
438         void add_dkdm_model (shared_ptr<DKDMBase> dkdm, shared_ptr<DKDMGroup> group)
439         {
440                 group->add (dkdm);
441                 /* We're messing with a Config-owned object here, so tell it that something has changed.
442                    This isn't nice.
443                 */
444                 Config::instance()->changed ();
445         }
446
447         wxTreeItemId dkdm_to_id (shared_ptr<DKDMBase> dkdm)
448         {
449                 for (DKDMMap::iterator i = _dkdm_id.begin(); i != _dkdm_id.end(); ++i) {
450                         if (i->second == dkdm) {
451                                 return i->first;
452                         }
453                 }
454                 DCPOMATIC_ASSERT (false);
455         }
456
457         void remove_dkdm_clicked ()
458         {
459                 shared_ptr<DKDMBase> removed = selected_dkdm ();
460                 if (!removed) {
461                         return;
462                 }
463
464                 _dkdm->Delete (dkdm_to_id (removed));
465                 shared_ptr<DKDMGroup> dkdms = Config::instance()->dkdms ();
466                 dkdms->remove (removed);
467                 Config::instance()->changed ();
468         }
469
470         wxPreferencesEditor* _config_dialog;
471         ScreensPanel* _screens;
472         KDMTimingPanel* _timing;
473         wxTreeCtrl* _dkdm;
474         typedef std::map<wxTreeItemId, boost::shared_ptr<DKDMBase> > DKDMMap;
475         DKDMMap _dkdm_id;
476         wxButton* _add_dkdm;
477         wxButton* _add_dkdm_folder;
478         wxButton* _remove_dkdm;
479         wxButton* _create;
480         KDMOutputPanel* _output;
481         JobViewDialog* _job_view;
482 };
483
484 /** @class App
485  *  @brief The magic App class for wxWidgets.
486  */
487 class App : public wxApp
488 {
489 public:
490         App ()
491                 : wxApp ()
492                 , _frame (0)
493         {}
494
495 private:
496
497         bool OnInit ()
498         try
499         {
500                 wxInitAllImageHandlers ();
501
502                 SetAppName (_("DCP-o-matic KDM Creator"));
503
504                 if (!wxApp::OnInit()) {
505                         return false;
506                 }
507
508 #ifdef DCPOMATIC_LINUX
509                 unsetenv ("UBUNTU_MENUPROXY");
510 #endif
511
512 #ifdef __WXOSX__
513                 ProcessSerialNumber serial;
514                 GetCurrentProcess (&serial);
515                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
516 #endif
517
518                 dcpomatic_setup_path_encoding ();
519
520                 /* Enable i18n; this will create a Config object
521                    to look for a force-configured language.  This Config
522                    object will be wrong, however, because dcpomatic_setup
523                    hasn't yet been called and there aren't any filters etc.
524                    set up yet.
525                 */
526                 dcpomatic_setup_i18n ();
527
528                 /* Set things up, including filters etc.
529                    which will now be internationalised correctly.
530                 */
531                 dcpomatic_setup ();
532
533                 /* Force the configuration to be re-loaded correctly next
534                    time it is needed.
535                 */
536                 Config::drop ();
537
538                 _frame = new DOMFrame (_("DCP-o-matic KDM Creator"));
539                 SetTopWindow (_frame);
540                 _frame->Maximize ();
541                 _frame->Show ();
542
543                 signal_manager = new wxSignalManager (this);
544                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
545
546                 return true;
547         }
548         catch (exception& e)
549         {
550                 error_dialog (0, wxString::Format ("DCP-o-matic could not start: %s", e.what ()));
551                 return true;
552         }
553
554         /* An unhandled exception has occurred inside the main event loop */
555         bool OnExceptionInMainLoop ()
556         {
557                 try {
558                         throw;
559                 } catch (FileError& e) {
560                         error_dialog (
561                                 0,
562                                 wxString::Format (
563                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
564                                         std_to_wx (e.what()),
565                                         std_to_wx (e.file().string().c_str ())
566                                         )
567                                 );
568                 } catch (exception& e) {
569                         error_dialog (
570                                 0,
571                                 wxString::Format (
572                                         _("An exception occurred: %s.\n\n") + " " + REPORT_PROBLEM,
573                                         std_to_wx (e.what ())
574                                         )
575                                 );
576                 } catch (...) {
577                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
578                 }
579
580                 /* This will terminate the program */
581                 return false;
582         }
583
584         void OnUnhandledException ()
585         {
586                 error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
587         }
588
589         void idle ()
590         {
591                 signal_manager->ui_idle ();
592         }
593
594         DOMFrame* _frame;
595 };
596
597 IMPLEMENT_APP (App)