Merge.
[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/editable_list.h"
33 #include "lib/config.h"
34 #include "lib/util.h"
35 #include "lib/screen.h"
36 #include "lib/job_manager.h"
37 #include "lib/screen_kdm.h"
38 #include "lib/exceptions.h"
39 #include "lib/cinema_kdms.h"
40 #include "lib/send_kdm_email_job.h"
41 #include "lib/compose.hpp"
42 #include "lib/cinema.h"
43 #include <dcp/encrypted_kdm.h>
44 #include <dcp/decrypted_kdm.h>
45 #include <dcp/exceptions.h>
46 #include <wx/wx.h>
47 #include <wx/preferences.h>
48 #include <wx/filepicker.h>
49 #ifdef __WXOSX__
50 #include <ApplicationServices/ApplicationServices.h>
51 #endif
52 #include <boost/bind.hpp>
53 #include <boost/foreach.hpp>
54
55 #ifdef check
56 #undef check
57 #endif
58
59 using std::exception;
60 using std::list;
61 using std::string;
62 using std::vector;
63 using std::pair;
64 using boost::shared_ptr;
65 using boost::bind;
66 using boost::optional;
67 using boost::ref;
68
69 enum {
70         ID_help_report_a_problem = 1,
71 };
72
73 class KDMFileDialogWrapper : public FileDialogWrapper<dcp::EncryptedKDM>
74 {
75 public:
76         KDMFileDialogWrapper (wxWindow* parent)
77                 : FileDialogWrapper<dcp::EncryptedKDM> (parent, _("Select DKDM file"))
78         {
79
80         }
81
82         optional<dcp::EncryptedKDM> get ()
83         {
84                 try {
85                         return dcp::EncryptedKDM (dcp::file_to_string (wx_to_std (_dialog->GetPath ()), MAX_KDM_SIZE));
86                 } catch (cxml::Error& e) {
87                         error_dialog (_parent, wxString::Format ("This file does not look like a KDM (%s)", std_to_wx (e.what()).data()));
88                 }
89
90                 return optional<dcp::EncryptedKDM> ();
91         }
92 };
93
94 static string
95 column (dcp::EncryptedKDM k)
96 {
97         return String::compose ("%1 (%2)", k.content_title_text(), k.cpl_id());
98 }
99
100 class DOMFrame : public wxFrame
101 {
102 public:
103         DOMFrame (wxString const & title)
104                 : wxFrame (0, -1, title)
105                 , _config_dialog (0)
106                 , _job_view (0)
107         {
108 #if defined(DCPOMATIC_WINDOWS)
109                 if (Config::instance()->win32_console ()) {
110                         AllocConsole();
111
112                         HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
113                         int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
114                         FILE* hf_out = _fdopen(hCrt, "w");
115                         setvbuf(hf_out, NULL, _IONBF, 1);
116                         *stdout = *hf_out;
117
118                         HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
119                         hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
120                         FILE* hf_in = _fdopen(hCrt, "r");
121                         setvbuf(hf_in, NULL, _IONBF, 128);
122                         *stdin = *hf_in;
123
124                         std::cout << "DCP-o-matic KDM creator is starting." << "\n";
125                 }
126 #endif
127
128                 wxMenuBar* bar = new wxMenuBar;
129                 setup_menu (bar);
130                 SetMenuBar (bar);
131
132                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this),             wxID_EXIT);
133                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this),      wxID_PREFERENCES);
134                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this),            wxID_ABOUT);
135                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
136
137                 /* Use a panel as the only child of the Frame so that we avoid
138                    the dark-grey background on Windows.
139                 */
140                 wxPanel* overall_panel = new wxPanel (this, wxID_ANY);
141                 wxBoxSizer* main_sizer = new wxBoxSizer (wxHORIZONTAL);
142
143                 wxBoxSizer* horizontal = new wxBoxSizer (wxHORIZONTAL);
144                 wxBoxSizer* left = new wxBoxSizer (wxVERTICAL);
145                 wxBoxSizer* right = new wxBoxSizer (wxVERTICAL);
146
147                 horizontal->Add (left, 1, wxEXPAND | wxRIGHT, DCPOMATIC_SIZER_X_GAP * 2);
148                 horizontal->Add (right, 1, wxEXPAND);
149
150                 wxFont subheading_font (*wxNORMAL_FONT);
151                 subheading_font.SetWeight (wxFONTWEIGHT_BOLD);
152
153                 wxStaticText* h = new wxStaticText (overall_panel, wxID_ANY, _("Screens"));
154                 h->SetFont (subheading_font);
155                 left->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
156                 _screens = new ScreensPanel (overall_panel);
157                 left->Add (_screens, 1, wxEXPAND | wxBOTTOM, DCPOMATIC_SIZER_Y_GAP);
158
159                 /// TRANSLATORS: translate the word "Timing" here; do not include the "KDM|" prefix
160                 h = new wxStaticText (overall_panel, wxID_ANY, S_("KDM|Timing"));
161                 h->SetFont (subheading_font);
162                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_Y_GAP * 2);
163                 _timing = new KDMTimingPanel (overall_panel);
164                 right->Add (_timing, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
165
166                 h = new wxStaticText (overall_panel, wxID_ANY, _("DKDM"));
167                 h->SetFont (subheading_font);
168                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxTOP, DCPOMATIC_SIZER_Y_GAP * 2);
169
170                 vector<string> columns;
171                 columns.push_back (wx_to_std (_("CPL")));
172                 _dkdm = new EditableList<dcp::EncryptedKDM, KDMFileDialogWrapper> (
173                         overall_panel, columns, bind (&DOMFrame::dkdms, this), bind (&DOMFrame::set_dkdms, this, _1), bind (&column, _1), false
174                         );
175                 right->Add (_dkdm, 0, wxEXPAND | wxALL, DCPOMATIC_SIZER_Y_GAP);
176
177                 h = new wxStaticText (overall_panel, wxID_ANY, _("Output"));
178                 h->SetFont (subheading_font);
179                 right->Add (h, 0, wxALIGN_CENTER_VERTICAL | wxTOP, DCPOMATIC_SIZER_Y_GAP * 2);
180                 /* XXX: hard-coded non-interop here */
181                 _output = new KDMOutputPanel (overall_panel, false);
182                 right->Add (_output, 0, wxALL, DCPOMATIC_SIZER_Y_GAP);
183
184                 _create = new wxButton (overall_panel, wxID_ANY, _("Create KDMs"));
185                 right->Add (_create, 0, wxALL, DCPOMATIC_SIZER_GAP);
186
187                 main_sizer->Add (horizontal, 1, wxALL | wxEXPAND, DCPOMATIC_DIALOG_BORDER);
188                 overall_panel->SetSizer (main_sizer);
189
190                 /* Instantly save any config changes when using a DCP-o-matic GUI */
191                 Config::instance()->Changed.connect (boost::bind (&Config::write, Config::instance ()));
192
193                 _screens->ScreensChanged.connect (boost::bind (&DOMFrame::setup_sensitivity, this));
194                 _create->Bind (wxEVT_BUTTON, bind (&DOMFrame::create_kdms, this));
195                 _dkdm->SelectionChanged.connect (boost::bind (&DOMFrame::setup_sensitivity, this));
196
197                 setup_sensitivity ();
198         }
199
200 private:
201         vector<dcp::EncryptedKDM> dkdms () const
202         {
203                 return Config::instance()->dkdms ();
204         }
205
206         void set_dkdms (vector<dcp::EncryptedKDM> dkdms)
207         {
208                 Config::instance()->set_dkdms (dkdms);
209         }
210
211         void file_exit ()
212         {
213                 /* false here allows the close handler to veto the close request */
214                 Close (false);
215         }
216
217         void edit_preferences ()
218         {
219                 if (!_config_dialog) {
220                         _config_dialog = create_config_dialog ();
221                 }
222                 _config_dialog->Show (this);
223         }
224
225         void help_about ()
226         {
227                 AboutDialog* d = new AboutDialog (this);
228                 d->ShowModal ();
229                 d->Destroy ();
230         }
231
232         void help_report_a_problem ()
233         {
234                 ReportProblemDialog* d = new ReportProblemDialog (this, shared_ptr<Film> ());
235                 if (d->ShowModal () == wxID_OK) {
236                         d->report ();
237                 }
238                 d->Destroy ();
239         }
240
241         void setup_menu (wxMenuBar* m)
242         {
243                 wxMenu* file = new wxMenu;
244
245 #ifdef __WXOSX__
246                 file->Append (wxID_EXIT, _("&Exit"));
247 #else
248                 file->Append (wxID_EXIT, _("&Quit"));
249 #endif
250
251 #ifdef __WXOSX__
252                 file->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
253 #else
254                 wxMenu* edit = new wxMenu;
255                 edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
256 #endif
257
258                 wxMenu* help = new wxMenu;
259 #ifdef __WXOSX__
260                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
261 #else
262                 help->Append (wxID_ABOUT, _("About"));
263 #endif
264                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
265
266                 m->Append (file, _("&File"));
267 #ifndef __WXOSX__
268                 m->Append (edit, _("&Edit"));
269 #endif
270                 m->Append (help, _("&Help"));
271         }
272
273         bool confirm_overwrite (boost::filesystem::path path)
274         {
275                 return confirm_dialog (
276                         this,
277                         wxString::Format (_("File %s already exists.  Do you want to overwrite it?"), std_to_wx(path.string()).data())
278                         );
279         }
280
281         void create_kdms ()
282         {
283                 try {
284                         if (!_dkdm->selection()) {
285                                 return;
286                         }
287
288                         /* Decrypt the DKDM */
289                         dcp::DecryptedKDM decrypted (_dkdm->selection().get(), Config::instance()->decryption_chain()->key().get());
290
291                         /* This is the signer for our new KDMs */
292                         shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
293                         if (!signer->valid ()) {
294                                 throw InvalidSignerError ();
295                         }
296
297                         list<ScreenKDM> screen_kdms;
298                         BOOST_FOREACH (shared_ptr<Screen> i, _screens->screens()) {
299
300                                 if (!i->recipient) {
301                                         continue;
302                                 }
303
304                                 /* Make an empty KDM */
305                                 dcp::DecryptedKDM kdm (
306                                         dcp::LocalTime (_timing->from(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
307                                         dcp::LocalTime (_timing->until(), i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
308                                         decrypted.annotation_text().get_value_or (""),
309                                         decrypted.content_title_text(),
310                                         dcp::LocalTime().as_string()
311                                         );
312
313                                 /* Add keys from the DKDM */
314                                 BOOST_FOREACH (dcp::DecryptedKDMKey const & j, decrypted.keys()) {
315                                         kdm.add_key (j);
316                                 }
317
318                                 /* Encrypt */
319                                 screen_kdms.push_back (ScreenKDM (i, kdm.encrypt (signer, i->recipient.get(), i->trusted_devices, _output->formulation())));
320                         }
321
322                         pair<shared_ptr<Job>, int> result = _output->make (
323                                 screen_kdms, decrypted.content_title_text(), _timing, bind (&DOMFrame::confirm_overwrite, this, _1), shared_ptr<Log> ()
324                                 );
325
326                         if (result.first) {
327                                 JobManager::instance()->add (result.first);
328                                 if (_job_view) {
329                                         _job_view->Destroy ();
330                                         _job_view = 0;
331                                 }
332                                 _job_view = new JobViewDialog (this, _("Send KDM emails"), result.first);
333                                 _job_view->ShowModal ();
334                         }
335
336                         if (result.second > 0) {
337                                 /* XXX: proper plural form support in wxWidgets? */
338                                 wxString s = result.second == 1 ? _("%d KDM written to %s") : _("%d KDMs written to %s");
339                                 message_dialog (
340                                         this,
341                                         wxString::Format (s, result.second, std_to_wx(_output->directory().string()).data())
342                                         );
343                         }
344                 } catch (dcp::NotEncryptedError& e) {
345                         error_dialog (this, _("CPL's content is not encrypted."));
346                 } catch (exception& e) {
347                         error_dialog (this, e.what ());
348                 } catch (...) {
349                         error_dialog (this, _("An unknown exception occurred."));
350                 }
351         }
352
353         void setup_sensitivity ()
354         {
355                 _screens->setup_sensitivity ();
356                 _output->setup_sensitivity ();
357                 _create->Enable (!_screens->screens().empty() && _dkdm->selection());
358         }
359
360         wxPreferencesEditor* _config_dialog;
361         ScreensPanel* _screens;
362         KDMTimingPanel* _timing;
363         EditableList<dcp::EncryptedKDM, KDMFileDialogWrapper>* _dkdm;
364         wxButton* _create;
365         KDMOutputPanel* _output;
366         JobViewDialog* _job_view;
367 };
368
369 /** @class App
370  *  @brief The magic App class for wxWidgets.
371  */
372 class App : public wxApp
373 {
374 public:
375         App ()
376                 : wxApp ()
377                 , _frame (0)
378         {}
379
380 private:
381
382         bool OnInit ()
383         try
384         {
385                 wxInitAllImageHandlers ();
386
387                 SetAppName (_("DCP-o-matic KDM Creator"));
388
389                 if (!wxApp::OnInit()) {
390                         return false;
391                 }
392
393 #ifdef DCPOMATIC_LINUX
394                 unsetenv ("UBUNTU_MENUPROXY");
395 #endif
396
397 #ifdef __WXOSX__
398                 ProcessSerialNumber serial;
399                 GetCurrentProcess (&serial);
400                 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
401 #endif
402
403                 dcpomatic_setup_path_encoding ();
404
405                 /* Enable i18n; this will create a Config object
406                    to look for a force-configured language.  This Config
407                    object will be wrong, however, because dcpomatic_setup
408                    hasn't yet been called and there aren't any filters etc.
409                    set up yet.
410                 */
411                 dcpomatic_setup_i18n ();
412
413                 /* Set things up, including filters etc.
414                    which will now be internationalised correctly.
415                 */
416                 dcpomatic_setup ();
417
418                 /* Force the configuration to be re-loaded correctly next
419                    time it is needed.
420                 */
421                 Config::drop ();
422
423                 _frame = new DOMFrame (_("DCP-o-matic KDM Creator"));
424                 SetTopWindow (_frame);
425                 _frame->Maximize ();
426                 _frame->Show ();
427
428                 signal_manager = new wxSignalManager (this);
429                 Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
430
431                 return true;
432         }
433         catch (exception& e)
434         {
435                 error_dialog (0, wxString::Format ("DCP-o-matic could not start: %s", e.what ()));
436                 return true;
437         }
438
439         /* An unhandled exception has occurred inside the main event loop */
440         bool OnExceptionInMainLoop ()
441         {
442                 try {
443                         throw;
444                 } catch (FileError& e) {
445                         error_dialog (
446                                 0,
447                                 wxString::Format (
448                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
449                                         std_to_wx (e.what()),
450                                         std_to_wx (e.file().string().c_str ())
451                                         )
452                                 );
453                 } catch (exception& e) {
454                         error_dialog (
455                                 0,
456                                 wxString::Format (
457                                         _("An exception occurred: %s.\n\n") + " " + REPORT_PROBLEM,
458                                         std_to_wx (e.what ())
459                                         )
460                                 );
461                 } catch (...) {
462                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
463                 }
464
465                 /* This will terminate the program */
466                 return false;
467         }
468
469         void OnUnhandledException ()
470         {
471                 error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
472         }
473
474         void idle ()
475         {
476                 signal_manager->ui_idle ();
477         }
478
479         DOMFrame* _frame;
480 };
481
482 IMPLEMENT_APP (App)