Rename certificate -> recipient in Screen.
[dcpomatic.git] / src / tools / dcpomatic_kdm.cc
1 /*
2     Copyright (C) 2015 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "wx/config_dialog.h"
21 #include "wx/about_dialog.h"
22 #include "wx/report_problem_dialog.h"
23 #include "wx/file_picker_ctrl.h"
24 #include "wx/wx_util.h"
25 #include "wx/wx_signal_manager.h"
26 #include "wx/screens_panel.h"
27 #include "wx/kdm_timing_panel.h"
28 #include "wx/kdm_output_panel.h"
29 #include "wx/job_view_dialog.h"
30 #include "lib/config.h"
31 #include "lib/util.h"
32 #include "lib/screen.h"
33 #include "lib/job_manager.h"
34 #include "lib/screen_kdm.h"
35 #include "lib/exceptions.h"
36 #include "lib/cinema_kdms.h"
37 #include "lib/send_kdm_email_job.h"
38 #include <dcp/encrypted_kdm.h>
39 #include <dcp/decrypted_kdm.h>
40 #include <dcp/exceptions.h>
41 #include <wx/wx.h>
42 #include <wx/preferences.h>
43 #include <wx/filepicker.h>
44 #ifdef __WXOSX__
45 #include <ApplicationServices/ApplicationServices.h>
46 #endif
47 #include <boost/bind.hpp>
48 #include <boost/foreach.hpp>
49
50 #ifdef check
51 #undef check
52 #endif
53
54 using std::exception;
55 using std::list;
56 using std::string;
57 using boost::shared_ptr;
58 using boost::bind;
59
60 enum {
61         ID_help_report_a_problem = 1,
62 };
63
64 class DOMFrame : public wxFrame
65 {
66 public:
67         DOMFrame (wxString const & title)
68                 : wxFrame (NULL, -1, title)
69                 , _config_dialog (0)
70                 , _job_view (0)
71         {
72 #if defined(DCPOMATIC_WINDOWS)
73                 if (Config::instance()->win32_console ()) {
74                         AllocConsole();
75
76                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
77                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
78                         FILE* hf_out = _fdopen(hCrt, "w");
79                         setvbuf(hf_out, NULL, _IONBF, 1);
80                         *stdout = *hf_out;
81
82                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
83                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
84                         FILE* hf_in = _fdopen(hCrt, "r");
85                         setvbuf(hf_in, NULL, _IONBF, 128);
86                         *stdin = *hf_in;
87
88                         std::cout << "DCP-o-matic KDM creator is starting." << "\n";
89                 }
90 #endif
91
92                 wxMenuBar* bar = new wxMenuBar;
93                 setup_menu (bar);
94                 SetMenuBar (bar);
95
96                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::file_exit, this),             wxID_EXIT);
97                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::edit_preferences, this),      wxID_PREFERENCES);
98                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::help_about, this),            wxID_ABOUT);
99                 Bind (wxEVT_COMMAND_MENU_SELECTED, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
100
101                 /* Use a panel as the only child of the Frame so that we avoid
102                    the dark-grey background on Windows.
103                 */
104                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
105                 wxBoxSizer* main_sizer = new wxBoxSizer (wxHORIZONTAL);
106
107                 wxBoxSizer* vertical = new wxBoxSizer (wxVERTICAL);
108
109                 wxFont subheading_font (*wxNORMAL_FONT);
110                 subheading_font.SetWeight (wxFONTWEIGHT_BOLD);
111
112                 wxStaticText* h = new wxStaticText (overall_panel, wxID_ANY, _("Screens"));
113                 h->SetFont (subheading_font);
114                 vertical->Add (h, 0, wxALIGN_CENTER_VERTICAL);
115                 _screens = new ScreensPanel (overall_panel);
116                 vertical->Add (_screens, 1, wxEXPAND | wxALL, DCPOMATIC_SIZER_Y_GAP);
117
118                 _timing = new KDMTimingPanel (overall_panel);
119                 vertical->Add (_timing, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
120
121                 wxSizer* dkdm = new wxFlexGridSizer (2, DCPOMATIC_SIZER_X_GAP, DCPOMATIC_SIZER_Y_GAP);
122                 add_label_to_sizer (dkdm, overall_panel, _("DKDM file"), true);
123                 _dkdm = new FilePickerCtrl (overall_panel, _("Select a DKDM XML file..."), "*.xml");
124                 dkdm->Add (_dkdm, 1, wxEXPAND);
125                 add_label_to_sizer (dkdm, overall_panel, _("Content title"), true);
126                 _content_title_text = new wxStaticText (overall_panel, wxID_ANY, wxT(""));
127                 dkdm->Add (_content_title_text, 1, wxEXPAND);
128                 add_label_to_sizer (dkdm, overall_panel, _("Annotation"), true);
129                 _annotation_text = new wxStaticText (overall_panel, wxID_ANY, wxT(""));
130                 dkdm->Add (_annotation_text, 1, wxEXPAND);
131                 add_label_to_sizer (dkdm, overall_panel, _("Issue date"), true);
132                 _issue_date = new wxStaticText (overall_panel, wxID_ANY, wxT(""));
133                 dkdm->Add (_issue_date, 1, wxEXPAND);
134                 vertical->Add (dkdm, 0, wxALL, DCPOMATIC_SIZER_X_GAP);
135
136                 h = new wxStaticText (overall_panel, wxID_ANY, _("Output"));
137                 h->SetFont (subheading_font);
138                 vertical->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxTOP, DCPOMATIC_SIZER_Y_GAP * 2);
139                 /* XXX: hard-coded non-interop here */
140                 _output = new KDMOutputPanel (overall_panel, false);
141                 vertical->Add (_output, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
142
143                 _create = new wxButton (overall_panel, wxID_ANY, _("Create KDMs"));
144                 vertical->Add (_create, 0, wxALL, DCPOMATIC_SIZER_GAP);
145
146                 main_sizer->Add (vertical, 1, wxALL, DCPOMATIC_DIALOG_BORDER);
147                 overall_panel->SetSizer (main_sizer);
148
149                 /* Instantly save any config changes when using a DCP-o-matic GUI */
150                 Config::instance()->Changed.connect (boost::bind (&Config::write, Config::instance ()));
151
152                 _screens->ScreensChanged.connect (boost::bind (&DOMFrame::setup_sensitivity, this));
153                 _dkdm->Bind (wxEVT_COMMAND_FILEPICKER_CHANGED, bind (&DOMFrame::dkdm_changed, this));
154                 _create->Bind (wxEVT_COMMAND_BUTTON_CLICKED, bind (&DOMFrame::create_kdms, this));
155
156                 setup_sensitivity ();
157         }
158
159 private:
160         void file_exit ()
161         {
162                 /* false here allows the close handler to veto the close request */
163                 Close (false);
164         }
165
166         void edit_preferences ()
167         {
168                 if (!_config_dialog) {
169                         _config_dialog = create_config_dialog ();
170                 }
171                 _config_dialog->Show (this);
172         }
173
174         void help_about ()
175         {
176                 AboutDialog* d = new AboutDialog (this);
177                 d->ShowModal ();
178                 d->Destroy ();
179         }
180
181         void help_report_a_problem ()
182         {
183                 ReportProblemDialog* d = new ReportProblemDialog (this, shared_ptr<Film> ());
184                 if (d->ShowModal () == wxID_OK) {
185                         d->report ();
186                 }
187                 d->Destroy ();
188         }
189
190         void setup_menu (wxMenuBar* m)
191         {
192                 wxMenu* file = new wxMenu;
193
194 #ifdef __WXOSX__
195                 file->Append (wxID_EXIT, _("&Exit"));
196 #else
197                 file->Append (wxID_EXIT, _("&Quit"));
198 #endif
199
200 #ifdef __WXOSX__
201                 file->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
202 #else
203                 wxMenu* edit = new wxMenu;
204                 edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
205 #endif
206
207                 wxMenu* help = new wxMenu;
208 #ifdef __WXOSX__
209                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
210 #else
211                 help->Append (wxID_ABOUT, _("About"));
212 #endif
213                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
214
215                 m->Append (file, _("&File"));
216 #ifndef __WXOSX__
217                 m->Append (edit, _("&Edit"));
218 #endif
219                 m->Append (help, _("&Help"));
220         }
221
222         void dkdm_changed ()
223         {
224                 if (_dkdm->GetPath().IsEmpty()) {
225                         return;
226                 }
227
228                 try {
229                         dcp::EncryptedKDM encrypted (dcp::file_to_string (wx_to_std (_dkdm->GetPath())));
230                         dcp::DecryptedKDM decrypted (encrypted, Config::instance()->decryption_chain()->key().get());
231                         _annotation_text->Enable (true);
232                         _annotation_text->SetLabel (std_to_wx (decrypted.annotation_text ()));
233                         _content_title_text->Enable (true);
234                         _content_title_text->SetLabel (std_to_wx (decrypted.content_title_text ()));
235                         _issue_date->Enable (true);
236                         _issue_date->SetLabel (std_to_wx (decrypted.issue_date ()));
237                 } catch (exception& e) {
238                         error_dialog (this, wxString::Format (_("Could not load DKDM (%s)"), std_to_wx (e.what()).data()));
239                         _dkdm->SetPath (wxT(""));
240                         _annotation_text->SetLabel (wxT(""));
241                         _annotation_text->Enable (false);
242                         _content_title_text->SetLabel (wxT(""));
243                         _content_title_text->Enable (false);
244                         _issue_date->SetLabel (wxT(""));
245                         _issue_date->Enable (false);
246                 }
247
248                 setup_sensitivity ();
249         }
250
251         void create_kdms ()
252         {
253                 try {
254                         /* Decrypt the DKDM */
255                         dcp::EncryptedKDM encrypted (dcp::file_to_string (wx_to_std (_dkdm->GetPath())));
256                         dcp::DecryptedKDM decrypted (encrypted, Config::instance()->decryption_chain()->key().get());
257
258                         /* This is the signer for our new KDMs */
259                         shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
260                         if (!signer->valid ()) {
261                                 throw InvalidSignerError ();
262                         }
263
264                         list<ScreenKDM> screen_kdms;
265                         BOOST_FOREACH (shared_ptr<Screen> i, _screens->screens()) {
266
267                                 if (!i->recipient) {
268                                         continue;
269                                 }
270
271                                 /* Make an empty KDM */
272                                 dcp::DecryptedKDM kdm (
273                                         _timing->from(), _timing->until(), decrypted.annotation_text(), decrypted.content_title_text(), dcp::LocalTime().as_string()
274                                         );
275
276                                 /* Add keys from the DKDM */
277                                 BOOST_FOREACH (dcp::DecryptedKDMKey const & j, decrypted.keys()) {
278                                         kdm.add_key (j);
279                                 }
280
281                                 /* Encrypt */
282                                 screen_kdms.push_back (ScreenKDM (i, kdm.encrypt (signer, i->recipient.get(), _output->formulation())));
283                         }
284
285                         if (_output->write_to()) {
286                                 ScreenKDM::write_files (decrypted.content_title_text(), screen_kdms, _output->directory());
287                                 /* XXX: proper plural form support in wxWidgets? */
288                                 wxString s = screen_kdms.size() == 1 ? _("%d KDM written to %s") : _("%d KDMs written to %s");
289                                 message_dialog (
290                                         this,
291                                         wxString::Format (s, int(screen_kdms.size()), std_to_wx(_output->directory().string()).data())
292                                         );
293                         } else {
294                                 string film_name = decrypted.annotation_text ();
295                                 if (film_name.empty ()) {
296                                         film_name = decrypted.content_title_text ();
297                                 }
298                                 shared_ptr<Job> job (new SendKDMEmailJob (
299                                                              film_name,
300                                                              decrypted.content_title_text(),
301                                                              _timing->from(), _timing->until(),
302                                                              CinemaKDMs::collect (screen_kdms),
303                                                              shared_ptr<Log> ()
304                                                              ));
305
306                                 JobManager::instance()->add (job);
307                                 if (_job_view) {
308                                         _job_view->Destroy ();
309                                         _job_view = 0;
310                                 }
311                                 _job_view = new JobViewDialog (this, _("Send KDM emails"), job);
312                                 _job_view->ShowModal ();
313                         }
314                 } catch (dcp::NotEncryptedError& e) {
315                         error_dialog (this, _("CPL's content is not encrypted."));
316                 } catch (exception& e) {
317                         error_dialog (this, e.what ());
318                 } catch (...) {
319                         error_dialog (this, _("An unknown exception occurred."));
320                 }
321         }
322
323         void setup_sensitivity ()
324         {
325                 _screens->setup_sensitivity ();
326                 _output->setup_sensitivity ();
327                 _create->Enable (!_screens->screens().empty() && !_dkdm->GetPath().IsEmpty());
328         }
329
330         wxPreferencesEditor* _config_dialog;
331         ScreensPanel* _screens;
332         KDMTimingPanel* _timing;
333         /* I can't seem to clear the value in a wxFilePickerCtrl, so use our own */
334         FilePickerCtrl* _dkdm;
335         wxStaticText* _annotation_text;
336         wxStaticText* _content_title_text;
337         wxStaticText* _issue_date;
338         wxButton* _create;
339         KDMOutputPanel* _output;
340         JobViewDialog* _job_view;
341 };
342
343 /** @class App
344  *  @brief The magic App class for wxWidgets.
345  */
346 class App : public wxApp
347 {
348 public:
349         App ()
350                 : wxApp ()
351                 , _frame (0)
352         {}
353
354 private:
355
356         bool OnInit ()
357         try
358         {
359                 wxInitAllImageHandlers ();
360
361                 SetAppName (_("DCP-o-matic KDM creator"));
362
363                 if (!wxApp::OnInit()) {
364                         return false;
365                 }
366
367 #ifdef DCPOMATIC_LINUX
368                 unsetenv ("UBUNTU_MENUPROXY");
369 #endif
370
371 #ifdef __WXOSX__
372                 ProcessSerialNumber serial;
373                 GetCurrentProcess (&serial);
374                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
375 #endif
376
377                 dcpomatic_setup_path_encoding ();
378
379                 /* Enable i18n; this will create a Config object
380                    to look for a force-configured language.  This Config
381                    object will be wrong, however, because dcpomatic_setup
382                    hasn't yet been called and there aren't any filters etc.
383                    set up yet.
384                 */
385                 dcpomatic_setup_i18n ();
386
387                 /* Set things up, including filters etc.
388                    which will now be internationalised correctly.
389                 */
390                 dcpomatic_setup ();
391
392                 /* Force the configuration to be re-loaded correctly next
393                    time it is needed.
394                 */
395                 Config::drop ();
396
397                 _frame = new DOMFrame (_("DCP-o-matic KDM creator"));
398                 SetTopWindow (_frame);
399                 _frame->Maximize ();
400                 _frame->Show ();
401
402                 signal_manager = new wxSignalManager (this);
403                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
404
405                 return true;
406         }
407         catch (exception& e)
408         {
409                 error_dialog (0, wxString::Format ("DCP-o-matic could not start: %s", e.what ()));
410                 return true;
411         }
412
413         /* An unhandled exception has occurred inside the main event loop */
414         bool OnExceptionInMainLoop ()
415         {
416                 try {
417                         throw;
418                 } catch (FileError& e) {
419                         error_dialog (
420                                 0,
421                                 wxString::Format (
422                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
423                                         std_to_wx (e.what()),
424                                         std_to_wx (e.file().string().c_str ())
425                                         )
426                                 );
427                 } catch (exception& e) {
428                         error_dialog (
429                                 0,
430                                 wxString::Format (
431                                         _("An exception occurred: %s.\n\n") + " " + REPORT_PROBLEM,
432                                         std_to_wx (e.what ())
433                                         )
434                                 );
435                 } catch (...) {
436                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
437                 }
438
439                 /* This will terminate the program */
440                 return false;
441         }
442
443         void OnUnhandledException ()
444         {
445                 error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
446         }
447
448         void idle ()
449         {
450                 signal_manager->ui_idle ();
451         }
452
453         DOMFrame* _frame;
454 };
455
456 IMPLEMENT_APP (App)