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