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